Matter SDK Coverage Report
Current view: top level - controller - CHIPDeviceController.cpp (source / functions) Coverage Total Hit
Test: SHA:09f6fdf93a7e847a42518c076e487f336877a722 Lines: 0.2 % 1798 3
Test Date: 2025-06-07 07:10:33 Functions: 0.5 % 195 1

            Line data    Source code
       1              : /*
       2              :  *
       3              :  *    Copyright (c) 2020-2024 Project CHIP Authors
       4              :  *    Copyright (c) 2013-2017 Nest Labs, Inc.
       5              :  *    All rights reserved.
       6              :  *
       7              :  *    Licensed under the Apache License, Version 2.0 (the "License");
       8              :  *    you may not use this file except in compliance with the License.
       9              :  *    You may obtain a copy of the License at
      10              :  *
      11              :  *        http://www.apache.org/licenses/LICENSE-2.0
      12              :  *
      13              :  *    Unless required by applicable law or agreed to in writing, software
      14              :  *    distributed under the License is distributed on an "AS IS" BASIS,
      15              :  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      16              :  *    See the License for the specific language governing permissions and
      17              :  *    limitations under the License.
      18              :  */
      19              : 
      20              : /**
      21              :  *    @file
      22              :  *      Implementation of CHIP Device Controller, a common class
      23              :  *      that implements discovery, pairing and provisioning of CHIP
      24              :  *      devices.
      25              :  *
      26              :  */
      27              : 
      28              : // module header, comes first
      29              : #include <controller/CHIPDeviceController.h>
      30              : 
      31              : #include <app-common/zap-generated/ids/Attributes.h>
      32              : #include <app-common/zap-generated/ids/Clusters.h>
      33              : 
      34              : #include <app/InteractionModelEngine.h>
      35              : #include <app/OperationalSessionSetup.h>
      36              : #include <app/server/Dnssd.h>
      37              : #include <controller/CurrentFabricRemover.h>
      38              : #include <controller/InvokeInteraction.h>
      39              : #include <controller/WriteInteraction.h>
      40              : #include <credentials/CHIPCert.h>
      41              : #include <credentials/DeviceAttestationCredsProvider.h>
      42              : #include <crypto/CHIPCryptoPAL.h>
      43              : #include <lib/core/CHIPCore.h>
      44              : #include <lib/core/CHIPEncoding.h>
      45              : #include <lib/core/CHIPSafeCasts.h>
      46              : #include <lib/core/ErrorStr.h>
      47              : #include <lib/core/NodeId.h>
      48              : #include <lib/support/Base64.h>
      49              : #include <lib/support/CHIPArgParser.hpp>
      50              : #include <lib/support/CHIPMem.h>
      51              : #include <lib/support/CodeUtils.h>
      52              : #include <lib/support/PersistentStorageMacros.h>
      53              : #include <lib/support/SafeInt.h>
      54              : #include <lib/support/ScopedBuffer.h>
      55              : #include <lib/support/ThreadOperationalDataset.h>
      56              : #include <lib/support/TimeUtils.h>
      57              : #include <lib/support/logging/CHIPLogging.h>
      58              : #include <messaging/ExchangeContext.h>
      59              : #include <platform/LockTracker.h>
      60              : #include <protocols/secure_channel/MessageCounterManager.h>
      61              : #include <setup_payload/QRCodeSetupPayloadParser.h>
      62              : #include <tracing/macros.h>
      63              : #include <tracing/metric_event.h>
      64              : 
      65              : #if CONFIG_NETWORK_LAYER_BLE
      66              : #include <ble/Ble.h>
      67              : #include <transport/raw/BLE.h>
      68              : #endif
      69              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
      70              : #include <transport/raw/WiFiPAF.h>
      71              : #endif
      72              : 
      73              : #include <algorithm>
      74              : #include <array>
      75              : #include <errno.h>
      76              : #include <inttypes.h>
      77              : #include <limits>
      78              : #include <memory>
      79              : #include <stdint.h>
      80              : #include <stdlib.h>
      81              : #include <string>
      82              : #include <time.h>
      83              : 
      84              : using namespace chip::app;
      85              : using namespace chip::app::Clusters;
      86              : using namespace chip::Inet;
      87              : using namespace chip::System;
      88              : using namespace chip::Transport;
      89              : using namespace chip::Credentials;
      90              : using namespace chip::Crypto;
      91              : using namespace chip::Tracing;
      92              : 
      93              : namespace chip {
      94              : namespace Controller {
      95              : 
      96              : using namespace chip::Encoding;
      97              : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
      98              : using namespace chip::Protocols::UserDirectedCommissioning;
      99              : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
     100              : 
     101           88 : DeviceController::DeviceController()
     102              : {
     103            8 :     mState = State::NotInitialized;
     104            8 : }
     105              : 
     106            0 : CHIP_ERROR DeviceController::Init(ControllerInitParams params)
     107              : {
     108            0 :     assertChipStackLockedByCurrentThread();
     109              : 
     110            0 :     VerifyOrReturnError(mState == State::NotInitialized, CHIP_ERROR_INCORRECT_STATE);
     111            0 :     VerifyOrReturnError(params.systemState != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     112              : 
     113            0 :     VerifyOrReturnError(params.systemState->SystemLayer() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     114            0 :     VerifyOrReturnError(params.systemState->UDPEndPointManager() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     115              : 
     116              : #if CONFIG_NETWORK_LAYER_BLE
     117            0 :     VerifyOrReturnError(params.systemState->BleLayer() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     118              : #endif
     119              : 
     120            0 :     VerifyOrReturnError(params.systemState->TransportMgr() != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     121              : 
     122            0 :     ReturnErrorOnFailure(mDNSResolver.Init(params.systemState->UDPEndPointManager()));
     123            0 :     mDNSResolver.SetDiscoveryDelegate(this);
     124            0 :     RegisterDeviceDiscoveryDelegate(params.deviceDiscoveryDelegate);
     125              : 
     126            0 :     mVendorId = params.controllerVendorId;
     127            0 :     if (params.operationalKeypair != nullptr || !params.controllerNOC.empty() || !params.controllerRCAC.empty())
     128              :     {
     129            0 :         ReturnErrorOnFailure(InitControllerNOCChain(params));
     130              :     }
     131            0 :     else if (params.fabricIndex.HasValue())
     132              :     {
     133            0 :         VerifyOrReturnError(params.systemState->Fabrics()->FabricCount() > 0, CHIP_ERROR_INVALID_ARGUMENT);
     134            0 :         if (params.systemState->Fabrics()->FindFabricWithIndex(params.fabricIndex.Value()) != nullptr)
     135              :         {
     136            0 :             mFabricIndex = params.fabricIndex.Value();
     137              :         }
     138              :         else
     139              :         {
     140            0 :             ChipLogError(Controller, "There is no fabric corresponding to the given fabricIndex");
     141            0 :             return CHIP_ERROR_INVALID_ARGUMENT;
     142              :         }
     143              :     }
     144              : 
     145            0 :     mSystemState = params.systemState->Retain();
     146            0 :     mState       = State::Initialized;
     147              : 
     148            0 :     mRemoveFromFabricTableOnShutdown = params.removeFromFabricTableOnShutdown;
     149            0 :     mDeleteFromFabricTableOnShutdown = params.deleteFromFabricTableOnShutdown;
     150              : 
     151            0 :     if (GetFabricIndex() != kUndefinedFabricIndex)
     152              :     {
     153            0 :         ChipLogProgress(Controller,
     154              :                         "Joined the fabric at index %d. Fabric ID is 0x" ChipLogFormatX64
     155              :                         " (Compressed Fabric ID: " ChipLogFormatX64 ")",
     156              :                         GetFabricIndex(), ChipLogValueX64(GetFabricId()), ChipLogValueX64(GetCompressedFabricId()));
     157              :     }
     158              : 
     159            0 :     return CHIP_NO_ERROR;
     160              : }
     161              : 
     162            0 : CHIP_ERROR DeviceController::InitControllerNOCChain(const ControllerInitParams & params)
     163              : {
     164            0 :     FabricInfo newFabric;
     165            0 :     constexpr uint32_t chipCertAllocatedLen = kMaxCHIPCertLength;
     166            0 :     chip::Platform::ScopedMemoryBuffer<uint8_t> rcacBuf;
     167            0 :     chip::Platform::ScopedMemoryBuffer<uint8_t> icacBuf;
     168            0 :     chip::Platform::ScopedMemoryBuffer<uint8_t> nocBuf;
     169            0 :     Credentials::P256PublicKeySpan rootPublicKeySpan;
     170              :     FabricId fabricId;
     171              :     NodeId nodeId;
     172            0 :     bool hasExternallyOwnedKeypair                   = false;
     173            0 :     Crypto::P256Keypair * externalOperationalKeypair = nullptr;
     174            0 :     VendorId newFabricVendorId                       = params.controllerVendorId;
     175              : 
     176              :     // There are three possibilities here in terms of what happens with our
     177              :     // operational key:
     178              :     // 1) We have an externally owned operational keypair.
     179              :     // 2) We have an operational keypair that the fabric table should clone via
     180              :     //    serialize/deserialize.
     181              :     // 3) We have no keypair at all, and the fabric table has been initialized
     182              :     //    with a key store.
     183            0 :     if (params.operationalKeypair != nullptr)
     184              :     {
     185            0 :         hasExternallyOwnedKeypair  = params.hasExternallyOwnedOperationalKeypair;
     186            0 :         externalOperationalKeypair = params.operationalKeypair;
     187              :     }
     188              : 
     189            0 :     VerifyOrReturnError(rcacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
     190            0 :     VerifyOrReturnError(icacBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
     191            0 :     VerifyOrReturnError(nocBuf.Alloc(chipCertAllocatedLen), CHIP_ERROR_NO_MEMORY);
     192              : 
     193            0 :     MutableByteSpan rcacSpan(rcacBuf.Get(), chipCertAllocatedLen);
     194              : 
     195            0 :     ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerRCAC, rcacSpan));
     196            0 :     ReturnErrorOnFailure(Credentials::ExtractPublicKeyFromChipCert(rcacSpan, rootPublicKeySpan));
     197            0 :     Crypto::P256PublicKey rootPublicKey{ rootPublicKeySpan };
     198              : 
     199            0 :     MutableByteSpan icacSpan;
     200            0 :     if (params.controllerICAC.empty())
     201              :     {
     202            0 :         ChipLogProgress(Controller, "Intermediate CA is not needed");
     203              :     }
     204              :     else
     205              :     {
     206            0 :         icacSpan = MutableByteSpan(icacBuf.Get(), chipCertAllocatedLen);
     207            0 :         ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerICAC, icacSpan));
     208              :     }
     209              : 
     210            0 :     MutableByteSpan nocSpan = MutableByteSpan(nocBuf.Get(), chipCertAllocatedLen);
     211              : 
     212            0 :     ReturnErrorOnFailure(ConvertX509CertToChipCert(params.controllerNOC, nocSpan));
     213            0 :     ReturnErrorOnFailure(ExtractNodeIdFabricIdFromOpCert(nocSpan, &nodeId, &fabricId));
     214              : 
     215            0 :     auto * fabricTable            = params.systemState->Fabrics();
     216            0 :     const FabricInfo * fabricInfo = nullptr;
     217              : 
     218              :     //
     219              :     // When multiple controllers are permitted on the same fabric, we need to find fabrics with
     220              :     // nodeId as an extra discriminant since we can have multiple FabricInfo objects that all
     221              :     // collide on the same fabric. Not doing so may result in a match with an existing FabricInfo
     222              :     // instance that matches the fabric in the provided NOC but is associated with a different NodeId
     223              :     // that is already in use by another active controller instance. That will effectively cause it
     224              :     // to change its identity inadvertently, which is not acceptable.
     225              :     //
     226              :     // TODO: Figure out how to clean up unreclaimed FabricInfos restored from persistent
     227              :     //       storage that are not in use by active DeviceController instances. Also, figure out
     228              :     //       how to reclaim FabricInfo slots when a DeviceController instance is deleted.
     229              :     //
     230            0 :     if (params.permitMultiControllerFabrics)
     231              :     {
     232            0 :         fabricInfo = fabricTable->FindIdentity(rootPublicKey, fabricId, nodeId);
     233              :     }
     234              :     else
     235              :     {
     236            0 :         fabricInfo = fabricTable->FindFabric(rootPublicKey, fabricId);
     237              :     }
     238              : 
     239            0 :     bool fabricFoundInTable = (fabricInfo != nullptr);
     240              : 
     241            0 :     FabricIndex fabricIndex = fabricFoundInTable ? fabricInfo->GetFabricIndex() : kUndefinedFabricIndex;
     242              : 
     243            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
     244              : 
     245            0 :     auto advertiseOperational =
     246            0 :         params.enableServerInteractions ? FabricTable::AdvertiseIdentity::Yes : FabricTable::AdvertiseIdentity::No;
     247              : 
     248              :     //
     249              :     // We permit colliding fabrics when multiple controllers are present on the same logical fabric
     250              :     // since each controller is associated with a unique FabricInfo 'identity' object and consequently,
     251              :     // a unique FabricIndex.
     252              :     //
     253              :     // This sets a flag that will be cleared automatically when the fabric is committed/reverted later
     254              :     // in this function.
     255              :     //
     256            0 :     if (params.permitMultiControllerFabrics)
     257              :     {
     258            0 :         fabricTable->PermitCollidingFabrics();
     259              :     }
     260              : 
     261              :     // We have 4 cases to handle legacy usage of direct operational key injection
     262            0 :     if (externalOperationalKeypair)
     263              :     {
     264              :         // Cases 1 and 2: Injected operational keys
     265              : 
     266              :         // CASE 1: Fabric update with injected key
     267            0 :         if (fabricFoundInTable)
     268              :         {
     269            0 :             err = fabricTable->UpdatePendingFabricWithProvidedOpKey(fabricIndex, nocSpan, icacSpan, externalOperationalKeypair,
     270              :                                                                     hasExternallyOwnedKeypair, advertiseOperational);
     271              :         }
     272              :         else
     273              :         // CASE 2: New fabric with injected key
     274              :         {
     275            0 :             err = fabricTable->AddNewPendingTrustedRootCert(rcacSpan);
     276            0 :             if (err == CHIP_NO_ERROR)
     277              :             {
     278            0 :                 err = fabricTable->AddNewPendingFabricWithProvidedOpKey(nocSpan, icacSpan, newFabricVendorId,
     279              :                                                                         externalOperationalKeypair, hasExternallyOwnedKeypair,
     280              :                                                                         &fabricIndex, advertiseOperational);
     281              :             }
     282              :         }
     283              :     }
     284              :     else
     285              :     {
     286              :         // Cases 3 and 4: OperationalKeystore has the keys
     287              : 
     288              :         // CASE 3: Fabric update with operational keystore
     289            0 :         if (fabricFoundInTable)
     290              :         {
     291            0 :             VerifyOrReturnError(fabricTable->HasOperationalKeyForFabric(fabricIndex), CHIP_ERROR_KEY_NOT_FOUND);
     292              : 
     293            0 :             err = fabricTable->UpdatePendingFabricWithOperationalKeystore(fabricIndex, nocSpan, icacSpan, advertiseOperational);
     294              :         }
     295              :         else
     296              :         // CASE 4: New fabric with operational keystore
     297              :         {
     298            0 :             err = fabricTable->AddNewPendingTrustedRootCert(rcacSpan);
     299            0 :             if (err == CHIP_NO_ERROR)
     300              :             {
     301            0 :                 err = fabricTable->AddNewPendingFabricWithOperationalKeystore(nocSpan, icacSpan, newFabricVendorId, &fabricIndex,
     302              :                                                                               advertiseOperational);
     303              :             }
     304              : 
     305            0 :             if (err == CHIP_NO_ERROR)
     306              :             {
     307              :                 // Now that we know our planned fabric index, verify that the
     308              :                 // keystore has a key for it.
     309            0 :                 if (!fabricTable->HasOperationalKeyForFabric(fabricIndex))
     310              :                 {
     311            0 :                     err = CHIP_ERROR_KEY_NOT_FOUND;
     312              :                 }
     313              :             }
     314              :         }
     315              :     }
     316              : 
     317              :     // Commit after setup, error-out on failure.
     318            0 :     if (err == CHIP_NO_ERROR)
     319              :     {
     320              :         // No need to revert on error: CommitPendingFabricData reverts internally on *any* error.
     321            0 :         err = fabricTable->CommitPendingFabricData();
     322              :     }
     323              :     else
     324              :     {
     325            0 :         fabricTable->RevertPendingFabricData();
     326              :     }
     327              : 
     328            0 :     ReturnErrorOnFailure(err);
     329            0 :     VerifyOrReturnError(fabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INTERNAL);
     330              : 
     331            0 :     mFabricIndex       = fabricIndex;
     332            0 :     mAdvertiseIdentity = advertiseOperational;
     333            0 :     return CHIP_NO_ERROR;
     334            0 : }
     335              : 
     336            0 : CHIP_ERROR DeviceController::UpdateControllerNOCChain(const ByteSpan & noc, const ByteSpan & icac,
     337              :                                                       Crypto::P256Keypair * operationalKeypair,
     338              :                                                       bool operationalKeypairExternalOwned)
     339              : {
     340            0 :     VerifyOrReturnError(mFabricIndex != kUndefinedFabricIndex, CHIP_ERROR_INTERNAL);
     341            0 :     VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INTERNAL);
     342            0 :     FabricTable * fabricTable = mSystemState->Fabrics();
     343            0 :     CHIP_ERROR err            = CHIP_NO_ERROR;
     344              :     FabricId fabricId;
     345              :     NodeId nodeId;
     346            0 :     CATValues oldCats;
     347            0 :     CATValues newCats;
     348            0 :     ReturnErrorOnFailure(ExtractNodeIdFabricIdFromOpCert(noc, &nodeId, &fabricId));
     349            0 :     ReturnErrorOnFailure(fabricTable->FetchCATs(mFabricIndex, oldCats));
     350            0 :     ReturnErrorOnFailure(ExtractCATsFromOpCert(noc, newCats));
     351              : 
     352            0 :     bool needCloseSession = true;
     353            0 :     if (GetFabricInfo()->GetNodeId() == nodeId && oldCats == newCats)
     354              :     {
     355            0 :         needCloseSession = false;
     356              :     }
     357              : 
     358            0 :     if (operationalKeypair != nullptr)
     359              :     {
     360            0 :         err = fabricTable->UpdatePendingFabricWithProvidedOpKey(mFabricIndex, noc, icac, operationalKeypair,
     361              :                                                                 operationalKeypairExternalOwned, mAdvertiseIdentity);
     362              :     }
     363              :     else
     364              :     {
     365            0 :         VerifyOrReturnError(fabricTable->HasOperationalKeyForFabric(mFabricIndex), CHIP_ERROR_KEY_NOT_FOUND);
     366            0 :         err = fabricTable->UpdatePendingFabricWithOperationalKeystore(mFabricIndex, noc, icac, mAdvertiseIdentity);
     367              :     }
     368              : 
     369            0 :     if (err == CHIP_NO_ERROR)
     370              :     {
     371            0 :         err = fabricTable->CommitPendingFabricData();
     372              :     }
     373              :     else
     374              :     {
     375            0 :         fabricTable->RevertPendingFabricData();
     376              :     }
     377              : 
     378            0 :     ReturnErrorOnFailure(err);
     379            0 :     if (needCloseSession)
     380              :     {
     381              :         // If the node id or CATs have changed, our existing CASE sessions are no longer valid,
     382              :         // because the other side will think anything coming over those sessions comes from our
     383              :         // old node ID, and the new CATs might not satisfy the ACL requirements of the other side.
     384            0 :         mSystemState->SessionMgr()->ExpireAllSessionsForFabric(mFabricIndex);
     385              :     }
     386            0 :     ChipLogProgress(Controller, "Controller NOC chain has updated");
     387            0 :     return CHIP_NO_ERROR;
     388              : }
     389              : 
     390            0 : void DeviceController::Shutdown()
     391              : {
     392            0 :     assertChipStackLockedByCurrentThread();
     393              : 
     394            0 :     VerifyOrReturn(mState != State::NotInitialized);
     395              : 
     396              :     // If our state is initialialized it means mSystemState is valid,
     397              :     // and we can use it below before we release our reference to it.
     398            0 :     ChipLogDetail(Controller, "Shutting down the controller");
     399            0 :     mState = State::NotInitialized;
     400              : 
     401            0 :     if (mFabricIndex != kUndefinedFabricIndex)
     402              :     {
     403              :         // Shut down any subscription clients for this fabric.
     404            0 :         app::InteractionModelEngine::GetInstance()->ShutdownSubscriptions(mFabricIndex);
     405              : 
     406              :         // Shut down any ongoing CASE session activity we have.  We're going to
     407              :         // assume that all sessions for our fabric belong to us here.
     408            0 :         mSystemState->CASESessionMgr()->ReleaseSessionsForFabric(mFabricIndex);
     409              : 
     410              :         // Shut down any bdx transfers we're acting as the server for.
     411            0 :         mSystemState->BDXTransferServer()->AbortTransfersForFabric(mFabricIndex);
     412              : 
     413              :         // TODO: The CASE session manager does not shut down existing CASE
     414              :         // sessions.  It just shuts down any ongoing CASE session establishment
     415              :         // we're in the middle of as initiator.  Maybe it should shut down
     416              :         // existing sessions too?
     417            0 :         mSystemState->SessionMgr()->ExpireAllSessionsForFabric(mFabricIndex);
     418              : 
     419            0 :         if (mDeleteFromFabricTableOnShutdown)
     420              :         {
     421            0 :             mSystemState->Fabrics()->Delete(mFabricIndex);
     422              :         }
     423            0 :         else if (mRemoveFromFabricTableOnShutdown)
     424              :         {
     425            0 :             mSystemState->Fabrics()->Forget(mFabricIndex);
     426              :         }
     427              :     }
     428              : 
     429            0 :     mSystemState->Release();
     430            0 :     mSystemState = nullptr;
     431              : 
     432            0 :     mDNSResolver.Shutdown();
     433            0 :     mDeviceDiscoveryDelegate = nullptr;
     434              : }
     435              : 
     436            0 : CHIP_ERROR DeviceController::GetPeerAddressAndPort(NodeId peerId, Inet::IPAddress & addr, uint16_t & port)
     437              : {
     438            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
     439            0 :     Transport::PeerAddress peerAddr;
     440            0 :     ReturnErrorOnFailure(mSystemState->CASESessionMgr()->GetPeerAddress(GetPeerScopedId(peerId), peerAddr));
     441            0 :     addr = peerAddr.GetIPAddress();
     442            0 :     port = peerAddr.GetPort();
     443            0 :     return CHIP_NO_ERROR;
     444              : }
     445              : 
     446            0 : CHIP_ERROR DeviceController::GetPeerAddress(NodeId nodeId, Transport::PeerAddress & addr)
     447              : {
     448            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
     449            0 :     ReturnErrorOnFailure(mSystemState->CASESessionMgr()->GetPeerAddress(GetPeerScopedId(nodeId), addr));
     450              : 
     451            0 :     return CHIP_NO_ERROR;
     452              : }
     453              : 
     454            0 : CHIP_ERROR DeviceController::ComputePASEVerifier(uint32_t iterations, uint32_t setupPincode, const ByteSpan & salt,
     455              :                                                  Spake2pVerifier & outVerifier)
     456              : {
     457            0 :     ReturnErrorOnFailure(PASESession::GeneratePASEVerifier(outVerifier, iterations, salt, /* useRandomPIN= */ false, setupPincode));
     458              : 
     459            0 :     return CHIP_NO_ERROR;
     460              : }
     461              : 
     462            0 : ControllerDeviceInitParams DeviceController::GetControllerDeviceInitParams()
     463              : {
     464              :     return ControllerDeviceInitParams{
     465            0 :         .sessionManager = mSystemState->SessionMgr(),
     466            0 :         .exchangeMgr    = mSystemState->ExchangeMgr(),
     467            0 :     };
     468              : }
     469              : 
     470            0 : DeviceCommissioner::DeviceCommissioner() :
     471            0 :     mOnDeviceConnectedCallback(OnDeviceConnectedFn, this), mOnDeviceConnectionFailureCallback(OnDeviceConnectionFailureFn, this),
     472              : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
     473            0 :     mOnDeviceConnectionRetryCallback(OnDeviceConnectionRetryFn, this),
     474              : #endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
     475            0 :     mDeviceAttestationInformationVerificationCallback(OnDeviceAttestationInformationVerification, this),
     476            0 :     mDeviceNOCChainCallback(OnDeviceNOCChainGeneration, this), mSetUpCodePairer(this)
     477            0 : {}
     478              : 
     479            0 : CHIP_ERROR DeviceCommissioner::Init(CommissionerInitParams params)
     480              : {
     481            0 :     VerifyOrReturnError(params.operationalCredentialsDelegate != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     482            0 :     mOperationalCredentialsDelegate = params.operationalCredentialsDelegate;
     483            0 :     ReturnErrorOnFailure(DeviceController::Init(params));
     484              : 
     485            0 :     mPairingDelegate = params.pairingDelegate;
     486              : 
     487              :     // Configure device attestation validation
     488            0 :     mDeviceAttestationVerifier = params.deviceAttestationVerifier;
     489            0 :     if (mDeviceAttestationVerifier == nullptr)
     490              :     {
     491            0 :         mDeviceAttestationVerifier = Credentials::GetDeviceAttestationVerifier();
     492            0 :         if (mDeviceAttestationVerifier == nullptr)
     493              :         {
     494            0 :             ChipLogError(Controller,
     495              :                          "Missing DeviceAttestationVerifier configuration at DeviceCommissioner init and none set with "
     496              :                          "Credentials::SetDeviceAttestationVerifier()!");
     497            0 :             return CHIP_ERROR_INVALID_ARGUMENT;
     498              :         }
     499              : 
     500              :         // We fell back on a default from singleton accessor.
     501            0 :         ChipLogProgress(Controller,
     502              :                         "*** Missing DeviceAttestationVerifier configuration at DeviceCommissioner init: using global default, "
     503              :                         "consider passing one in CommissionerInitParams.");
     504              :     }
     505              : 
     506            0 :     if (params.defaultCommissioner != nullptr)
     507              :     {
     508            0 :         mDefaultCommissioner = params.defaultCommissioner;
     509              :     }
     510              :     else
     511              :     {
     512            0 :         mDefaultCommissioner = &mAutoCommissioner;
     513              :     }
     514              : 
     515              : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
     516              :     mUdcTransportMgr = chip::Platform::New<UdcTransportMgr>();
     517              :     ReturnErrorOnFailure(mUdcTransportMgr->Init(Transport::UdpListenParameters(mSystemState->UDPEndPointManager())
     518              :                                                     .SetAddressType(Inet::IPAddressType::kIPv6)
     519              :                                                     .SetListenPort(static_cast<uint16_t>(mUdcListenPort))
     520              : #if INET_CONFIG_ENABLE_IPV4
     521              :                                                     ,
     522              :                                                 Transport::UdpListenParameters(mSystemState->UDPEndPointManager())
     523              :                                                     .SetAddressType(Inet::IPAddressType::kIPv4)
     524              :                                                     .SetListenPort(static_cast<uint16_t>(mUdcListenPort))
     525              : #endif // INET_CONFIG_ENABLE_IPV4
     526              :                                                     ));
     527              : 
     528              :     mUdcServer = chip::Platform::New<UserDirectedCommissioningServer>();
     529              :     mUdcTransportMgr->SetSessionManager(mUdcServer);
     530              :     mUdcServer->SetTransportManager(mUdcTransportMgr);
     531              : 
     532              :     mUdcServer->SetInstanceNameResolver(this);
     533              : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
     534              : 
     535            0 :     mSetUpCodePairer.SetSystemLayer(mSystemState->SystemLayer());
     536              : #if CONFIG_NETWORK_LAYER_BLE
     537            0 :     mSetUpCodePairer.SetBleLayer(mSystemState->BleLayer());
     538              : #endif // CONFIG_NETWORK_LAYER_BLE
     539              : 
     540            0 :     return CHIP_NO_ERROR;
     541              : }
     542              : 
     543            0 : void DeviceCommissioner::Shutdown()
     544              : {
     545            0 :     VerifyOrReturn(mState != State::NotInitialized);
     546              : 
     547            0 :     ChipLogDetail(Controller, "Shutting down the commissioner");
     548              : 
     549            0 :     mSetUpCodePairer.StopPairing();
     550              : 
     551              :     // Check to see if pairing in progress before shutting down
     552            0 :     CommissioneeDeviceProxy * device = mDeviceInPASEEstablishment;
     553            0 :     if (device != nullptr && device->IsSessionSetupInProgress())
     554              :     {
     555            0 :         ChipLogDetail(Controller, "Setup in progress, stopping setup before shutting down");
     556            0 :         OnSessionEstablishmentError(CHIP_ERROR_CONNECTION_ABORTED);
     557              :     }
     558              : 
     559            0 :     CancelCommissioningInteractions();
     560              : 
     561              : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
     562              :     if (mUdcTransportMgr != nullptr)
     563              :     {
     564              :         chip::Platform::Delete(mUdcTransportMgr);
     565              :         mUdcTransportMgr = nullptr;
     566              :     }
     567              :     if (mUdcServer != nullptr)
     568              :     {
     569              :         mUdcServer->SetInstanceNameResolver(nullptr);
     570              :         chip::Platform::Delete(mUdcServer);
     571              :         mUdcServer = nullptr;
     572              :     }
     573              : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
     574              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     575            0 :     WiFiPAF::WiFiPAFLayer::GetWiFiPAFLayer().Shutdown(
     576            0 :         [](uint32_t id, WiFiPAF::WiFiPafRole role) { DeviceLayer::ConnectivityMgr().WiFiPAFShutdown(id, role); });
     577              : #endif
     578              : 
     579              :     // Release everything from the commissionee device pool here.
     580              :     // Make sure to use ReleaseCommissioneeDevice so we don't keep dangling
     581              :     // pointers to the device objects.
     582            0 :     mCommissioneeDevicePool.ForEachActiveObject([this](auto * commissioneeDevice) {
     583            0 :         ReleaseCommissioneeDevice(commissioneeDevice);
     584            0 :         return Loop::Continue;
     585              :     });
     586              : 
     587            0 :     DeviceController::Shutdown();
     588              : }
     589              : 
     590            0 : CommissioneeDeviceProxy * DeviceCommissioner::FindCommissioneeDevice(NodeId id)
     591              : {
     592              :     MATTER_TRACE_SCOPE("FindCommissioneeDevice", "DeviceCommissioner");
     593            0 :     CommissioneeDeviceProxy * foundDevice = nullptr;
     594            0 :     mCommissioneeDevicePool.ForEachActiveObject([&](auto * deviceProxy) {
     595            0 :         if (deviceProxy->GetDeviceId() == id)
     596              :         {
     597            0 :             foundDevice = deviceProxy;
     598            0 :             return Loop::Break;
     599              :         }
     600            0 :         return Loop::Continue;
     601              :     });
     602              : 
     603            0 :     return foundDevice;
     604              : }
     605              : 
     606            0 : CommissioneeDeviceProxy * DeviceCommissioner::FindCommissioneeDevice(const Transport::PeerAddress & peerAddress)
     607              : {
     608            0 :     CommissioneeDeviceProxy * foundDevice = nullptr;
     609            0 :     mCommissioneeDevicePool.ForEachActiveObject([&](auto * deviceProxy) {
     610            0 :         if (deviceProxy->GetPeerAddress() == peerAddress)
     611              :         {
     612            0 :             foundDevice = deviceProxy;
     613            0 :             return Loop::Break;
     614              :         }
     615            0 :         return Loop::Continue;
     616              :     });
     617              : 
     618            0 :     return foundDevice;
     619              : }
     620              : 
     621            0 : void DeviceCommissioner::ReleaseCommissioneeDevice(CommissioneeDeviceProxy * device)
     622              : {
     623              : #if CONFIG_NETWORK_LAYER_BLE
     624            0 :     if (mSystemState->BleLayer() != nullptr && device->GetDeviceTransportType() == Transport::Type::kBle)
     625              :     {
     626              :         // We only support one BLE connection, so if this is BLE, close it
     627            0 :         ChipLogProgress(Discovery, "Closing all BLE connections");
     628            0 :         mSystemState->BleLayer()->CloseAllBleConnections();
     629              :     }
     630              : #endif
     631              :     // Make sure that there will be no dangling pointer
     632            0 :     if (mDeviceInPASEEstablishment == device)
     633              :     {
     634            0 :         mDeviceInPASEEstablishment = nullptr;
     635              :     }
     636            0 :     if (mDeviceBeingCommissioned == device)
     637              :     {
     638            0 :         mDeviceBeingCommissioned = nullptr;
     639              :     }
     640              : 
     641              :     // Release the commissionee device after we have nulled out our pointers,
     642              :     // because that can call back in to us with error notifications as the
     643              :     // session is released.
     644            0 :     mCommissioneeDevicePool.ReleaseObject(device);
     645            0 : }
     646              : 
     647            0 : CHIP_ERROR DeviceCommissioner::GetDeviceBeingCommissioned(NodeId deviceId, CommissioneeDeviceProxy ** out_device)
     648              : {
     649            0 :     VerifyOrReturnError(out_device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     650            0 :     CommissioneeDeviceProxy * device = FindCommissioneeDevice(deviceId);
     651              : 
     652            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
     653              : 
     654            0 :     *out_device = device;
     655              : 
     656            0 :     return CHIP_NO_ERROR;
     657              : }
     658              : 
     659            0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, const char * setUpCode, const CommissioningParameters & params,
     660              :                                           DiscoveryType discoveryType, Optional<Dnssd::CommonResolutionData> resolutionData)
     661              : {
     662              :     MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
     663              : 
     664            0 :     if (mDefaultCommissioner == nullptr)
     665              :     {
     666            0 :         ChipLogError(Controller, "No default commissioner is specified");
     667            0 :         return CHIP_ERROR_INCORRECT_STATE;
     668              :     }
     669            0 :     ReturnErrorOnFailure(mDefaultCommissioner->SetCommissioningParameters(params));
     670              : 
     671            0 :     return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kCommission, discoveryType,
     672            0 :                                        resolutionData);
     673              : }
     674              : 
     675            0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, const char * setUpCode, DiscoveryType discoveryType,
     676              :                                           Optional<Dnssd::CommonResolutionData> resolutionData)
     677              : {
     678              :     MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
     679            0 :     return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kCommission, discoveryType,
     680            0 :                                        resolutionData);
     681              : }
     682              : 
     683            0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParameters & params)
     684              : {
     685              :     MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
     686            0 :     ReturnErrorOnFailureWithMetric(kMetricDeviceCommissionerCommission, EstablishPASEConnection(remoteDeviceId, params));
     687            0 :     auto errorCode = Commission(remoteDeviceId);
     688            0 :     VerifyOrDoWithMetric(kMetricDeviceCommissionerCommission, CHIP_NO_ERROR == errorCode, errorCode);
     689            0 :     return errorCode;
     690              : }
     691              : 
     692            0 : CHIP_ERROR DeviceCommissioner::PairDevice(NodeId remoteDeviceId, RendezvousParameters & rendezvousParams,
     693              :                                           CommissioningParameters & commissioningParams)
     694              : {
     695              :     MATTER_TRACE_SCOPE("PairDevice", "DeviceCommissioner");
     696            0 :     ReturnErrorOnFailureWithMetric(kMetricDeviceCommissionerCommission, EstablishPASEConnection(remoteDeviceId, rendezvousParams));
     697            0 :     auto errorCode = Commission(remoteDeviceId, commissioningParams);
     698            0 :     VerifyOrDoWithMetric(kMetricDeviceCommissionerCommission, CHIP_NO_ERROR == errorCode, errorCode);
     699            0 :     return errorCode;
     700              : }
     701              : 
     702            0 : CHIP_ERROR DeviceCommissioner::EstablishPASEConnection(NodeId remoteDeviceId, const char * setUpCode, DiscoveryType discoveryType,
     703              :                                                        Optional<Dnssd::CommonResolutionData> resolutionData)
     704              : {
     705              :     MATTER_TRACE_SCOPE("EstablishPASEConnection", "DeviceCommissioner");
     706            0 :     return mSetUpCodePairer.PairDevice(remoteDeviceId, setUpCode, SetupCodePairerBehaviour::kPaseOnly, discoveryType,
     707            0 :                                        resolutionData);
     708              : }
     709              : 
     710            0 : CHIP_ERROR DeviceCommissioner::EstablishPASEConnection(NodeId remoteDeviceId, RendezvousParameters & params)
     711              : {
     712              :     MATTER_TRACE_SCOPE("EstablishPASEConnection", "DeviceCommissioner");
     713              :     MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissionerPASESession);
     714              : 
     715            0 :     CHIP_ERROR err                     = CHIP_NO_ERROR;
     716            0 :     CommissioneeDeviceProxy * device   = nullptr;
     717            0 :     CommissioneeDeviceProxy * current  = nullptr;
     718            0 :     Transport::PeerAddress peerAddress = Transport::PeerAddress::UDP(Inet::IPAddress::Any);
     719              : 
     720            0 :     Messaging::ExchangeContext * exchangeCtxt = nullptr;
     721            0 :     Optional<SessionHandle> session;
     722              : 
     723            0 :     VerifyOrExit(mState == State::Initialized, err = CHIP_ERROR_INCORRECT_STATE);
     724            0 :     VerifyOrExit(mDeviceInPASEEstablishment == nullptr, err = CHIP_ERROR_INCORRECT_STATE);
     725              : 
     726              :     // TODO(#13940): We need to specify the peer address for BLE transport in bindings.
     727            0 :     if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle ||
     728            0 :         params.GetPeerAddress().GetTransportType() == Transport::Type::kUndefined)
     729              :     {
     730              : #if CONFIG_NETWORK_LAYER_BLE
     731              : #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
     732              :         ConnectBleTransportToSelf();
     733              : #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
     734            0 :         if (!params.HasBleLayer())
     735              :         {
     736            0 :             params.SetPeerAddress(Transport::PeerAddress::BLE());
     737              :         }
     738            0 :         peerAddress = Transport::PeerAddress::BLE();
     739              : #endif // CONFIG_NETWORK_LAYER_BLE
     740              :     }
     741            0 :     else if (params.GetPeerAddress().GetTransportType() == Transport::Type::kTcp ||
     742            0 :              params.GetPeerAddress().GetTransportType() == Transport::Type::kUdp)
     743              :     {
     744            0 :         peerAddress = Transport::PeerAddress::UDP(params.GetPeerAddress().GetIPAddress(), params.GetPeerAddress().GetPort(),
     745            0 :                                                   params.GetPeerAddress().GetInterface());
     746              :     }
     747              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     748            0 :     else if (params.GetPeerAddress().GetTransportType() == Transport::Type::kWiFiPAF)
     749              :     {
     750            0 :         peerAddress = Transport::PeerAddress::WiFiPAF(remoteDeviceId);
     751              :     }
     752              : #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     753              : 
     754            0 :     current = FindCommissioneeDevice(peerAddress);
     755            0 :     if (current != nullptr)
     756              :     {
     757            0 :         if (current->GetDeviceId() == remoteDeviceId)
     758              :         {
     759              :             // We might be able to just reuse its connection if it has one or is
     760              :             // working on one.
     761            0 :             if (current->IsSecureConnected())
     762              :             {
     763            0 :                 if (mPairingDelegate)
     764              :                 {
     765              :                     // We already have an open secure session to this device, call the callback immediately and early return.
     766            0 :                     mPairingDelegate->OnPairingComplete(CHIP_NO_ERROR);
     767              :                 }
     768              :                 MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, CHIP_NO_ERROR);
     769            0 :                 return CHIP_NO_ERROR;
     770              :             }
     771            0 :             if (current->IsSessionSetupInProgress())
     772              :             {
     773              :                 // We're not connected yet, but we're in the process of connecting. Pairing delegate will get a callback when
     774              :                 // connection completes
     775            0 :                 return CHIP_NO_ERROR;
     776              :             }
     777              :         }
     778              : 
     779              :         // Either the consumer wants to assign a different device id to this
     780              :         // peer address now (so we can't reuse the commissionee device we have
     781              :         // already) or something has gone strange. Delete the old device, try
     782              :         // again.
     783            0 :         ChipLogError(Controller, "Found unconnected device, removing");
     784            0 :         ReleaseCommissioneeDevice(current);
     785              :     }
     786              : 
     787            0 :     device = mCommissioneeDevicePool.CreateObject();
     788            0 :     VerifyOrExit(device != nullptr, err = CHIP_ERROR_NO_MEMORY);
     789              : 
     790            0 :     mDeviceInPASEEstablishment = device;
     791            0 :     device->Init(GetControllerDeviceInitParams(), remoteDeviceId, peerAddress);
     792            0 :     device->UpdateDeviceData(params.GetPeerAddress(), params.GetMRPConfig());
     793              : 
     794              : #if CONFIG_NETWORK_LAYER_BLE
     795            0 :     if (params.GetPeerAddress().GetTransportType() == Transport::Type::kBle)
     796              :     {
     797            0 :         if (params.HasConnectionObject())
     798              :         {
     799            0 :             SuccessOrExit(err = mSystemState->BleLayer()->NewBleConnectionByObject(params.GetConnectionObject()));
     800              :         }
     801            0 :         else if (params.HasDiscoveredObject())
     802              :         {
     803              :             // The RendezvousParameters argument needs to be recovered if the search succeed, so save them
     804              :             // for later.
     805            0 :             mRendezvousParametersForDeviceDiscoveredOverBle = params;
     806            0 :             SuccessOrExit(err = mSystemState->BleLayer()->NewBleConnectionByObject(params.GetDiscoveredObject(), this,
     807              :                                                                                    OnDiscoveredDeviceOverBleSuccess,
     808              :                                                                                    OnDiscoveredDeviceOverBleError));
     809            0 :             ExitNow(CHIP_NO_ERROR);
     810              :         }
     811            0 :         else if (params.HasDiscriminator())
     812              :         {
     813              :             // The RendezvousParameters argument needs to be recovered if the search succeed, so save them
     814              :             // for later.
     815            0 :             mRendezvousParametersForDeviceDiscoveredOverBle = params;
     816              : 
     817            0 :             SuccessOrExit(err = mSystemState->BleLayer()->NewBleConnectionByDiscriminator(params.GetSetupDiscriminator().value(),
     818              :                                                                                           this, OnDiscoveredDeviceOverBleSuccess,
     819              :                                                                                           OnDiscoveredDeviceOverBleError));
     820            0 :             ExitNow(CHIP_NO_ERROR);
     821              :         }
     822              :         else
     823              :         {
     824            0 :             ExitNow(err = CHIP_ERROR_INVALID_ARGUMENT);
     825              :         }
     826              :     }
     827              : #endif
     828              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     829            0 :     if (params.GetPeerAddress().GetTransportType() == Transport::Type::kWiFiPAF)
     830              :     {
     831            0 :         if (DeviceLayer::ConnectivityMgr().GetWiFiPAF()->GetWiFiPAFState() != WiFiPAF::State::kConnected)
     832              :         {
     833            0 :             ChipLogProgress(Controller, "WiFi-PAF: Subscribing to the NAN-USD devices, nodeId: %lu",
     834              :                             params.GetPeerAddress().GetRemoteId());
     835            0 :             mRendezvousParametersForDeviceDiscoveredOverWiFiPAF = params;
     836            0 :             auto nodeId                                         = params.GetPeerAddress().GetRemoteId();
     837            0 :             const SetupDiscriminator connDiscriminator(params.GetSetupDiscriminator().value());
     838            0 :             VerifyOrReturnValue(!connDiscriminator.IsShortDiscriminator(), CHIP_ERROR_INVALID_ARGUMENT,
     839              :                                 ChipLogError(Controller, "Error, Long discriminator is required"));
     840            0 :             uint16_t discriminator              = connDiscriminator.GetLongValue();
     841            0 :             WiFiPAF::WiFiPAFSession sessionInfo = { .role          = WiFiPAF::WiFiPafRole::kWiFiPafRole_Subscriber,
     842              :                                                     .nodeId        = nodeId,
     843            0 :                                                     .discriminator = discriminator };
     844            0 :             ReturnErrorOnFailure(
     845              :                 DeviceLayer::ConnectivityMgr().GetWiFiPAF()->AddPafSession(WiFiPAF::PafInfoAccess::kAccNodeInfo, sessionInfo));
     846            0 :             DeviceLayer::ConnectivityMgr().WiFiPAFSubscribe(discriminator, reinterpret_cast<void *>(this),
     847              :                                                             OnWiFiPAFSubscribeComplete, OnWiFiPAFSubscribeError);
     848            0 :             ExitNow(CHIP_NO_ERROR);
     849              :         }
     850              :     }
     851              : #endif
     852            0 :     session = mSystemState->SessionMgr()->CreateUnauthenticatedSession(params.GetPeerAddress(), params.GetMRPConfig());
     853            0 :     VerifyOrExit(session.HasValue(), err = CHIP_ERROR_NO_MEMORY);
     854              : 
     855              :     // Allocate the exchange immediately before calling PASESession::Pair.
     856              :     //
     857              :     // PASESession::Pair takes ownership of the exchange and will free it on
     858              :     // error, but can only do this if it is actually called.  Allocating the
     859              :     // exchange context right before calling Pair ensures that if allocation
     860              :     // succeeds, PASESession has taken ownership.
     861            0 :     exchangeCtxt = mSystemState->ExchangeMgr()->NewContext(session.Value(), &device->GetPairing());
     862            0 :     VerifyOrExit(exchangeCtxt != nullptr, err = CHIP_ERROR_INTERNAL);
     863              : 
     864            0 :     err = device->GetPairing().Pair(*mSystemState->SessionMgr(), params.GetSetupPINCode(), GetLocalMRPConfig(), exchangeCtxt, this);
     865            0 :     SuccessOrExit(err);
     866              : 
     867            0 : exit:
     868            0 :     if (err != CHIP_NO_ERROR)
     869              :     {
     870            0 :         if (device != nullptr)
     871              :         {
     872            0 :             ReleaseCommissioneeDevice(device);
     873              :         }
     874              :         MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, err);
     875              :     }
     876              : 
     877            0 :     return err;
     878            0 : }
     879              : 
     880              : #if CONFIG_NETWORK_LAYER_BLE
     881            0 : void DeviceCommissioner::OnDiscoveredDeviceOverBleSuccess(void * appState, BLE_CONNECTION_OBJECT connObj)
     882              : {
     883            0 :     auto self   = static_cast<DeviceCommissioner *>(appState);
     884            0 :     auto device = self->mDeviceInPASEEstablishment;
     885              : 
     886            0 :     if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kBle)
     887              :     {
     888            0 :         auto remoteId = device->GetDeviceId();
     889              : 
     890            0 :         auto params = self->mRendezvousParametersForDeviceDiscoveredOverBle;
     891            0 :         params.SetConnectionObject(connObj);
     892            0 :         self->mRendezvousParametersForDeviceDiscoveredOverBle = RendezvousParameters();
     893              : 
     894            0 :         self->ReleaseCommissioneeDevice(device);
     895            0 :         LogErrorOnFailure(self->EstablishPASEConnection(remoteId, params));
     896              :     }
     897            0 : }
     898              : 
     899            0 : void DeviceCommissioner::OnDiscoveredDeviceOverBleError(void * appState, CHIP_ERROR err)
     900              : {
     901            0 :     auto self   = static_cast<DeviceCommissioner *>(appState);
     902            0 :     auto device = self->mDeviceInPASEEstablishment;
     903              : 
     904            0 :     if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kBle)
     905              :     {
     906            0 :         self->ReleaseCommissioneeDevice(device);
     907            0 :         self->mRendezvousParametersForDeviceDiscoveredOverBle = RendezvousParameters();
     908              : 
     909              :         // Callback is required when BLE discovery fails, otherwise the caller will always be in a suspended state
     910              :         // A better way to handle it should define a new error code
     911            0 :         if (self->mPairingDelegate != nullptr)
     912              :         {
     913            0 :             self->mPairingDelegate->OnPairingComplete(err);
     914              :         }
     915              :     }
     916            0 : }
     917              : #endif // CONFIG_NETWORK_LAYER_BLE
     918              : 
     919              : #if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
     920            0 : void DeviceCommissioner::OnWiFiPAFSubscribeComplete(void * appState)
     921              : {
     922            0 :     auto self   = reinterpret_cast<DeviceCommissioner *>(appState);
     923            0 :     auto device = self->mDeviceInPASEEstablishment;
     924              : 
     925            0 :     if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kWiFiPAF)
     926              :     {
     927            0 :         ChipLogProgress(Controller, "WiFi-PAF: Subscription Completed, dev_id = %lu", device->GetDeviceId());
     928            0 :         auto remoteId = device->GetDeviceId();
     929            0 :         auto params   = self->mRendezvousParametersForDeviceDiscoveredOverWiFiPAF;
     930              : 
     931            0 :         self->mRendezvousParametersForDeviceDiscoveredOverWiFiPAF = RendezvousParameters();
     932            0 :         self->ReleaseCommissioneeDevice(device);
     933            0 :         LogErrorOnFailure(self->EstablishPASEConnection(remoteId, params));
     934              :     }
     935            0 : }
     936              : 
     937            0 : void DeviceCommissioner::OnWiFiPAFSubscribeError(void * appState, CHIP_ERROR err)
     938              : {
     939            0 :     auto self   = (DeviceCommissioner *) appState;
     940            0 :     auto device = self->mDeviceInPASEEstablishment;
     941              : 
     942            0 :     if (nullptr != device && device->GetDeviceTransportType() == Transport::Type::kWiFiPAF)
     943              :     {
     944            0 :         ChipLogError(Controller, "WiFi-PAF: Subscription Error, id = %lu, err = %" CHIP_ERROR_FORMAT, device->GetDeviceId(),
     945              :                      err.Format());
     946            0 :         self->ReleaseCommissioneeDevice(device);
     947            0 :         self->mRendezvousParametersForDeviceDiscoveredOverWiFiPAF = RendezvousParameters();
     948            0 :         if (self->mPairingDelegate != nullptr)
     949              :         {
     950            0 :             self->mPairingDelegate->OnPairingComplete(err);
     951              :         }
     952              :     }
     953            0 : }
     954              : #endif
     955              : 
     956            0 : CHIP_ERROR DeviceCommissioner::Commission(NodeId remoteDeviceId, CommissioningParameters & params)
     957              : {
     958            0 :     if (mDefaultCommissioner == nullptr)
     959              :     {
     960            0 :         ChipLogError(Controller, "No default commissioner is specified");
     961            0 :         return CHIP_ERROR_INCORRECT_STATE;
     962              :     }
     963            0 :     ReturnErrorOnFailureWithMetric(kMetricDeviceCommissionerCommission, mDefaultCommissioner->SetCommissioningParameters(params));
     964            0 :     auto errorCode = Commission(remoteDeviceId);
     965            0 :     VerifyOrDoWithMetric(kMetricDeviceCommissionerCommission, CHIP_NO_ERROR == errorCode, errorCode);
     966            0 :     return errorCode;
     967              : }
     968              : 
     969            0 : CHIP_ERROR DeviceCommissioner::Commission(NodeId remoteDeviceId)
     970              : {
     971              :     MATTER_TRACE_SCOPE("Commission", "DeviceCommissioner");
     972              : 
     973            0 :     if (mDefaultCommissioner == nullptr)
     974              :     {
     975            0 :         ChipLogError(Controller, "No default commissioner is specified");
     976            0 :         return CHIP_ERROR_INCORRECT_STATE;
     977              :     }
     978              : 
     979            0 :     CommissioneeDeviceProxy * device = FindCommissioneeDevice(remoteDeviceId);
     980            0 :     if (device == nullptr || (!device->IsSecureConnected() && !device->IsSessionSetupInProgress()))
     981              :     {
     982            0 :         ChipLogError(Controller, "Invalid device for commissioning " ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
     983            0 :         return CHIP_ERROR_INCORRECT_STATE;
     984              :     }
     985            0 :     if (!device->IsSecureConnected() && device != mDeviceInPASEEstablishment)
     986              :     {
     987              :         // We should not end up in this state because we won't attempt to establish more than one connection at a time.
     988            0 :         ChipLogError(Controller, "Device is not connected and not being paired " ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
     989            0 :         return CHIP_ERROR_INCORRECT_STATE;
     990              :     }
     991              : 
     992            0 :     if (mCommissioningStage != CommissioningStage::kSecurePairing)
     993              :     {
     994            0 :         ChipLogError(Controller, "Commissioning already in progress (stage '%s') - not restarting",
     995              :                      StageToString(mCommissioningStage));
     996            0 :         return CHIP_ERROR_INCORRECT_STATE;
     997              :     }
     998              : 
     999            0 :     ChipLogProgress(Controller, "Commission called for node ID 0x" ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
    1000              : 
    1001            0 :     mDefaultCommissioner->SetOperationalCredentialsDelegate(mOperationalCredentialsDelegate);
    1002            0 :     if (device->IsSecureConnected())
    1003              :     {
    1004              :         MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissionerCommission);
    1005            0 :         mDefaultCommissioner->StartCommissioning(this, device);
    1006              :     }
    1007              :     else
    1008              :     {
    1009            0 :         mRunCommissioningAfterConnection = true;
    1010              :     }
    1011            0 :     return CHIP_NO_ERROR;
    1012              : }
    1013              : 
    1014              : CHIP_ERROR
    1015            0 : DeviceCommissioner::ContinueCommissioningAfterDeviceAttestation(DeviceProxy * device,
    1016              :                                                                 Credentials::AttestationVerificationResult attestationResult)
    1017              : {
    1018              :     MATTER_TRACE_SCOPE("continueCommissioningDevice", "DeviceCommissioner");
    1019              : 
    1020            0 :     if (mDefaultCommissioner == nullptr)
    1021              :     {
    1022            0 :         ChipLogError(Controller, "No default commissioner is specified");
    1023            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1024              :     }
    1025              : 
    1026            0 :     if (device == nullptr || device != mDeviceBeingCommissioned)
    1027              :     {
    1028            0 :         ChipLogError(Controller, "Invalid device for commissioning %p", device);
    1029            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1030              :     }
    1031            0 :     CommissioneeDeviceProxy * commissioneeDevice = FindCommissioneeDevice(device->GetDeviceId());
    1032            0 :     if (commissioneeDevice == nullptr)
    1033              :     {
    1034            0 :         ChipLogError(Controller, "Couldn't find commissionee device");
    1035            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1036              :     }
    1037            0 :     if (!commissioneeDevice->IsSecureConnected() || commissioneeDevice != mDeviceBeingCommissioned)
    1038              :     {
    1039            0 :         ChipLogError(Controller, "Invalid device for commissioning after attestation failure: 0x" ChipLogFormatX64,
    1040              :                      ChipLogValueX64(commissioneeDevice->GetDeviceId()));
    1041            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1042              :     }
    1043              : 
    1044            0 :     if (mCommissioningStage != CommissioningStage::kAttestationRevocationCheck)
    1045              :     {
    1046            0 :         ChipLogError(Controller, "Commissioning is not attestation verification phase");
    1047            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1048              :     }
    1049              : 
    1050            0 :     ChipLogProgress(Controller, "Continuing commissioning after attestation failure for device ID 0x" ChipLogFormatX64,
    1051              :                     ChipLogValueX64(commissioneeDevice->GetDeviceId()));
    1052              : 
    1053            0 :     if (attestationResult != AttestationVerificationResult::kSuccess)
    1054              :     {
    1055            0 :         ChipLogError(Controller, "Client selected error: %u for failed 'Attestation Information' for device",
    1056              :                      to_underlying(attestationResult));
    1057              : 
    1058            0 :         CommissioningDelegate::CommissioningReport report;
    1059            0 :         report.Set<AttestationErrorInfo>(attestationResult);
    1060            0 :         CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
    1061            0 :     }
    1062              :     else
    1063              :     {
    1064            0 :         ChipLogProgress(Controller, "Overriding attestation failure per client and continuing commissioning");
    1065            0 :         CommissioningStageComplete(CHIP_NO_ERROR);
    1066              :     }
    1067            0 :     return CHIP_NO_ERROR;
    1068              : }
    1069              : 
    1070            0 : CHIP_ERROR DeviceCommissioner::StopPairing(NodeId remoteDeviceId)
    1071              : {
    1072            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1073            0 :     VerifyOrReturnError(remoteDeviceId != kUndefinedNodeId, CHIP_ERROR_INVALID_ARGUMENT);
    1074              : 
    1075            0 :     ChipLogProgress(Controller, "StopPairing called for node ID 0x" ChipLogFormatX64, ChipLogValueX64(remoteDeviceId));
    1076              : 
    1077              :     // If we're still in the process of discovering the device, just stop the SetUpCodePairer
    1078            0 :     if (mSetUpCodePairer.StopPairing(remoteDeviceId))
    1079              :     {
    1080            0 :         mRunCommissioningAfterConnection = false;
    1081            0 :         return CHIP_NO_ERROR;
    1082              :     }
    1083              : 
    1084              :     // Otherwise we might be pairing and / or commissioning it.
    1085            0 :     CommissioneeDeviceProxy * device = FindCommissioneeDevice(remoteDeviceId);
    1086            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_DEVICE_DESCRIPTOR);
    1087              : 
    1088            0 :     if (mDeviceBeingCommissioned == device)
    1089              :     {
    1090            0 :         CancelCommissioningInteractions();
    1091            0 :         CommissioningStageComplete(CHIP_ERROR_CANCELLED);
    1092              :     }
    1093              :     else
    1094              :     {
    1095            0 :         ReleaseCommissioneeDevice(device);
    1096              :     }
    1097            0 :     return CHIP_NO_ERROR;
    1098              : }
    1099              : 
    1100            0 : void DeviceCommissioner::CancelCommissioningInteractions()
    1101              : {
    1102            0 :     if (mReadClient)
    1103              :     {
    1104            0 :         ChipLogDetail(Controller, "Cancelling read request for step '%s'", StageToString(mCommissioningStage));
    1105            0 :         mReadClient.reset(); // destructor cancels
    1106            0 :         mAttributeCache.reset();
    1107              :     }
    1108            0 :     if (mInvokeCancelFn)
    1109              :     {
    1110            0 :         ChipLogDetail(Controller, "Cancelling command invocation for step '%s'", StageToString(mCommissioningStage));
    1111            0 :         mInvokeCancelFn();
    1112            0 :         mInvokeCancelFn = nullptr;
    1113              :     }
    1114            0 :     if (mWriteCancelFn)
    1115              :     {
    1116            0 :         ChipLogDetail(Controller, "Cancelling write request for step '%s'", StageToString(mCommissioningStage));
    1117            0 :         mWriteCancelFn();
    1118            0 :         mWriteCancelFn = nullptr;
    1119              :     }
    1120            0 :     if (mOnDeviceConnectedCallback.IsRegistered())
    1121              :     {
    1122            0 :         ChipLogDetail(Controller, "Cancelling CASE setup for step '%s'", StageToString(mCommissioningStage));
    1123            0 :         CancelCASECallbacks();
    1124              :     }
    1125            0 : }
    1126              : 
    1127            0 : void DeviceCommissioner::CancelCASECallbacks()
    1128              : {
    1129            0 :     mOnDeviceConnectedCallback.Cancel();
    1130            0 :     mOnDeviceConnectionFailureCallback.Cancel();
    1131              : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
    1132            0 :     mOnDeviceConnectionRetryCallback.Cancel();
    1133              : #endif
    1134            0 : }
    1135              : 
    1136            0 : CHIP_ERROR DeviceCommissioner::UnpairDevice(NodeId remoteDeviceId)
    1137              : {
    1138              :     MATTER_TRACE_SCOPE("UnpairDevice", "DeviceCommissioner");
    1139            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1140              : 
    1141            0 :     return AutoCurrentFabricRemover::RemoveCurrentFabric(this, remoteDeviceId);
    1142              : }
    1143              : 
    1144            0 : void DeviceCommissioner::RendezvousCleanup(CHIP_ERROR status)
    1145              : {
    1146            0 :     if (mDeviceInPASEEstablishment != nullptr)
    1147              :     {
    1148              :         // Release the commissionee device. For BLE, this is stored,
    1149              :         // for IP commissioning, we have taken a reference to the
    1150              :         // operational node to send the completion command.
    1151            0 :         ReleaseCommissioneeDevice(mDeviceInPASEEstablishment);
    1152              : 
    1153            0 :         if (mPairingDelegate != nullptr)
    1154              :         {
    1155            0 :             mPairingDelegate->OnPairingComplete(status);
    1156              :         }
    1157              :     }
    1158            0 : }
    1159              : 
    1160            0 : void DeviceCommissioner::OnSessionEstablishmentError(CHIP_ERROR err)
    1161              : {
    1162              :     MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, err);
    1163              : 
    1164            0 :     if (mPairingDelegate != nullptr)
    1165              :     {
    1166            0 :         mPairingDelegate->OnStatusUpdate(DevicePairingDelegate::SecurePairingFailed);
    1167              :     }
    1168              : 
    1169            0 :     RendezvousCleanup(err);
    1170            0 : }
    1171              : 
    1172            0 : void DeviceCommissioner::OnSessionEstablished(const SessionHandle & session)
    1173              : {
    1174              :     // PASE session established.
    1175            0 :     CommissioneeDeviceProxy * device = mDeviceInPASEEstablishment;
    1176              : 
    1177              :     // We are in the callback for this pairing. Reset so we can pair another device.
    1178            0 :     mDeviceInPASEEstablishment = nullptr;
    1179              : 
    1180            0 :     VerifyOrReturn(device != nullptr, OnSessionEstablishmentError(CHIP_ERROR_INVALID_DEVICE_DESCRIPTOR));
    1181              : 
    1182            0 :     CHIP_ERROR err = device->SetConnected(session);
    1183            0 :     if (err != CHIP_NO_ERROR)
    1184              :     {
    1185            0 :         ChipLogError(Controller, "Failed in setting up secure channel: err %s", ErrorStr(err));
    1186            0 :         OnSessionEstablishmentError(err);
    1187            0 :         return;
    1188              :     }
    1189              : 
    1190            0 :     ChipLogDetail(Controller, "Remote device completed SPAKE2+ handshake");
    1191              : 
    1192              :     MATTER_LOG_METRIC_END(kMetricDeviceCommissionerPASESession, CHIP_NO_ERROR);
    1193            0 :     if (mPairingDelegate != nullptr)
    1194              :     {
    1195            0 :         mPairingDelegate->OnPairingComplete(CHIP_NO_ERROR);
    1196              :     }
    1197              : 
    1198            0 :     if (mRunCommissioningAfterConnection)
    1199              :     {
    1200            0 :         mRunCommissioningAfterConnection = false;
    1201              :         MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissionerCommission);
    1202            0 :         mDefaultCommissioner->StartCommissioning(this, device);
    1203              :     }
    1204              : }
    1205              : 
    1206            0 : CHIP_ERROR DeviceCommissioner::SendCertificateChainRequestCommand(DeviceProxy * device,
    1207              :                                                                   Credentials::CertificateType certificateType,
    1208              :                                                                   Optional<System::Clock::Timeout> timeout)
    1209              : {
    1210              :     MATTER_TRACE_SCOPE("SendCertificateChainRequestCommand", "DeviceCommissioner");
    1211            0 :     ChipLogDetail(Controller, "Sending Certificate Chain request to %p device", device);
    1212            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1213              : 
    1214            0 :     OperationalCredentials::Commands::CertificateChainRequest::Type request;
    1215            0 :     request.certificateType = static_cast<OperationalCredentials::CertificateChainTypeEnum>(certificateType);
    1216            0 :     return SendCommissioningCommand(device, request, OnCertificateChainResponse, OnCertificateChainFailureResponse, kRootEndpointId,
    1217            0 :                                     timeout);
    1218              : }
    1219              : 
    1220            0 : void DeviceCommissioner::OnCertificateChainFailureResponse(void * context, CHIP_ERROR error)
    1221              : {
    1222              :     MATTER_TRACE_SCOPE("OnCertificateChainFailureResponse", "DeviceCommissioner");
    1223            0 :     ChipLogProgress(Controller, "Device failed to receive the Certificate Chain request Response: %s", chip::ErrorStr(error));
    1224            0 :     DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
    1225            0 :     commissioner->CommissioningStageComplete(error);
    1226            0 : }
    1227              : 
    1228            0 : void DeviceCommissioner::OnCertificateChainResponse(
    1229              :     void * context, const chip::app::Clusters::OperationalCredentials::Commands::CertificateChainResponse::DecodableType & response)
    1230              : {
    1231              :     MATTER_TRACE_SCOPE("OnCertificateChainResponse", "DeviceCommissioner");
    1232            0 :     ChipLogProgress(Controller, "Received certificate chain from the device");
    1233            0 :     DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
    1234              : 
    1235            0 :     CommissioningDelegate::CommissioningReport report;
    1236            0 :     report.Set<RequestedCertificate>(RequestedCertificate(response.certificate));
    1237              : 
    1238            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
    1239            0 : }
    1240              : 
    1241            0 : CHIP_ERROR DeviceCommissioner::SendAttestationRequestCommand(DeviceProxy * device, const ByteSpan & attestationNonce,
    1242              :                                                              Optional<System::Clock::Timeout> timeout)
    1243              : {
    1244              :     MATTER_TRACE_SCOPE("SendAttestationRequestCommand", "DeviceCommissioner");
    1245            0 :     ChipLogDetail(Controller, "Sending Attestation request to %p device", device);
    1246            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1247              : 
    1248            0 :     OperationalCredentials::Commands::AttestationRequest::Type request;
    1249            0 :     request.attestationNonce = attestationNonce;
    1250              : 
    1251            0 :     ReturnErrorOnFailure(
    1252              :         SendCommissioningCommand(device, request, OnAttestationResponse, OnAttestationFailureResponse, kRootEndpointId, timeout));
    1253            0 :     ChipLogDetail(Controller, "Sent Attestation request, waiting for the Attestation Information");
    1254            0 :     return CHIP_NO_ERROR;
    1255              : }
    1256              : 
    1257            0 : void DeviceCommissioner::OnAttestationFailureResponse(void * context, CHIP_ERROR error)
    1258              : {
    1259              :     MATTER_TRACE_SCOPE("OnAttestationFailureResponse", "DeviceCommissioner");
    1260            0 :     ChipLogProgress(Controller, "Device failed to receive the Attestation Information Response: %s", chip::ErrorStr(error));
    1261            0 :     DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
    1262            0 :     commissioner->CommissioningStageComplete(error);
    1263            0 : }
    1264              : 
    1265            0 : void DeviceCommissioner::OnAttestationResponse(void * context,
    1266              :                                                const OperationalCredentials::Commands::AttestationResponse::DecodableType & data)
    1267              : {
    1268              :     MATTER_TRACE_SCOPE("OnAttestationResponse", "DeviceCommissioner");
    1269            0 :     ChipLogProgress(Controller, "Received Attestation Information from the device");
    1270            0 :     DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
    1271              : 
    1272            0 :     CommissioningDelegate::CommissioningReport report;
    1273            0 :     report.Set<AttestationResponse>(AttestationResponse(data.attestationElements, data.attestationSignature));
    1274            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
    1275            0 : }
    1276              : 
    1277            0 : void DeviceCommissioner::OnDeviceAttestationInformationVerification(
    1278              :     void * context, const Credentials::DeviceAttestationVerifier::AttestationInfo & info, AttestationVerificationResult result)
    1279              : {
    1280              :     MATTER_TRACE_SCOPE("OnDeviceAttestationInformationVerification", "DeviceCommissioner");
    1281            0 :     DeviceCommissioner * commissioner = reinterpret_cast<DeviceCommissioner *>(context);
    1282              : 
    1283            0 :     if (commissioner->mCommissioningStage == CommissioningStage::kAttestationVerification)
    1284              :     {
    1285              :         // Check for revoked DAC Chain before calling delegate. Enter next stage.
    1286              : 
    1287            0 :         CommissioningDelegate::CommissioningReport report;
    1288            0 :         report.Set<AttestationErrorInfo>(result);
    1289              : 
    1290            0 :         return commissioner->CommissioningStageComplete(
    1291            0 :             result == AttestationVerificationResult::kSuccess ? CHIP_NO_ERROR : CHIP_ERROR_INTERNAL, report);
    1292            0 :     }
    1293              : 
    1294            0 :     if (!commissioner->mDeviceBeingCommissioned)
    1295              :     {
    1296            0 :         ChipLogError(Controller, "Device attestation verification result received when we're not commissioning a device");
    1297            0 :         return;
    1298              :     }
    1299              : 
    1300            0 :     auto & params = commissioner->mDefaultCommissioner->GetCommissioningParameters();
    1301            0 :     Credentials::DeviceAttestationDelegate * deviceAttestationDelegate = params.GetDeviceAttestationDelegate();
    1302              : 
    1303            0 :     if (params.GetCompletionStatus().attestationResult.HasValue())
    1304              :     {
    1305            0 :         auto previousResult = params.GetCompletionStatus().attestationResult.Value();
    1306            0 :         if (previousResult != AttestationVerificationResult::kSuccess)
    1307              :         {
    1308            0 :             result = previousResult;
    1309              :         }
    1310              :     }
    1311              : 
    1312            0 :     if (result != AttestationVerificationResult::kSuccess)
    1313              :     {
    1314            0 :         CommissioningDelegate::CommissioningReport report;
    1315            0 :         report.Set<AttestationErrorInfo>(result);
    1316            0 :         if (result == AttestationVerificationResult::kNotImplemented)
    1317              :         {
    1318            0 :             ChipLogError(Controller,
    1319              :                          "Failed in verifying 'Attestation Information' command received from the device due to default "
    1320              :                          "DeviceAttestationVerifier Class not being overridden by a real implementation.");
    1321            0 :             commissioner->CommissioningStageComplete(CHIP_ERROR_NOT_IMPLEMENTED, report);
    1322            0 :             return;
    1323              :         }
    1324              : 
    1325            0 :         ChipLogError(Controller,
    1326              :                      "Failed in verifying 'Attestation Information' command received from the device: err %hu. Look at "
    1327              :                      "AttestationVerificationResult enum to understand the errors",
    1328              :                      static_cast<uint16_t>(result));
    1329              :         // Go look at AttestationVerificationResult enum in src/credentials/attestation_verifier/DeviceAttestationVerifier.h to
    1330              :         // understand the errors.
    1331              : 
    1332              :         // If a device attestation status delegate is installed, delegate handling of failure to the client and let them
    1333              :         // decide on whether to proceed further or not.
    1334            0 :         if (deviceAttestationDelegate)
    1335              :         {
    1336            0 :             commissioner->ExtendArmFailSafeForDeviceAttestation(info, result);
    1337              :         }
    1338              :         else
    1339              :         {
    1340            0 :             commissioner->CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
    1341              :         }
    1342            0 :     }
    1343              :     else
    1344              :     {
    1345            0 :         if (deviceAttestationDelegate && deviceAttestationDelegate->ShouldWaitAfterDeviceAttestation())
    1346              :         {
    1347            0 :             commissioner->ExtendArmFailSafeForDeviceAttestation(info, result);
    1348              :         }
    1349              :         else
    1350              :         {
    1351            0 :             ChipLogProgress(Controller, "Successfully validated 'Attestation Information' command received from the device.");
    1352            0 :             commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    1353              :         }
    1354              :     }
    1355              : }
    1356              : 
    1357            0 : void DeviceCommissioner::OnArmFailSafeExtendedForDeviceAttestation(
    1358              :     void * context, const GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType &)
    1359              : {
    1360            0 :     ChipLogProgress(Controller, "Successfully extended fail-safe timer to handle DA failure");
    1361            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1362              : 
    1363              :     // We have completed our command invoke, but we're not going to finish the
    1364              :     // commissioning step until our client examines the attestation
    1365              :     // information.  Clear out mInvokeCancelFn (which points at the
    1366              :     // CommandSender we just finished using) now, so it's not dangling.
    1367            0 :     commissioner->mInvokeCancelFn = nullptr;
    1368              : 
    1369            0 :     commissioner->HandleDeviceAttestationCompleted();
    1370            0 : }
    1371              : 
    1372            0 : void DeviceCommissioner::HandleDeviceAttestationCompleted()
    1373              : {
    1374            0 :     if (!mDeviceBeingCommissioned)
    1375              :     {
    1376            0 :         return;
    1377              :     }
    1378              : 
    1379            0 :     auto & params                                                      = mDefaultCommissioner->GetCommissioningParameters();
    1380            0 :     Credentials::DeviceAttestationDelegate * deviceAttestationDelegate = params.GetDeviceAttestationDelegate();
    1381            0 :     if (deviceAttestationDelegate)
    1382              :     {
    1383            0 :         ChipLogProgress(Controller, "Device attestation completed, delegating continuation to client");
    1384            0 :         deviceAttestationDelegate->OnDeviceAttestationCompleted(this, mDeviceBeingCommissioned, *mAttestationDeviceInfo,
    1385              :                                                                 mAttestationResult);
    1386              :     }
    1387              :     else
    1388              :     {
    1389            0 :         ChipLogProgress(Controller, "Device attestation failed and no delegate set, failing commissioning");
    1390            0 :         CommissioningDelegate::CommissioningReport report;
    1391            0 :         report.Set<AttestationErrorInfo>(mAttestationResult);
    1392            0 :         CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
    1393            0 :     }
    1394              : }
    1395              : 
    1396            0 : void DeviceCommissioner::OnFailedToExtendedArmFailSafeDeviceAttestation(void * context, CHIP_ERROR error)
    1397              : {
    1398            0 :     ChipLogProgress(Controller, "Failed to extend fail-safe timer to handle attestation failure %s", chip::ErrorStr(error));
    1399            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1400              : 
    1401            0 :     CommissioningDelegate::CommissioningReport report;
    1402            0 :     report.Set<AttestationErrorInfo>(commissioner->mAttestationResult);
    1403            0 :     commissioner->CommissioningStageComplete(CHIP_ERROR_INTERNAL, report);
    1404            0 : }
    1405              : 
    1406            0 : void DeviceCommissioner::OnICDManagementRegisterClientResponse(
    1407              :     void * context, const app::Clusters::IcdManagement::Commands::RegisterClientResponse::DecodableType & data)
    1408              : {
    1409            0 :     CHIP_ERROR err                    = CHIP_NO_ERROR;
    1410            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1411            0 :     VerifyOrExit(commissioner != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
    1412            0 :     VerifyOrExit(commissioner->mCommissioningStage == CommissioningStage::kICDRegistration, err = CHIP_ERROR_INCORRECT_STATE);
    1413            0 :     VerifyOrExit(commissioner->mDeviceBeingCommissioned != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
    1414              : 
    1415            0 :     if (commissioner->mPairingDelegate != nullptr)
    1416              :     {
    1417            0 :         commissioner->mPairingDelegate->OnICDRegistrationComplete(
    1418            0 :             ScopedNodeId(commissioner->mDeviceBeingCommissioned->GetDeviceId(), commissioner->GetFabricIndex()), data.ICDCounter);
    1419              :     }
    1420              : 
    1421            0 : exit:
    1422            0 :     CommissioningDelegate::CommissioningReport report;
    1423            0 :     commissioner->CommissioningStageComplete(err, report);
    1424            0 : }
    1425              : 
    1426            0 : void DeviceCommissioner::OnICDManagementStayActiveResponse(
    1427              :     void * context, const app::Clusters::IcdManagement::Commands::StayActiveResponse::DecodableType & data)
    1428              : {
    1429            0 :     CHIP_ERROR err                    = CHIP_NO_ERROR;
    1430            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1431            0 :     VerifyOrExit(commissioner != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
    1432            0 :     VerifyOrExit(commissioner->mCommissioningStage == CommissioningStage::kICDSendStayActive, err = CHIP_ERROR_INCORRECT_STATE);
    1433            0 :     VerifyOrExit(commissioner->mDeviceBeingCommissioned != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
    1434              : 
    1435            0 :     if (commissioner->mPairingDelegate != nullptr)
    1436              :     {
    1437            0 :         commissioner->mPairingDelegate->OnICDStayActiveComplete(
    1438              : 
    1439            0 :             ScopedNodeId(commissioner->mDeviceBeingCommissioned->GetDeviceId(), commissioner->GetFabricIndex()),
    1440            0 :             data.promisedActiveDuration);
    1441              :     }
    1442              : 
    1443            0 : exit:
    1444            0 :     CommissioningDelegate::CommissioningReport report;
    1445            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
    1446            0 : }
    1447              : 
    1448            0 : bool DeviceCommissioner::ExtendArmFailSafeInternal(DeviceProxy * proxy, CommissioningStage step, uint16_t armFailSafeTimeout,
    1449              :                                                    Optional<System::Clock::Timeout> commandTimeout,
    1450              :                                                    OnExtendFailsafeSuccess onSuccess, OnExtendFailsafeFailure onFailure,
    1451              :                                                    bool fireAndForget)
    1452              : {
    1453              :     using namespace System;
    1454              :     using namespace System::Clock;
    1455            0 :     auto now                = SystemClock().GetMonotonicTimestamp();
    1456            0 :     auto newFailSafeTimeout = now + Seconds16(armFailSafeTimeout);
    1457            0 :     if (newFailSafeTimeout < proxy->GetFailSafeExpirationTimestamp())
    1458              :     {
    1459            0 :         ChipLogProgress(
    1460              :             Controller, "Skipping arming failsafe: new time (%u seconds from now) before old time (%u seconds from now)",
    1461              :             armFailSafeTimeout, std::chrono::duration_cast<Seconds16>(proxy->GetFailSafeExpirationTimestamp() - now).count());
    1462            0 :         return false;
    1463              :     }
    1464              : 
    1465            0 :     uint64_t breadcrumb = static_cast<uint64_t>(step);
    1466            0 :     GeneralCommissioning::Commands::ArmFailSafe::Type request;
    1467            0 :     request.expiryLengthSeconds = armFailSafeTimeout;
    1468            0 :     request.breadcrumb          = breadcrumb;
    1469            0 :     ChipLogProgress(Controller, "Arming failsafe (%u seconds)", request.expiryLengthSeconds);
    1470            0 :     CHIP_ERROR err = SendCommissioningCommand(proxy, request, onSuccess, onFailure, kRootEndpointId, commandTimeout, fireAndForget);
    1471            0 :     if (err != CHIP_NO_ERROR)
    1472              :     {
    1473            0 :         onFailure((!fireAndForget) ? this : nullptr, err);
    1474            0 :         return true; // we have called onFailure already
    1475              :     }
    1476              : 
    1477              :     // Note: The stored timestamp may become invalid if we fail asynchronously
    1478            0 :     proxy->SetFailSafeExpirationTimestamp(newFailSafeTimeout);
    1479            0 :     return true;
    1480              : }
    1481              : 
    1482            0 : void DeviceCommissioner::ExtendArmFailSafeForDeviceAttestation(const Credentials::DeviceAttestationVerifier::AttestationInfo & info,
    1483              :                                                                Credentials::AttestationVerificationResult result)
    1484              : {
    1485            0 :     mAttestationResult = result;
    1486              : 
    1487            0 :     auto & params                                                      = mDefaultCommissioner->GetCommissioningParameters();
    1488            0 :     Credentials::DeviceAttestationDelegate * deviceAttestationDelegate = params.GetDeviceAttestationDelegate();
    1489              : 
    1490            0 :     mAttestationDeviceInfo = Platform::MakeUnique<Credentials::DeviceAttestationVerifier::AttestationDeviceInfo>(info);
    1491              : 
    1492            0 :     auto expiryLengthSeconds      = deviceAttestationDelegate->FailSafeExpiryTimeoutSecs();
    1493            0 :     bool waitForFailsafeExtension = expiryLengthSeconds.HasValue();
    1494            0 :     if (waitForFailsafeExtension)
    1495              :     {
    1496            0 :         ChipLogProgress(Controller, "Changing fail-safe timer to %u seconds to handle DA failure", expiryLengthSeconds.Value());
    1497              :         // Per spec, anything we do with the fail-safe armed must not time out
    1498              :         // in less than kMinimumCommissioningStepTimeout.
    1499              :         waitForFailsafeExtension =
    1500            0 :             ExtendArmFailSafeInternal(mDeviceBeingCommissioned, mCommissioningStage, expiryLengthSeconds.Value(),
    1501            0 :                                       MakeOptional(kMinimumCommissioningStepTimeout), OnArmFailSafeExtendedForDeviceAttestation,
    1502              :                                       OnFailedToExtendedArmFailSafeDeviceAttestation, /* fireAndForget = */ false);
    1503              :     }
    1504              :     else
    1505              :     {
    1506            0 :         ChipLogProgress(Controller, "Proceeding without changing fail-safe timer value as delegate has not set it");
    1507              :     }
    1508              : 
    1509            0 :     if (!waitForFailsafeExtension)
    1510              :     {
    1511            0 :         HandleDeviceAttestationCompleted();
    1512              :     }
    1513            0 : }
    1514              : 
    1515            0 : CHIP_ERROR DeviceCommissioner::ValidateAttestationInfo(const Credentials::DeviceAttestationVerifier::AttestationInfo & info)
    1516              : {
    1517              :     MATTER_TRACE_SCOPE("ValidateAttestationInfo", "DeviceCommissioner");
    1518            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1519            0 :     VerifyOrReturnError(mDeviceAttestationVerifier != nullptr, CHIP_ERROR_INCORRECT_STATE);
    1520              : 
    1521            0 :     mDeviceAttestationVerifier->VerifyAttestationInformation(info, &mDeviceAttestationInformationVerificationCallback);
    1522              : 
    1523              :     // TODO: Validate Firmware Information
    1524              : 
    1525            0 :     return CHIP_NO_ERROR;
    1526              : }
    1527              : 
    1528              : CHIP_ERROR
    1529            0 : DeviceCommissioner::CheckForRevokedDACChain(const Credentials::DeviceAttestationVerifier::AttestationInfo & info)
    1530              : {
    1531              :     MATTER_TRACE_SCOPE("CheckForRevokedDACChain", "DeviceCommissioner");
    1532            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1533            0 :     VerifyOrReturnError(mDeviceAttestationVerifier != nullptr, CHIP_ERROR_INCORRECT_STATE);
    1534              : 
    1535            0 :     mDeviceAttestationVerifier->CheckForRevokedDACChain(info, &mDeviceAttestationInformationVerificationCallback);
    1536              : 
    1537            0 :     return CHIP_NO_ERROR;
    1538              : }
    1539              : 
    1540            0 : CHIP_ERROR DeviceCommissioner::ValidateCSR(DeviceProxy * proxy, const ByteSpan & NOCSRElements,
    1541              :                                            const ByteSpan & AttestationSignature, const ByteSpan & dac, const ByteSpan & csrNonce)
    1542              : {
    1543              :     MATTER_TRACE_SCOPE("ValidateCSR", "DeviceCommissioner");
    1544            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1545            0 :     VerifyOrReturnError(mDeviceAttestationVerifier != nullptr, CHIP_ERROR_INCORRECT_STATE);
    1546              : 
    1547            0 :     P256PublicKey dacPubkey;
    1548            0 :     ReturnErrorOnFailure(ExtractPubkeyFromX509Cert(dac, dacPubkey));
    1549              : 
    1550              :     // Retrieve attestation challenge
    1551              :     ByteSpan attestationChallenge =
    1552            0 :         proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge();
    1553              : 
    1554              :     // The operational CA should also verify this on its end during NOC generation, if end-to-end attestation is desired.
    1555            0 :     return mDeviceAttestationVerifier->VerifyNodeOperationalCSRInformation(NOCSRElements, attestationChallenge,
    1556            0 :                                                                            AttestationSignature, dacPubkey, csrNonce);
    1557            0 : }
    1558              : 
    1559            0 : CHIP_ERROR DeviceCommissioner::SendOperationalCertificateSigningRequestCommand(DeviceProxy * device, const ByteSpan & csrNonce,
    1560              :                                                                                Optional<System::Clock::Timeout> timeout)
    1561              : {
    1562              :     MATTER_TRACE_SCOPE("SendOperationalCertificateSigningRequestCommand", "DeviceCommissioner");
    1563            0 :     ChipLogDetail(Controller, "Sending CSR request to %p device", device);
    1564            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1565              : 
    1566            0 :     OperationalCredentials::Commands::CSRRequest::Type request;
    1567            0 :     request.CSRNonce = csrNonce;
    1568              : 
    1569            0 :     ReturnErrorOnFailure(SendCommissioningCommand(device, request, OnOperationalCertificateSigningRequest, OnCSRFailureResponse,
    1570              :                                                   kRootEndpointId, timeout));
    1571            0 :     ChipLogDetail(Controller, "Sent CSR request, waiting for the CSR");
    1572            0 :     return CHIP_NO_ERROR;
    1573              : }
    1574              : 
    1575            0 : void DeviceCommissioner::OnCSRFailureResponse(void * context, CHIP_ERROR error)
    1576              : {
    1577              :     MATTER_TRACE_SCOPE("OnCSRFailureResponse", "DeviceCommissioner");
    1578            0 :     ChipLogProgress(Controller, "Device failed to receive the CSR request Response: %s", chip::ErrorStr(error));
    1579            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1580            0 :     commissioner->CommissioningStageComplete(error);
    1581            0 : }
    1582              : 
    1583            0 : void DeviceCommissioner::OnOperationalCertificateSigningRequest(
    1584              :     void * context, const OperationalCredentials::Commands::CSRResponse::DecodableType & data)
    1585              : {
    1586              :     MATTER_TRACE_SCOPE("OnOperationalCertificateSigningRequest", "DeviceCommissioner");
    1587            0 :     ChipLogProgress(Controller, "Received certificate signing request from the device");
    1588            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1589              : 
    1590            0 :     CommissioningDelegate::CommissioningReport report;
    1591            0 :     report.Set<CSRResponse>(CSRResponse(data.NOCSRElements, data.attestationSignature));
    1592            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
    1593            0 : }
    1594              : 
    1595            0 : void DeviceCommissioner::OnDeviceNOCChainGeneration(void * context, CHIP_ERROR status, const ByteSpan & noc, const ByteSpan & icac,
    1596              :                                                     const ByteSpan & rcac, Optional<IdentityProtectionKeySpan> ipk,
    1597              :                                                     Optional<NodeId> adminSubject)
    1598              : {
    1599              :     MATTER_TRACE_SCOPE("OnDeviceNOCChainGeneration", "DeviceCommissioner");
    1600            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1601              : 
    1602              :     // The placeholder IPK is not satisfactory, but is there to fill the NocChain struct on error. It will still fail.
    1603            0 :     const uint8_t placeHolderIpk[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    1604              :                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    1605            0 :     if (status == CHIP_NO_ERROR && !ipk.HasValue())
    1606              :     {
    1607            0 :         ChipLogError(Controller, "Did not have an IPK from the OperationalCredentialsIssuer! Cannot commission.");
    1608            0 :         status = CHIP_ERROR_INVALID_ARGUMENT;
    1609              :     }
    1610              : 
    1611            0 :     ChipLogProgress(Controller, "Received callback from the CA for NOC Chain generation. Status %s", ErrorStr(status));
    1612            0 :     if (status == CHIP_NO_ERROR && commissioner->mState != State::Initialized)
    1613              :     {
    1614            0 :         status = CHIP_ERROR_INCORRECT_STATE;
    1615              :     }
    1616            0 :     if (status != CHIP_NO_ERROR)
    1617              :     {
    1618            0 :         ChipLogError(Controller, "Failed in generating device's operational credentials. Error %s", ErrorStr(status));
    1619              :     }
    1620              : 
    1621              :     // TODO - Verify that the generated root cert matches with commissioner's root cert
    1622            0 :     CommissioningDelegate::CommissioningReport report;
    1623            0 :     report.Set<NocChain>(NocChain(noc, icac, rcac, ipk.HasValue() ? ipk.Value() : IdentityProtectionKeySpan(placeHolderIpk),
    1624            0 :                                   adminSubject.HasValue() ? adminSubject.Value() : commissioner->GetNodeId()));
    1625            0 :     commissioner->CommissioningStageComplete(status, report);
    1626            0 : }
    1627              : 
    1628            0 : CHIP_ERROR DeviceCommissioner::IssueNOCChain(const ByteSpan & NOCSRElements, NodeId nodeId,
    1629              :                                              chip::Callback::Callback<OnNOCChainGeneration> * callback)
    1630              : {
    1631              :     MATTER_TRACE_SCOPE("IssueNOCChain", "DeviceCommissioner");
    1632            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1633              : 
    1634            0 :     ChipLogProgress(Controller, "Getting certificate chain for the device on fabric idx %u", static_cast<unsigned>(mFabricIndex));
    1635              : 
    1636            0 :     mOperationalCredentialsDelegate->SetNodeIdForNextNOCRequest(nodeId);
    1637              : 
    1638            0 :     if (mFabricIndex != kUndefinedFabricIndex)
    1639              :     {
    1640            0 :         mOperationalCredentialsDelegate->SetFabricIdForNextNOCRequest(GetFabricId());
    1641              :     }
    1642              : 
    1643              :     // Note: we don't have attestationSignature, attestationChallenge, DAC, PAI so we are just providing an empty ByteSpan
    1644              :     // for those arguments.
    1645            0 :     return mOperationalCredentialsDelegate->GenerateNOCChain(NOCSRElements, ByteSpan(), ByteSpan(), ByteSpan(), ByteSpan(),
    1646            0 :                                                              ByteSpan(), callback);
    1647              : }
    1648              : 
    1649            0 : CHIP_ERROR DeviceCommissioner::ProcessCSR(DeviceProxy * proxy, const ByteSpan & NOCSRElements,
    1650              :                                           const ByteSpan & AttestationSignature, const ByteSpan & dac, const ByteSpan & pai,
    1651              :                                           const ByteSpan & csrNonce)
    1652              : {
    1653              :     MATTER_TRACE_SCOPE("ProcessOpCSR", "DeviceCommissioner");
    1654            0 :     VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
    1655              : 
    1656            0 :     ChipLogProgress(Controller, "Getting certificate chain for the device from the issuer");
    1657              : 
    1658            0 :     P256PublicKey dacPubkey;
    1659            0 :     ReturnErrorOnFailure(ExtractPubkeyFromX509Cert(dac, dacPubkey));
    1660              : 
    1661              :     // Retrieve attestation challenge
    1662              :     ByteSpan attestationChallenge =
    1663            0 :         proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge();
    1664              : 
    1665            0 :     mOperationalCredentialsDelegate->SetNodeIdForNextNOCRequest(proxy->GetDeviceId());
    1666              : 
    1667            0 :     if (mFabricIndex != kUndefinedFabricIndex)
    1668              :     {
    1669            0 :         mOperationalCredentialsDelegate->SetFabricIdForNextNOCRequest(GetFabricId());
    1670              :     }
    1671              : 
    1672            0 :     return mOperationalCredentialsDelegate->GenerateNOCChain(NOCSRElements, csrNonce, AttestationSignature, attestationChallenge,
    1673            0 :                                                              dac, pai, &mDeviceNOCChainCallback);
    1674            0 : }
    1675              : 
    1676            0 : CHIP_ERROR DeviceCommissioner::SendOperationalCertificate(DeviceProxy * device, const ByteSpan & nocCertBuf,
    1677              :                                                           const Optional<ByteSpan> & icaCertBuf,
    1678              :                                                           const IdentityProtectionKeySpan ipk, const NodeId adminSubject,
    1679              :                                                           Optional<System::Clock::Timeout> timeout)
    1680              : {
    1681              :     MATTER_TRACE_SCOPE("SendOperationalCertificate", "DeviceCommissioner");
    1682              : 
    1683            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1684              : 
    1685            0 :     OperationalCredentials::Commands::AddNOC::Type request;
    1686            0 :     request.NOCValue         = nocCertBuf;
    1687            0 :     request.ICACValue        = icaCertBuf;
    1688            0 :     request.IPKValue         = ipk;
    1689            0 :     request.caseAdminSubject = adminSubject;
    1690            0 :     request.adminVendorId    = mVendorId;
    1691              : 
    1692            0 :     ReturnErrorOnFailure(SendCommissioningCommand(device, request, OnOperationalCertificateAddResponse, OnAddNOCFailureResponse,
    1693              :                                                   kRootEndpointId, timeout));
    1694              : 
    1695            0 :     ChipLogProgress(Controller, "Sent operational certificate to the device");
    1696              : 
    1697            0 :     return CHIP_NO_ERROR;
    1698              : }
    1699              : 
    1700            0 : CHIP_ERROR DeviceCommissioner::ConvertFromOperationalCertStatus(OperationalCredentials::NodeOperationalCertStatusEnum err)
    1701              : {
    1702              :     using OperationalCredentials::NodeOperationalCertStatusEnum;
    1703            0 :     switch (err)
    1704              :     {
    1705            0 :     case NodeOperationalCertStatusEnum::kOk:
    1706            0 :         return CHIP_NO_ERROR;
    1707            0 :     case NodeOperationalCertStatusEnum::kInvalidPublicKey:
    1708            0 :         return CHIP_ERROR_INVALID_PUBLIC_KEY;
    1709            0 :     case NodeOperationalCertStatusEnum::kInvalidNodeOpId:
    1710            0 :         return CHIP_ERROR_WRONG_NODE_ID;
    1711            0 :     case NodeOperationalCertStatusEnum::kInvalidNOC:
    1712            0 :         return CHIP_ERROR_UNSUPPORTED_CERT_FORMAT;
    1713            0 :     case NodeOperationalCertStatusEnum::kMissingCsr:
    1714            0 :         return CHIP_ERROR_INCORRECT_STATE;
    1715            0 :     case NodeOperationalCertStatusEnum::kTableFull:
    1716            0 :         return CHIP_ERROR_NO_MEMORY;
    1717            0 :     case NodeOperationalCertStatusEnum::kInvalidAdminSubject:
    1718            0 :         return CHIP_ERROR_INVALID_ADMIN_SUBJECT;
    1719            0 :     case NodeOperationalCertStatusEnum::kFabricConflict:
    1720            0 :         return CHIP_ERROR_FABRIC_EXISTS;
    1721            0 :     case NodeOperationalCertStatusEnum::kLabelConflict:
    1722            0 :         return CHIP_ERROR_INVALID_ARGUMENT;
    1723            0 :     case NodeOperationalCertStatusEnum::kInvalidFabricIndex:
    1724            0 :         return CHIP_ERROR_INVALID_FABRIC_INDEX;
    1725            0 :     case NodeOperationalCertStatusEnum::kUnknownEnumValue:
    1726              :         // Is this a reasonable value?
    1727            0 :         return CHIP_ERROR_CERT_LOAD_FAILED;
    1728              :     }
    1729              : 
    1730            0 :     return CHIP_ERROR_CERT_LOAD_FAILED;
    1731              : }
    1732              : 
    1733            0 : void DeviceCommissioner::OnAddNOCFailureResponse(void * context, CHIP_ERROR error)
    1734              : {
    1735              :     MATTER_TRACE_SCOPE("OnAddNOCFailureResponse", "DeviceCommissioner");
    1736            0 :     ChipLogProgress(Controller, "Device failed to receive the operational certificate Response: %s", chip::ErrorStr(error));
    1737            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1738            0 :     commissioner->CommissioningStageComplete(error);
    1739            0 : }
    1740              : 
    1741            0 : void DeviceCommissioner::OnOperationalCertificateAddResponse(
    1742              :     void * context, const OperationalCredentials::Commands::NOCResponse::DecodableType & data)
    1743              : {
    1744              :     MATTER_TRACE_SCOPE("OnOperationalCertificateAddResponse", "DeviceCommissioner");
    1745            0 :     ChipLogProgress(Controller, "Device returned status %d on receiving the NOC", to_underlying(data.statusCode));
    1746            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1747              : 
    1748            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    1749              : 
    1750            0 :     VerifyOrExit(commissioner->mState == State::Initialized, err = CHIP_ERROR_INCORRECT_STATE);
    1751              : 
    1752            0 :     VerifyOrExit(commissioner->mDeviceBeingCommissioned != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
    1753              : 
    1754            0 :     err = ConvertFromOperationalCertStatus(data.statusCode);
    1755            0 :     SuccessOrExit(err);
    1756              : 
    1757            0 :     err = commissioner->OnOperationalCredentialsProvisioningCompletion(commissioner->mDeviceBeingCommissioned);
    1758              : 
    1759            0 : exit:
    1760            0 :     if (err != CHIP_NO_ERROR)
    1761              :     {
    1762            0 :         ChipLogProgress(Controller, "Add NOC failed with error %s", ErrorStr(err));
    1763            0 :         commissioner->CommissioningStageComplete(err);
    1764              :     }
    1765            0 : }
    1766              : 
    1767            0 : CHIP_ERROR DeviceCommissioner::SendTrustedRootCertificate(DeviceProxy * device, const ByteSpan & rcac,
    1768              :                                                           Optional<System::Clock::Timeout> timeout)
    1769              : {
    1770              :     MATTER_TRACE_SCOPE("SendTrustedRootCertificate", "DeviceCommissioner");
    1771            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1772              : 
    1773            0 :     ChipLogProgress(Controller, "Sending root certificate to the device");
    1774              : 
    1775            0 :     OperationalCredentials::Commands::AddTrustedRootCertificate::Type request;
    1776            0 :     request.rootCACertificate = rcac;
    1777            0 :     ReturnErrorOnFailure(
    1778              :         SendCommissioningCommand(device, request, OnRootCertSuccessResponse, OnRootCertFailureResponse, kRootEndpointId, timeout));
    1779              : 
    1780            0 :     ChipLogProgress(Controller, "Sent root certificate to the device");
    1781              : 
    1782            0 :     return CHIP_NO_ERROR;
    1783              : }
    1784              : 
    1785            0 : void DeviceCommissioner::OnRootCertSuccessResponse(void * context, const chip::app::DataModel::NullObjectType &)
    1786              : {
    1787              :     MATTER_TRACE_SCOPE("OnRootCertSuccessResponse", "DeviceCommissioner");
    1788            0 :     ChipLogProgress(Controller, "Device confirmed that it has received the root certificate");
    1789            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1790            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    1791            0 : }
    1792              : 
    1793            0 : void DeviceCommissioner::OnRootCertFailureResponse(void * context, CHIP_ERROR error)
    1794              : {
    1795              :     MATTER_TRACE_SCOPE("OnRootCertFailureResponse", "DeviceCommissioner");
    1796            0 :     ChipLogProgress(Controller, "Device failed to receive the root certificate Response: %s", chip::ErrorStr(error));
    1797            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1798            0 :     commissioner->CommissioningStageComplete(error);
    1799            0 : }
    1800              : 
    1801            0 : CHIP_ERROR DeviceCommissioner::OnOperationalCredentialsProvisioningCompletion(DeviceProxy * device)
    1802              : {
    1803              :     MATTER_TRACE_SCOPE("OnOperationalCredentialsProvisioningCompletion", "DeviceCommissioner");
    1804            0 :     ChipLogProgress(Controller, "Operational credentials provisioned on device %p", device);
    1805            0 :     VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
    1806              : 
    1807            0 :     if (mPairingDelegate != nullptr)
    1808              :     {
    1809            0 :         mPairingDelegate->OnStatusUpdate(DevicePairingDelegate::SecurePairingSuccess);
    1810              :     }
    1811            0 :     CommissioningStageComplete(CHIP_NO_ERROR);
    1812              : 
    1813            0 :     return CHIP_NO_ERROR;
    1814              : }
    1815              : 
    1816              : #if CONFIG_NETWORK_LAYER_BLE
    1817              : #if CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
    1818              : void DeviceCommissioner::ConnectBleTransportToSelf()
    1819              : {
    1820              :     Transport::BLEBase & transport = std::get<Transport::BLE<1>>(mSystemState->TransportMgr()->GetTransport().GetTransports());
    1821              :     if (!transport.IsBleLayerTransportSetToSelf())
    1822              :     {
    1823              :         transport.SetBleLayerTransportToSelf();
    1824              :     }
    1825              : }
    1826              : #endif // CHIP_DEVICE_CONFIG_ENABLE_BOTH_COMMISSIONER_AND_COMMISSIONEE
    1827              : 
    1828            0 : void DeviceCommissioner::CloseBleConnection()
    1829              : {
    1830              :     // It is fine since we can only commission one device at the same time.
    1831              :     // We should be able to distinguish different BLE connections if we want
    1832              :     // to commission multiple devices at the same time over BLE.
    1833            0 :     mSystemState->BleLayer()->CloseAllBleConnections();
    1834            0 : }
    1835              : #endif
    1836              : 
    1837            0 : CHIP_ERROR DeviceCommissioner::DiscoverCommissionableNodes(Dnssd::DiscoveryFilter filter)
    1838              : {
    1839            0 :     ReturnErrorOnFailure(SetUpNodeDiscovery());
    1840            0 :     return mDNSResolver.DiscoverCommissionableNodes(filter);
    1841              : }
    1842              : 
    1843            0 : CHIP_ERROR DeviceCommissioner::StopCommissionableDiscovery()
    1844              : {
    1845            0 :     return mDNSResolver.StopDiscovery();
    1846              : }
    1847              : 
    1848            0 : const Dnssd::CommissionNodeData * DeviceCommissioner::GetDiscoveredDevice(int idx)
    1849              : {
    1850            0 :     return GetDiscoveredNode(idx);
    1851              : }
    1852              : 
    1853              : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY // make this commissioner discoverable
    1854              : 
    1855              : CHIP_ERROR DeviceCommissioner::SetUdcListenPort(uint16_t listenPort)
    1856              : {
    1857              :     if (mState == State::Initialized)
    1858              :     {
    1859              :         return CHIP_ERROR_INCORRECT_STATE;
    1860              :     }
    1861              : 
    1862              :     mUdcListenPort = listenPort;
    1863              :     return CHIP_NO_ERROR;
    1864              : }
    1865              : 
    1866              : void DeviceCommissioner::FindCommissionableNode(char * instanceName)
    1867              : {
    1868              :     Dnssd::DiscoveryFilter filter(Dnssd::DiscoveryFilterType::kInstanceName, instanceName);
    1869              :     DiscoverCommissionableNodes(filter);
    1870              : }
    1871              : 
    1872              : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
    1873              : 
    1874            0 : void DeviceCommissioner::OnNodeDiscovered(const chip::Dnssd::DiscoveredNodeData & nodeData)
    1875              : {
    1876              : #if CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
    1877              :     if (mUdcServer != nullptr)
    1878              :     {
    1879              :         mUdcServer->OnCommissionableNodeFound(nodeData);
    1880              :     }
    1881              : #endif // CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONER_DISCOVERY
    1882            0 :     AbstractDnssdDiscoveryController::OnNodeDiscovered(nodeData);
    1883            0 :     mSetUpCodePairer.NotifyCommissionableDeviceDiscovered(nodeData);
    1884            0 : }
    1885              : 
    1886            0 : void DeviceCommissioner::OnBasicSuccess(void * context, const chip::app::DataModel::NullObjectType &)
    1887              : {
    1888            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1889            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    1890            0 : }
    1891              : 
    1892            0 : void DeviceCommissioner::OnBasicFailure(void * context, CHIP_ERROR error)
    1893              : {
    1894            0 :     ChipLogProgress(Controller, "Received failure response %s\n", chip::ErrorStr(error));
    1895            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    1896            0 :     commissioner->CommissioningStageComplete(error);
    1897            0 : }
    1898              : 
    1899            0 : static GeneralCommissioning::Commands::ArmFailSafe::Type DisarmFailsafeRequest()
    1900              : {
    1901            0 :     GeneralCommissioning::Commands::ArmFailSafe::Type request;
    1902            0 :     request.expiryLengthSeconds = 0; // Expire immediately.
    1903            0 :     request.breadcrumb          = 0;
    1904            0 :     return request;
    1905              : }
    1906              : 
    1907            0 : static void MarkForEviction(const Optional<SessionHandle> & session)
    1908              : {
    1909            0 :     if (session.HasValue())
    1910              :     {
    1911            0 :         session.Value()->AsSecureSession()->MarkForEviction();
    1912              :     }
    1913            0 : }
    1914              : 
    1915            0 : void DeviceCommissioner::CleanupCommissioning(DeviceProxy * proxy, NodeId nodeId, const CompletionStatus & completionStatus)
    1916              : {
    1917              :     // At this point, proxy == mDeviceBeingCommissioned, nodeId == mDeviceBeingCommissioned->GetDeviceId()
    1918              : 
    1919            0 :     mCommissioningCompletionStatus = completionStatus;
    1920              : 
    1921            0 :     if (completionStatus.err == CHIP_NO_ERROR)
    1922              :     {
    1923              :         // CommissioningStageComplete uses mDeviceBeingCommissioned, which can
    1924              :         // be commissionee if we are cleaning up before we've gone operational.  Normally
    1925              :         // that would not happen in this non-error case, _except_ if we were told to skip sending
    1926              :         // CommissioningComplete: in that case we do not have an operational DeviceProxy, so
    1927              :         // we're using our CommissioneeDeviceProxy to do a successful cleanup.
    1928              :         //
    1929              :         // This means we have to call CommissioningStageComplete() before we destroy commissionee.
    1930              :         //
    1931              :         // This should be safe, because CommissioningStageComplete() does not call CleanupCommissioning
    1932              :         // when called in the cleanup stage (which is where we are), and StopPairing does not directly release
    1933              :         // mDeviceBeingCommissioned.
    1934            0 :         CommissioningStageComplete(CHIP_NO_ERROR);
    1935              : 
    1936            0 :         CommissioneeDeviceProxy * commissionee = FindCommissioneeDevice(nodeId);
    1937            0 :         if (commissionee != nullptr)
    1938              :         {
    1939            0 :             ReleaseCommissioneeDevice(commissionee);
    1940              :         }
    1941              :         // Send the callbacks, we're done.
    1942            0 :         SendCommissioningCompleteCallbacks(nodeId, mCommissioningCompletionStatus);
    1943              :     }
    1944            0 :     else if (completionStatus.err == CHIP_ERROR_CANCELLED)
    1945              :     {
    1946              :         // If we're cleaning up because cancellation has been requested via StopPairing(), expire the failsafe
    1947              :         // in the background and reset our state synchronously, so a new commissioning attempt can be started.
    1948            0 :         CommissioneeDeviceProxy * commissionee = FindCommissioneeDevice(nodeId);
    1949            0 :         SessionHolder session((commissionee == proxy) ? commissionee->DetachSecureSession().Value()
    1950            0 :                                                       : proxy->GetSecureSession().Value());
    1951              : 
    1952            0 :         auto request     = DisarmFailsafeRequest();
    1953            0 :         auto onSuccessCb = [session](const app::ConcreteCommandPath & aPath, const app::StatusIB & aStatus,
    1954              :                                      const decltype(request)::ResponseType & responseData) {
    1955            0 :             ChipLogProgress(Controller, "Failsafe disarmed");
    1956            0 :             MarkForEviction(session.Get());
    1957            0 :         };
    1958            0 :         auto onFailureCb = [session](CHIP_ERROR aError) {
    1959            0 :             ChipLogProgress(Controller, "Ignoring failure to disarm failsafe: %" CHIP_ERROR_FORMAT, aError.Format());
    1960            0 :             MarkForEviction(session.Get());
    1961            0 :         };
    1962              : 
    1963            0 :         ChipLogProgress(Controller, "Disarming failsafe on device %p in background", proxy);
    1964            0 :         CHIP_ERROR err = InvokeCommandRequest(proxy->GetExchangeManager(), session.Get().Value(), kRootEndpointId, request,
    1965              :                                               onSuccessCb, onFailureCb);
    1966            0 :         if (err != CHIP_NO_ERROR)
    1967              :         {
    1968            0 :             ChipLogError(Controller, "Failed to send command to disarm fail-safe: %" CHIP_ERROR_FORMAT, err.Format());
    1969              :         }
    1970              : 
    1971            0 :         CleanupDoneAfterError();
    1972            0 :     }
    1973            0 :     else if (completionStatus.failedStage.HasValue() && completionStatus.failedStage.Value() >= kWiFiNetworkSetup)
    1974              :     {
    1975              :         // If we were already doing network setup, we need to retain the pase session and start again from network setup stage.
    1976              :         // We do not need to reset the failsafe here because we want to keep everything on the device up to this point, so just
    1977              :         // send the completion callbacks (see "Commissioning Flows Error Handling" in the spec).
    1978            0 :         CommissioningStageComplete(CHIP_NO_ERROR);
    1979            0 :         SendCommissioningCompleteCallbacks(nodeId, mCommissioningCompletionStatus);
    1980              :     }
    1981              :     else
    1982              :     {
    1983              :         // If we've failed somewhere in the early stages (or we don't have a failedStage specified), we need to start from the
    1984              :         // beginning. However, because some of the commands can only be sent once per arm-failsafe, we also need to force a reset on
    1985              :         // the failsafe so we can start fresh on the next attempt.
    1986            0 :         ChipLogProgress(Controller, "Disarming failsafe on device %p", proxy);
    1987            0 :         auto request   = DisarmFailsafeRequest();
    1988            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnDisarmFailsafe, OnDisarmFailsafeFailure, kRootEndpointId);
    1989            0 :         if (err != CHIP_NO_ERROR)
    1990              :         {
    1991              :             // We won't get any async callbacks here, so just pretend like the command errored out async.
    1992            0 :             ChipLogError(Controller, "Failed to send command to disarm fail-safe: %" CHIP_ERROR_FORMAT, err.Format());
    1993            0 :             CleanupDoneAfterError();
    1994              :         }
    1995              :     }
    1996            0 : }
    1997              : 
    1998            0 : void DeviceCommissioner::OnDisarmFailsafe(void * context,
    1999              :                                           const GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType & data)
    2000              : {
    2001            0 :     ChipLogProgress(Controller, "Failsafe disarmed");
    2002            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2003            0 :     commissioner->CleanupDoneAfterError();
    2004            0 : }
    2005              : 
    2006            0 : void DeviceCommissioner::OnDisarmFailsafeFailure(void * context, CHIP_ERROR error)
    2007              : {
    2008            0 :     ChipLogProgress(Controller, "Ignoring failure to disarm failsafe: %" CHIP_ERROR_FORMAT, error.Format());
    2009            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2010            0 :     commissioner->CleanupDoneAfterError();
    2011            0 : }
    2012              : 
    2013            0 : void DeviceCommissioner::CleanupDoneAfterError()
    2014              : {
    2015              :     // If someone nulled out our mDeviceBeingCommissioned, there's nothing else
    2016              :     // to do here.
    2017            0 :     VerifyOrReturn(mDeviceBeingCommissioned != nullptr);
    2018              : 
    2019            0 :     NodeId nodeId = mDeviceBeingCommissioned->GetDeviceId();
    2020              : 
    2021              :     // Signal completion - this will reset mDeviceBeingCommissioned.
    2022            0 :     CommissioningStageComplete(CHIP_NO_ERROR);
    2023              : 
    2024              :     // At this point, we also want to close off the pase session so we need to re-establish
    2025            0 :     CommissioneeDeviceProxy * commissionee = FindCommissioneeDevice(nodeId);
    2026              : 
    2027              :     // If we've disarmed the failsafe, it's because we're starting again, so kill the pase connection.
    2028            0 :     if (commissionee != nullptr)
    2029              :     {
    2030            0 :         ReleaseCommissioneeDevice(commissionee);
    2031              :     }
    2032              : 
    2033              :     // Invoke callbacks last, after we have cleared up all state.
    2034            0 :     SendCommissioningCompleteCallbacks(nodeId, mCommissioningCompletionStatus);
    2035              : }
    2036              : 
    2037            0 : void DeviceCommissioner::SendCommissioningCompleteCallbacks(NodeId nodeId, const CompletionStatus & completionStatus)
    2038              : {
    2039              :     MATTER_LOG_METRIC_END(kMetricDeviceCommissionerCommission, completionStatus.err);
    2040              : 
    2041            0 :     ChipLogProgress(Controller, "Commissioning complete for node ID 0x" ChipLogFormatX64 ": %s", ChipLogValueX64(nodeId),
    2042              :                     (completionStatus.err == CHIP_NO_ERROR ? "success" : completionStatus.err.AsString()));
    2043            0 :     mCommissioningStage = CommissioningStage::kSecurePairing;
    2044              : 
    2045            0 :     if (mPairingDelegate == nullptr)
    2046              :     {
    2047            0 :         return;
    2048              :     }
    2049              : 
    2050            0 :     mPairingDelegate->OnCommissioningComplete(nodeId, completionStatus.err);
    2051            0 :     PeerId peerId(GetCompressedFabricId(), nodeId);
    2052            0 :     if (completionStatus.err == CHIP_NO_ERROR)
    2053              :     {
    2054            0 :         mPairingDelegate->OnCommissioningSuccess(peerId);
    2055              :     }
    2056              :     else
    2057              :     {
    2058              :         // TODO: We should propogate detailed error information (commissioningError, networkCommissioningStatus) from
    2059              :         // completionStatus.
    2060            0 :         mPairingDelegate->OnCommissioningFailure(peerId, completionStatus.err, completionStatus.failedStage.ValueOr(kError),
    2061            0 :                                                  completionStatus.attestationResult);
    2062              :     }
    2063              : }
    2064              : 
    2065            0 : void DeviceCommissioner::CommissioningStageComplete(CHIP_ERROR err, CommissioningDelegate::CommissioningReport report)
    2066              : {
    2067              :     // Once this stage is complete, reset mDeviceBeingCommissioned - this will be reset when the delegate calls the next step.
    2068              :     MATTER_TRACE_SCOPE("CommissioningStageComplete", "DeviceCommissioner");
    2069              :     MATTER_LOG_METRIC_END(MetricKeyForCommissioningStage(mCommissioningStage), err);
    2070            0 :     VerifyOrDie(mDeviceBeingCommissioned);
    2071              : 
    2072            0 :     NodeId nodeId            = mDeviceBeingCommissioned->GetDeviceId();
    2073            0 :     DeviceProxy * proxy      = mDeviceBeingCommissioned;
    2074            0 :     mDeviceBeingCommissioned = nullptr;
    2075            0 :     mInvokeCancelFn          = nullptr;
    2076            0 :     mWriteCancelFn           = nullptr;
    2077              : 
    2078            0 :     if (mPairingDelegate != nullptr)
    2079              :     {
    2080            0 :         mPairingDelegate->OnCommissioningStatusUpdate(PeerId(GetCompressedFabricId(), nodeId), mCommissioningStage, err);
    2081              :     }
    2082              : 
    2083            0 :     if (mCommissioningDelegate == nullptr)
    2084              :     {
    2085            0 :         return;
    2086              :     }
    2087            0 :     report.stageCompleted = mCommissioningStage;
    2088            0 :     CHIP_ERROR status     = mCommissioningDelegate->CommissioningStepFinished(err, report);
    2089            0 :     if (status != CHIP_NO_ERROR && mCommissioningStage != CommissioningStage::kCleanup)
    2090              :     {
    2091              :         // Commissioning delegate will only return error if it failed to perform the appropriate commissioning step.
    2092              :         // In this case, we should complete the commissioning for it.
    2093            0 :         CompletionStatus completionStatus;
    2094            0 :         completionStatus.err         = status;
    2095            0 :         completionStatus.failedStage = MakeOptional(report.stageCompleted);
    2096            0 :         mCommissioningStage          = CommissioningStage::kCleanup;
    2097            0 :         mDeviceBeingCommissioned     = proxy;
    2098            0 :         CleanupCommissioning(proxy, nodeId, completionStatus);
    2099              :     }
    2100              : }
    2101              : 
    2102            0 : void DeviceCommissioner::OnDeviceConnectedFn(void * context, Messaging::ExchangeManager & exchangeMgr,
    2103              :                                              const SessionHandle & sessionHandle)
    2104              : {
    2105              :     // CASE session established.
    2106              :     MATTER_LOG_METRIC_END(kMetricDeviceCommissioningOperationalSetup, CHIP_NO_ERROR);
    2107            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2108            0 :     VerifyOrDie(commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForStayActive ||
    2109              :                 commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForCommissioningComplete);
    2110            0 :     VerifyOrDie(commissioner->mDeviceBeingCommissioned->GetDeviceId() == sessionHandle->GetPeer().GetNodeId());
    2111            0 :     commissioner->CancelCASECallbacks(); // ensure all CASE callbacks are unregistered
    2112              : 
    2113            0 :     CommissioningDelegate::CommissioningReport report;
    2114            0 :     report.Set<OperationalNodeFoundData>(OperationalNodeFoundData(OperationalDeviceProxy(&exchangeMgr, sessionHandle)));
    2115            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR, report);
    2116            0 : }
    2117              : 
    2118            0 : void DeviceCommissioner::OnDeviceConnectionFailureFn(void * context, const ScopedNodeId & peerId, CHIP_ERROR error)
    2119              : {
    2120              :     // CASE session establishment failed.
    2121              :     MATTER_LOG_METRIC_END(kMetricDeviceCommissioningOperationalSetup, error);
    2122            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2123            0 :     VerifyOrDie(commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForStayActive ||
    2124              :                 commissioner->mCommissioningStage == CommissioningStage::kFindOperationalForCommissioningComplete);
    2125            0 :     VerifyOrDie(commissioner->mDeviceBeingCommissioned->GetDeviceId() == peerId.GetNodeId());
    2126            0 :     commissioner->CancelCASECallbacks(); // ensure all CASE callbacks are unregistered
    2127              : 
    2128            0 :     if (error != CHIP_NO_ERROR)
    2129              :     {
    2130            0 :         ChipLogProgress(Controller, "Device connection failed. Error %" CHIP_ERROR_FORMAT, error.Format());
    2131              :     }
    2132              :     else
    2133              :     {
    2134              :         // Ensure that commissioning stage advancement is done based on seeing an error.
    2135            0 :         ChipLogError(Controller, "Device connection failed without a valid error code.");
    2136            0 :         error = CHIP_ERROR_INTERNAL;
    2137              :     }
    2138            0 :     commissioner->CommissioningStageComplete(error);
    2139            0 : }
    2140              : 
    2141              : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
    2142              : // No specific action to take on either success or failure here; we're just
    2143              : // trying to bump the fail-safe, and if that fails it's not clear there's much
    2144              : // we can to with that.
    2145            0 : static void OnExtendFailsafeForCASERetryFailure(void * context, CHIP_ERROR error)
    2146              : {
    2147            0 :     ChipLogError(Controller, "Failed to extend fail-safe for CASE retry: %" CHIP_ERROR_FORMAT, error.Format());
    2148            0 : }
    2149              : static void
    2150            0 : OnExtendFailsafeForCASERetrySuccess(void * context,
    2151              :                                     const app::Clusters::GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType & data)
    2152              : {
    2153            0 :     ChipLogProgress(Controller, "Status of extending fail-safe for CASE retry: %u", to_underlying(data.errorCode));
    2154            0 : }
    2155              : 
    2156            0 : void DeviceCommissioner::OnDeviceConnectionRetryFn(void * context, const ScopedNodeId & peerId, CHIP_ERROR error,
    2157              :                                                    System::Clock::Seconds16 retryTimeout)
    2158              : {
    2159            0 :     ChipLogError(Controller,
    2160              :                  "Session establishment failed for " ChipLogFormatScopedNodeId ", error: %" CHIP_ERROR_FORMAT
    2161              :                  ".  Next retry expected to get a response to Sigma1 or fail within %d seconds",
    2162              :                  ChipLogValueScopedNodeId(peerId), error.Format(), retryTimeout.count());
    2163              : 
    2164            0 :     auto self = static_cast<DeviceCommissioner *>(context);
    2165            0 :     VerifyOrDie(self->GetCommissioningStage() == CommissioningStage::kFindOperationalForStayActive ||
    2166              :                 self->GetCommissioningStage() == CommissioningStage::kFindOperationalForCommissioningComplete);
    2167            0 :     VerifyOrDie(self->mDeviceBeingCommissioned->GetDeviceId() == peerId.GetNodeId());
    2168              : 
    2169              :     // We need to do the fail-safe arming over the PASE session.
    2170            0 :     auto * commissioneeDevice = self->FindCommissioneeDevice(peerId.GetNodeId());
    2171            0 :     if (!commissioneeDevice)
    2172              :     {
    2173              :         // Commissioning canceled, presumably.  Just ignore the notification,
    2174              :         // not much we can do here.
    2175            0 :         return;
    2176              :     }
    2177              : 
    2178              :     // Extend by the default failsafe timeout plus our retry timeout, so we can
    2179              :     // be sure the fail-safe will not expire before we try the next time, if
    2180              :     // there will be a next time.
    2181              :     //
    2182              :     // TODO: Make it possible for our clients to control the exact timeout here?
    2183              :     uint16_t failsafeTimeout;
    2184            0 :     if (UINT16_MAX - retryTimeout.count() < kDefaultFailsafeTimeout)
    2185              :     {
    2186            0 :         failsafeTimeout = UINT16_MAX;
    2187              :     }
    2188              :     else
    2189              :     {
    2190            0 :         failsafeTimeout = static_cast<uint16_t>(retryTimeout.count() + kDefaultFailsafeTimeout);
    2191              :     }
    2192              : 
    2193              :     // A false return is fine; we don't want to make the fail-safe shorter here.
    2194            0 :     self->ExtendArmFailSafeInternal(commissioneeDevice, self->GetCommissioningStage(), failsafeTimeout,
    2195            0 :                                     MakeOptional(kMinimumCommissioningStepTimeout), OnExtendFailsafeForCASERetrySuccess,
    2196              :                                     OnExtendFailsafeForCASERetryFailure, /* fireAndForget = */ true);
    2197              : }
    2198              : #endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
    2199              : 
    2200              : // ClusterStateCache::Callback / ReadClient::Callback
    2201            0 : void DeviceCommissioner::OnDone(app::ReadClient * readClient)
    2202              : {
    2203            0 :     VerifyOrDie(readClient != nullptr && readClient == mReadClient.get());
    2204            0 :     mReadClient.reset();
    2205            0 :     switch (mCommissioningStage)
    2206              :     {
    2207            0 :     case CommissioningStage::kReadCommissioningInfo:
    2208            0 :         ContinueReadingCommissioningInfo(mCommissioningDelegate->GetCommissioningParameters());
    2209            0 :         break;
    2210            0 :     default:
    2211            0 :         VerifyOrDie(false);
    2212              :         break;
    2213              :     }
    2214            0 : }
    2215              : 
    2216              : namespace {
    2217              : // Helper for grouping attribute paths into read interactions in ContinueReadingCommissioningInfo()
    2218              : // below. The logic generates a sequence of calls to AddAttributePath(), stopping when the capacity
    2219              : // of the builder is exceeded. When creating subsequent read requests, the same sequence of calls
    2220              : // is generated again, but the builder will skip however many attributes were already read in
    2221              : // previous requests. This makes it easy to have logic that conditionally reads attributes, without
    2222              : // needing to write manual code to work out where subsequent reads need to resume -- the logic that
    2223              : // decides which attributes to read simply needs to be repeatable / deterministic.
    2224              : class ReadInteractionBuilder
    2225              : {
    2226              :     static constexpr auto kCapacity = InteractionModelEngine::kMinSupportedPathsPerReadRequest;
    2227              : 
    2228              :     size_t mSkip  = 0;
    2229              :     size_t mCount = 0;
    2230              :     app::AttributePathParams mPaths[kCapacity];
    2231              : 
    2232              : public:
    2233            0 :     ReadInteractionBuilder(size_t skip = 0) : mSkip(skip) {}
    2234              : 
    2235            0 :     size_t size() { return std::min(mCount, kCapacity); }
    2236            0 :     bool exceeded() { return mCount > kCapacity; }
    2237            0 :     app::AttributePathParams * paths() { return mPaths; }
    2238              : 
    2239              :     // Adds an attribute path if within the current window.
    2240              :     // Returns false if the available space has been exceeded.
    2241              :     template <typename... Ts>
    2242            0 :     bool AddAttributePath(Ts &&... args)
    2243              :     {
    2244            0 :         if (mSkip > 0)
    2245              :         {
    2246            0 :             mSkip--;
    2247            0 :             return true;
    2248              :         }
    2249            0 :         if (mCount >= kCapacity)
    2250              :         {
    2251              :             // capacity exceeded
    2252            0 :             mCount = kCapacity + 1;
    2253            0 :             return false;
    2254              :         }
    2255            0 :         mPaths[mCount++] = app::AttributePathParams(std::forward<Ts>(args)...);
    2256            0 :         return true;
    2257              :     }
    2258              : };
    2259              : } // namespace
    2260              : 
    2261            0 : void DeviceCommissioner::ContinueReadingCommissioningInfo(const CommissioningParameters & params)
    2262              : {
    2263            0 :     VerifyOrDie(mCommissioningStage == CommissioningStage::kReadCommissioningInfo);
    2264              : 
    2265              :     // mReadCommissioningInfoProgress starts at 0 and counts the number of paths we have read.
    2266              :     // A marker value is used to indicate that there are no further attributes to read.
    2267              :     static constexpr auto kReadProgressNoFurtherAttributes = std::numeric_limits<decltype(mReadCommissioningInfoProgress)>::max();
    2268            0 :     if (mReadCommissioningInfoProgress == kReadProgressNoFurtherAttributes)
    2269              :     {
    2270            0 :         FinishReadingCommissioningInfo();
    2271            0 :         return;
    2272              :     }
    2273              : 
    2274              :     // We can ony read 9 paths per Read Interaction, since that is the minimum a server has to
    2275              :     // support per spec (see "Interaction Model Limits"), so we generally need to perform more
    2276              :     // that one interaction. To build the list of attributes for each interaction, we use a
    2277              :     // builder that skips adding paths that we already handled in a previous interaction, and
    2278              :     // returns false if the current request is exhausted. This construction avoids allocating
    2279              :     // memory to hold the complete list of attributes to read up front; however the logic to
    2280              :     // determine the attributes to include must be deterministic since it runs multiple times.
    2281              :     // The use of an immediately-invoked lambda is convenient for control flow.
    2282            0 :     ReadInteractionBuilder builder(mReadCommissioningInfoProgress);
    2283            0 :     [&]() -> void {
    2284              :         // General Commissioning
    2285            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2286              :                                                 Clusters::GeneralCommissioning::Attributes::SupportsConcurrentConnection::Id));
    2287            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2288              :                                                 Clusters::GeneralCommissioning::Attributes::Breadcrumb::Id));
    2289            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2290              :                                                 Clusters::GeneralCommissioning::Attributes::BasicCommissioningInfo::Id));
    2291            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2292              :                                                 Clusters::GeneralCommissioning::Attributes::RegulatoryConfig::Id));
    2293            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::GeneralCommissioning::Id,
    2294              :                                                 Clusters::GeneralCommissioning::Attributes::LocationCapability::Id));
    2295              : 
    2296              :         // Basic Information: VID and PID for device attestation purposes
    2297            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::BasicInformation::Id,
    2298              :                                                 Clusters::BasicInformation::Attributes::VendorID::Id));
    2299            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::BasicInformation::Id,
    2300              :                                                 Clusters::BasicInformation::Attributes::ProductID::Id));
    2301              : 
    2302              :         // Time Synchronization: all attributes
    2303            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::TimeSynchronization::Id));
    2304              : 
    2305              :         // Network Commissioning (all endpoints): Read the feature map and connect time
    2306              :         // TODO: Expose a flag that disables network setup so we don't need to read this
    2307            0 :         VerifyOrReturn(builder.AddAttributePath(Clusters::NetworkCommissioning::Id,
    2308              :                                                 Clusters::NetworkCommissioning::Attributes::FeatureMap::Id));
    2309            0 :         VerifyOrReturn(builder.AddAttributePath(Clusters::NetworkCommissioning::Id,
    2310              :                                                 Clusters::NetworkCommissioning::Attributes::ConnectMaxTimeSeconds::Id));
    2311              : 
    2312              :         // OperationalCredentials: existing fabrics, if necessary
    2313            0 :         if (params.GetCheckForMatchingFabric())
    2314              :         {
    2315            0 :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::OperationalCredentials::Id,
    2316              :                                                     Clusters::OperationalCredentials::Attributes::Fabrics::Id));
    2317              :         }
    2318              : 
    2319              :         // ICD Management
    2320            0 :         if (params.GetICDRegistrationStrategy() != ICDRegistrationStrategy::kIgnore)
    2321              :         {
    2322            0 :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2323              :                                                     Clusters::IcdManagement::Attributes::FeatureMap::Id));
    2324              :         }
    2325            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2326              :                                                 Clusters::IcdManagement::Attributes::UserActiveModeTriggerHint::Id));
    2327            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2328              :                                                 Clusters::IcdManagement::Attributes::UserActiveModeTriggerInstruction::Id));
    2329            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2330              :                                                 Clusters::IcdManagement::Attributes::IdleModeDuration::Id));
    2331            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2332              :                                                 Clusters::IcdManagement::Attributes::ActiveModeDuration::Id));
    2333            0 :         VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::IcdManagement::Id,
    2334              :                                                 Clusters::IcdManagement::Attributes::ActiveModeThreshold::Id));
    2335              : 
    2336              : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
    2337              :         if (params.GetExecuteJCM().ValueOr(false))
    2338              :         {
    2339              :             VerifyOrReturn(builder.AddAttributePath(Clusters::JointFabricAdministrator::Id,
    2340              :                                                     Clusters::JointFabricAdministrator::Attributes::AdministratorFabricIndex::Id));
    2341              :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::OperationalCredentials::Id,
    2342              :                                                     Clusters::OperationalCredentials::Attributes::Fabrics::Id));
    2343              :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::OperationalCredentials::Id,
    2344              :                                                     Clusters::OperationalCredentials::Attributes::NOCs::Id));
    2345              :             VerifyOrReturn(builder.AddAttributePath(kRootEndpointId, Clusters::OperationalCredentials::Id,
    2346              :                                                     Clusters::OperationalCredentials::Attributes::TrustedRootCertificates::Id));
    2347              :         }
    2348              : #endif // CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
    2349              : 
    2350              :         // Extra paths requested via CommissioningParameters
    2351            0 :         for (auto const & path : params.GetExtraReadPaths())
    2352              :         {
    2353            0 :             VerifyOrReturn(builder.AddAttributePath(path));
    2354              :         }
    2355            0 :     }();
    2356              : 
    2357            0 :     VerifyOrDie(builder.size() > 0); // our logic is broken if there is nothing to read
    2358            0 :     if (builder.exceeded())
    2359              :     {
    2360              :         // Keep track of the number of attributes we have read already so we can resume from there.
    2361            0 :         auto progress = mReadCommissioningInfoProgress + builder.size();
    2362            0 :         VerifyOrDie(progress < kReadProgressNoFurtherAttributes);
    2363            0 :         mReadCommissioningInfoProgress = static_cast<decltype(mReadCommissioningInfoProgress)>(progress);
    2364              :     }
    2365              :     else
    2366              :     {
    2367            0 :         mReadCommissioningInfoProgress = kReadProgressNoFurtherAttributes;
    2368              :     }
    2369              : 
    2370            0 :     SendCommissioningReadRequest(mDeviceBeingCommissioned, mCommissioningStepTimeout, builder.paths(), builder.size());
    2371              : }
    2372              : 
    2373              : namespace {
    2374            0 : void AccumulateErrors(CHIP_ERROR & acc, CHIP_ERROR err)
    2375              : {
    2376            0 :     if (acc == CHIP_NO_ERROR && err != CHIP_NO_ERROR)
    2377              :     {
    2378            0 :         acc = err;
    2379              :     }
    2380            0 : }
    2381              : } // namespace
    2382              : 
    2383            0 : void DeviceCommissioner::FinishReadingCommissioningInfo()
    2384              : {
    2385              :     // We want to parse as much information as possible, even if we eventually end
    2386              :     // up returning an error (e.g. because some mandatory information was missing).
    2387            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    2388            0 :     ReadCommissioningInfo info;
    2389            0 :     info.attributes = mAttributeCache.get();
    2390            0 :     AccumulateErrors(err, ParseGeneralCommissioningInfo(info));
    2391            0 :     AccumulateErrors(err, ParseBasicInformation(info));
    2392            0 :     AccumulateErrors(err, ParseNetworkCommissioningInfo(info));
    2393            0 :     AccumulateErrors(err, ParseTimeSyncInfo(info));
    2394            0 :     AccumulateErrors(err, ParseFabrics(info));
    2395            0 :     AccumulateErrors(err, ParseICDInfo(info));
    2396              : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
    2397              :     AccumulateErrors(err, ParseJFAdministratorInfo(info));
    2398              : #endif
    2399              : 
    2400            0 :     if (mPairingDelegate != nullptr && err == CHIP_NO_ERROR)
    2401              :     {
    2402            0 :         mPairingDelegate->OnReadCommissioningInfo(info);
    2403              :     }
    2404              : 
    2405            0 :     CommissioningDelegate::CommissioningReport report;
    2406            0 :     report.Set<ReadCommissioningInfo>(info);
    2407            0 :     CommissioningStageComplete(err, report);
    2408              : 
    2409              :     // Only release the attribute cache once `info` is no longer needed.
    2410            0 :     mAttributeCache.reset();
    2411            0 : }
    2412              : 
    2413            0 : CHIP_ERROR DeviceCommissioner::ParseGeneralCommissioningInfo(ReadCommissioningInfo & info)
    2414              : {
    2415              :     using namespace GeneralCommissioning::Attributes;
    2416            0 :     CHIP_ERROR return_err = CHIP_NO_ERROR;
    2417              :     CHIP_ERROR err;
    2418              : 
    2419            0 :     BasicCommissioningInfo::TypeInfo::DecodableType basicInfo;
    2420            0 :     err = mAttributeCache->Get<BasicCommissioningInfo::TypeInfo>(kRootEndpointId, basicInfo);
    2421            0 :     if (err == CHIP_NO_ERROR)
    2422              :     {
    2423            0 :         info.general.recommendedFailsafe = basicInfo.failSafeExpiryLengthSeconds;
    2424              :     }
    2425              :     else
    2426              :     {
    2427            0 :         ChipLogError(Controller, "Failed to read BasicCommissioningInfo: %" CHIP_ERROR_FORMAT, err.Format());
    2428            0 :         return_err = err;
    2429              :     }
    2430              : 
    2431            0 :     err = mAttributeCache->Get<RegulatoryConfig::TypeInfo>(kRootEndpointId, info.general.currentRegulatoryLocation);
    2432            0 :     if (err != CHIP_NO_ERROR)
    2433              :     {
    2434            0 :         ChipLogError(Controller, "Failed to read RegulatoryConfig: %" CHIP_ERROR_FORMAT, err.Format());
    2435            0 :         return_err = err;
    2436              :     }
    2437              : 
    2438            0 :     err = mAttributeCache->Get<LocationCapability::TypeInfo>(kRootEndpointId, info.general.locationCapability);
    2439            0 :     if (err != CHIP_NO_ERROR)
    2440              :     {
    2441            0 :         ChipLogError(Controller, "Failed to read LocationCapability: %" CHIP_ERROR_FORMAT, err.Format());
    2442            0 :         return_err = err;
    2443              :     }
    2444              : 
    2445            0 :     err = mAttributeCache->Get<Breadcrumb::TypeInfo>(kRootEndpointId, info.general.breadcrumb);
    2446            0 :     if (err != CHIP_NO_ERROR)
    2447              :     {
    2448            0 :         ChipLogError(Controller, "Failed to read Breadcrumb: %" CHIP_ERROR_FORMAT, err.Format());
    2449            0 :         return_err = err;
    2450              :     }
    2451              : 
    2452            0 :     err = mAttributeCache->Get<SupportsConcurrentConnection::TypeInfo>(kRootEndpointId, info.supportsConcurrentConnection);
    2453            0 :     if (err != CHIP_NO_ERROR)
    2454              :     {
    2455            0 :         ChipLogError(Controller, "Ignoring failure to read SupportsConcurrentConnection: %" CHIP_ERROR_FORMAT, err.Format());
    2456            0 :         info.supportsConcurrentConnection = true; // default to true (concurrent), not a fatal error
    2457              :     }
    2458              : 
    2459            0 :     return return_err;
    2460              : }
    2461              : 
    2462            0 : CHIP_ERROR DeviceCommissioner::ParseBasicInformation(ReadCommissioningInfo & info)
    2463              : {
    2464              :     using namespace BasicInformation::Attributes;
    2465            0 :     CHIP_ERROR return_err = CHIP_NO_ERROR;
    2466              :     CHIP_ERROR err;
    2467              : 
    2468            0 :     err = mAttributeCache->Get<VendorID::TypeInfo>(kRootEndpointId, info.basic.vendorId);
    2469            0 :     if (err != CHIP_NO_ERROR)
    2470              :     {
    2471            0 :         ChipLogError(Controller, "Failed to read VendorID: %" CHIP_ERROR_FORMAT, err.Format());
    2472            0 :         return_err = err;
    2473              :     }
    2474              : 
    2475            0 :     err = mAttributeCache->Get<ProductID::TypeInfo>(kRootEndpointId, info.basic.productId);
    2476            0 :     if (err != CHIP_NO_ERROR)
    2477              :     {
    2478            0 :         ChipLogError(Controller, "Failed to read ProductID: %" CHIP_ERROR_FORMAT, err.Format());
    2479            0 :         return_err = err;
    2480              :     }
    2481              : 
    2482            0 :     return return_err;
    2483              : }
    2484              : 
    2485            0 : CHIP_ERROR DeviceCommissioner::ParseNetworkCommissioningInfo(ReadCommissioningInfo & info)
    2486              : {
    2487              :     using namespace NetworkCommissioning::Attributes;
    2488            0 :     CHIP_ERROR return_err = CHIP_NO_ERROR;
    2489              :     CHIP_ERROR err;
    2490              : 
    2491              :     // Set the network cluster endpoints first so we can match up the connection
    2492              :     // times. Note that here we don't know what endpoints the network
    2493              :     // commissioning clusters might be on.
    2494            0 :     err = mAttributeCache->ForEachAttribute(NetworkCommissioning::Id, [this, &info](const ConcreteAttributePath & path) {
    2495            0 :         VerifyOrReturnError(path.mAttributeId == FeatureMap::Id, CHIP_NO_ERROR);
    2496            0 :         BitFlags<NetworkCommissioning::Feature> features;
    2497            0 :         if (mAttributeCache->Get<FeatureMap::TypeInfo>(path, *features.RawStorage()) == CHIP_NO_ERROR)
    2498              :         {
    2499            0 :             if (features.Has(NetworkCommissioning::Feature::kWiFiNetworkInterface))
    2500              :             {
    2501            0 :                 ChipLogProgress(Controller, "NetworkCommissioning Features: has WiFi. endpointid = %u", path.mEndpointId);
    2502            0 :                 info.network.wifi.endpoint = path.mEndpointId;
    2503              :             }
    2504            0 :             else if (features.Has(NetworkCommissioning::Feature::kThreadNetworkInterface))
    2505              :             {
    2506            0 :                 ChipLogProgress(Controller, "NetworkCommissioning Features: has Thread. endpointid = %u", path.mEndpointId);
    2507            0 :                 info.network.thread.endpoint = path.mEndpointId;
    2508              :             }
    2509            0 :             else if (features.Has(NetworkCommissioning::Feature::kEthernetNetworkInterface))
    2510              :             {
    2511            0 :                 ChipLogProgress(Controller, "NetworkCommissioning Features: has Ethernet. endpointid = %u", path.mEndpointId);
    2512            0 :                 info.network.eth.endpoint = path.mEndpointId;
    2513              :             }
    2514              :         }
    2515            0 :         return CHIP_NO_ERROR;
    2516              :     });
    2517            0 :     AccumulateErrors(return_err, err);
    2518              : 
    2519            0 :     if (info.network.thread.endpoint != kInvalidEndpointId)
    2520              :     {
    2521            0 :         err = mAttributeCache->Get<ConnectMaxTimeSeconds::TypeInfo>(info.network.thread.endpoint,
    2522            0 :                                                                     info.network.thread.minConnectionTime);
    2523            0 :         if (err != CHIP_NO_ERROR)
    2524              :         {
    2525            0 :             ChipLogError(Controller, "Failed to read Thread ConnectMaxTimeSeconds (endpoint %u): %" CHIP_ERROR_FORMAT,
    2526              :                          info.network.thread.endpoint, err.Format());
    2527            0 :             return_err = err;
    2528              :         }
    2529              :     }
    2530              : 
    2531            0 :     if (info.network.wifi.endpoint != kInvalidEndpointId)
    2532              :     {
    2533            0 :         err =
    2534            0 :             mAttributeCache->Get<ConnectMaxTimeSeconds::TypeInfo>(info.network.wifi.endpoint, info.network.wifi.minConnectionTime);
    2535            0 :         if (err != CHIP_NO_ERROR)
    2536              :         {
    2537            0 :             ChipLogError(Controller, "Failed to read Wi-Fi ConnectMaxTimeSeconds (endpoint %u): %" CHIP_ERROR_FORMAT,
    2538              :                          info.network.wifi.endpoint, err.Format());
    2539            0 :             return_err = err;
    2540              :         }
    2541              :     }
    2542              : 
    2543            0 :     if (return_err != CHIP_NO_ERROR)
    2544              :     {
    2545            0 :         ChipLogError(Controller, "Failed to parsing Network Commissioning information: %" CHIP_ERROR_FORMAT, return_err.Format());
    2546              :     }
    2547            0 :     return return_err;
    2548              : }
    2549              : 
    2550            0 : CHIP_ERROR DeviceCommissioner::ParseTimeSyncInfo(ReadCommissioningInfo & info)
    2551              : {
    2552              :     using namespace TimeSynchronization::Attributes;
    2553              :     CHIP_ERROR err;
    2554              : 
    2555              :     // If we fail to get the feature map, there's no viable time cluster, don't set anything.
    2556            0 :     BitFlags<TimeSynchronization::Feature> featureMap;
    2557            0 :     err = mAttributeCache->Get<FeatureMap::TypeInfo>(kRootEndpointId, *featureMap.RawStorage());
    2558            0 :     if (err != CHIP_NO_ERROR)
    2559              :     {
    2560            0 :         info.requiresUTC               = false;
    2561            0 :         info.requiresTimeZone          = false;
    2562            0 :         info.requiresDefaultNTP        = false;
    2563            0 :         info.requiresTrustedTimeSource = false;
    2564            0 :         return CHIP_NO_ERROR;
    2565              :     }
    2566            0 :     info.requiresUTC               = true;
    2567            0 :     info.requiresTimeZone          = featureMap.Has(TimeSynchronization::Feature::kTimeZone);
    2568            0 :     info.requiresDefaultNTP        = featureMap.Has(TimeSynchronization::Feature::kNTPClient);
    2569            0 :     info.requiresTrustedTimeSource = featureMap.Has(TimeSynchronization::Feature::kTimeSyncClient);
    2570              : 
    2571            0 :     if (info.requiresTimeZone)
    2572              :     {
    2573            0 :         err = mAttributeCache->Get<TimeZoneListMaxSize::TypeInfo>(kRootEndpointId, info.maxTimeZoneSize);
    2574            0 :         if (err != CHIP_NO_ERROR)
    2575              :         {
    2576              :             // This information should be available, let's do our best with what we have, but we can't set
    2577              :             // the time zone without this information
    2578            0 :             info.requiresTimeZone = false;
    2579              :         }
    2580            0 :         err = mAttributeCache->Get<DSTOffsetListMaxSize::TypeInfo>(kRootEndpointId, info.maxDSTSize);
    2581            0 :         if (err != CHIP_NO_ERROR)
    2582              :         {
    2583            0 :             info.requiresTimeZone = false;
    2584              :         }
    2585              :     }
    2586            0 :     if (info.requiresDefaultNTP)
    2587              :     {
    2588            0 :         DefaultNTP::TypeInfo::DecodableType defaultNTP;
    2589            0 :         err = mAttributeCache->Get<DefaultNTP::TypeInfo>(kRootEndpointId, defaultNTP);
    2590            0 :         if (err == CHIP_NO_ERROR && (!defaultNTP.IsNull()) && (defaultNTP.Value().size() != 0))
    2591              :         {
    2592            0 :             info.requiresDefaultNTP = false;
    2593              :         }
    2594              :     }
    2595            0 :     if (info.requiresTrustedTimeSource)
    2596              :     {
    2597            0 :         TrustedTimeSource::TypeInfo::DecodableType trustedTimeSource;
    2598            0 :         err = mAttributeCache->Get<TrustedTimeSource::TypeInfo>(kRootEndpointId, trustedTimeSource);
    2599            0 :         if (err == CHIP_NO_ERROR && !trustedTimeSource.IsNull())
    2600              :         {
    2601            0 :             info.requiresTrustedTimeSource = false;
    2602              :         }
    2603              :     }
    2604              : 
    2605            0 :     return CHIP_NO_ERROR;
    2606              : }
    2607              : 
    2608            0 : CHIP_ERROR DeviceCommissioner::ParseFabrics(ReadCommissioningInfo & info)
    2609              : {
    2610              :     using namespace OperationalCredentials::Attributes;
    2611              :     CHIP_ERROR err;
    2612            0 :     CHIP_ERROR return_err = CHIP_NO_ERROR;
    2613              : 
    2614              :     // We might not have requested a Fabrics attribute at all, so not having a
    2615              :     // value for it is not an error.
    2616            0 :     err = mAttributeCache->ForEachAttribute(OperationalCredentials::Id, [this, &info](const ConcreteAttributePath & path) {
    2617              :         using namespace chip::app::Clusters::OperationalCredentials::Attributes;
    2618              :         // this code is checking if the device is already on the commissioner's fabric.
    2619              :         // if a matching fabric is found, then remember the nodeId so that the commissioner
    2620              :         // can, if it decides to, cancel commissioning (before it fails in AddNoc) and know
    2621              :         // the device's nodeId on its fabric.
    2622            0 :         switch (path.mAttributeId)
    2623              :         {
    2624            0 :         case Fabrics::Id: {
    2625            0 :             Fabrics::TypeInfo::DecodableType fabrics;
    2626            0 :             ReturnErrorOnFailure(this->mAttributeCache->Get<Fabrics::TypeInfo>(path, fabrics));
    2627              :             // this is a best effort attempt to find a matching fabric, so no error checking on iter
    2628            0 :             auto iter = fabrics.begin();
    2629            0 :             while (iter.Next())
    2630              :             {
    2631            0 :                 auto & fabricDescriptor = iter.GetValue();
    2632            0 :                 ChipLogProgress(Controller,
    2633              :                                 "DeviceCommissioner::OnDone - fabric.vendorId=0x%04X fabric.fabricId=0x" ChipLogFormatX64
    2634              :                                 " fabric.nodeId=0x" ChipLogFormatX64,
    2635              :                                 fabricDescriptor.vendorID, ChipLogValueX64(fabricDescriptor.fabricID),
    2636              :                                 ChipLogValueX64(fabricDescriptor.nodeID));
    2637            0 :                 if (GetFabricId() == fabricDescriptor.fabricID)
    2638              :                 {
    2639            0 :                     ChipLogProgress(Controller, "DeviceCommissioner::OnDone - found a matching fabric id");
    2640            0 :                     chip::ByteSpan rootKeySpan = fabricDescriptor.rootPublicKey;
    2641            0 :                     if (rootKeySpan.size() != Crypto::kP256_PublicKey_Length)
    2642              :                     {
    2643            0 :                         ChipLogError(Controller, "DeviceCommissioner::OnDone - fabric root key size mismatch %u != %u",
    2644              :                                      static_cast<unsigned>(rootKeySpan.size()),
    2645              :                                      static_cast<unsigned>(Crypto::kP256_PublicKey_Length));
    2646            0 :                         continue;
    2647              :                     }
    2648            0 :                     P256PublicKeySpan rootPubKeySpan(rootKeySpan.data());
    2649            0 :                     Crypto::P256PublicKey deviceRootPublicKey(rootPubKeySpan);
    2650              : 
    2651            0 :                     Crypto::P256PublicKey commissionerRootPublicKey;
    2652            0 :                     if (CHIP_NO_ERROR != GetRootPublicKey(commissionerRootPublicKey))
    2653              :                     {
    2654            0 :                         ChipLogError(Controller, "DeviceCommissioner::OnDone - error reading commissioner root public key");
    2655              :                     }
    2656            0 :                     else if (commissionerRootPublicKey.Matches(deviceRootPublicKey))
    2657              :                     {
    2658            0 :                         ChipLogProgress(Controller, "DeviceCommissioner::OnDone - fabric root keys match");
    2659            0 :                         info.remoteNodeId = fabricDescriptor.nodeID;
    2660              :                     }
    2661            0 :                 }
    2662              :             }
    2663              : 
    2664            0 :             return CHIP_NO_ERROR;
    2665              :         }
    2666            0 :         default:
    2667            0 :             return CHIP_NO_ERROR;
    2668              :         }
    2669              :     });
    2670              : 
    2671            0 :     if (mPairingDelegate != nullptr)
    2672              :     {
    2673            0 :         mPairingDelegate->OnFabricCheck(info.remoteNodeId);
    2674              :     }
    2675              : 
    2676            0 :     return return_err;
    2677              : }
    2678              : 
    2679            0 : CHIP_ERROR DeviceCommissioner::ParseICDInfo(ReadCommissioningInfo & info)
    2680              : {
    2681              :     using namespace IcdManagement::Attributes;
    2682              :     CHIP_ERROR err;
    2683              : 
    2684            0 :     bool hasUserActiveModeTrigger = false;
    2685            0 :     bool isICD                    = false;
    2686              : 
    2687            0 :     BitFlags<IcdManagement::Feature> featureMap;
    2688            0 :     err = mAttributeCache->Get<FeatureMap::TypeInfo>(kRootEndpointId, *featureMap.RawStorage());
    2689            0 :     if (err == CHIP_NO_ERROR)
    2690              :     {
    2691            0 :         info.icd.isLIT                  = featureMap.Has(IcdManagement::Feature::kLongIdleTimeSupport);
    2692            0 :         info.icd.checkInProtocolSupport = featureMap.Has(IcdManagement::Feature::kCheckInProtocolSupport);
    2693            0 :         hasUserActiveModeTrigger        = featureMap.Has(IcdManagement::Feature::kUserActiveModeTrigger);
    2694            0 :         isICD                           = true;
    2695              :     }
    2696            0 :     else if (err == CHIP_ERROR_KEY_NOT_FOUND)
    2697              :     {
    2698              :         // This key is optional so not an error
    2699            0 :         info.icd.isLIT = false;
    2700            0 :         err            = CHIP_NO_ERROR;
    2701              :     }
    2702            0 :     else if (err == CHIP_ERROR_IM_STATUS_CODE_RECEIVED)
    2703              :     {
    2704            0 :         app::StatusIB statusIB;
    2705            0 :         err = mAttributeCache->GetStatus(app::ConcreteAttributePath(kRootEndpointId, IcdManagement::Id, FeatureMap::Id), statusIB);
    2706            0 :         if (err == CHIP_NO_ERROR)
    2707              :         {
    2708            0 :             if (statusIB.mStatus == Protocols::InteractionModel::Status::UnsupportedCluster)
    2709              :             {
    2710            0 :                 info.icd.isLIT = false;
    2711              :             }
    2712              :             else
    2713              :             {
    2714            0 :                 err = statusIB.ToChipError();
    2715              :             }
    2716              :         }
    2717              :     }
    2718              : 
    2719            0 :     ReturnErrorOnFailure(err);
    2720              : 
    2721            0 :     info.icd.userActiveModeTriggerHint.ClearAll();
    2722            0 :     info.icd.userActiveModeTriggerInstruction = CharSpan();
    2723              : 
    2724            0 :     if (hasUserActiveModeTrigger)
    2725              :     {
    2726              :         // Intentionally ignore errors since they are not mandatory.
    2727            0 :         bool activeModeTriggerInstructionRequired = false;
    2728              : 
    2729            0 :         err = mAttributeCache->Get<UserActiveModeTriggerHint::TypeInfo>(kRootEndpointId, info.icd.userActiveModeTriggerHint);
    2730            0 :         if (err != CHIP_NO_ERROR)
    2731              :         {
    2732            0 :             ChipLogError(Controller, "IcdManagement.UserActiveModeTriggerHint expected, but failed to read.");
    2733            0 :             return err;
    2734              :         }
    2735              : 
    2736              :         using IcdManagement::UserActiveModeTriggerBitmap;
    2737            0 :         activeModeTriggerInstructionRequired = info.icd.userActiveModeTriggerHint.HasAny(
    2738            0 :             UserActiveModeTriggerBitmap::kCustomInstruction, UserActiveModeTriggerBitmap::kActuateSensorSeconds,
    2739            0 :             UserActiveModeTriggerBitmap::kActuateSensorTimes, UserActiveModeTriggerBitmap::kActuateSensorLightsBlink,
    2740            0 :             UserActiveModeTriggerBitmap::kResetButtonLightsBlink, UserActiveModeTriggerBitmap::kResetButtonSeconds,
    2741            0 :             UserActiveModeTriggerBitmap::kResetButtonTimes, UserActiveModeTriggerBitmap::kSetupButtonSeconds,
    2742            0 :             UserActiveModeTriggerBitmap::kSetupButtonTimes, UserActiveModeTriggerBitmap::kSetupButtonTimes,
    2743            0 :             UserActiveModeTriggerBitmap::kAppDefinedButton);
    2744              : 
    2745            0 :         if (activeModeTriggerInstructionRequired)
    2746              :         {
    2747            0 :             err = mAttributeCache->Get<UserActiveModeTriggerInstruction::TypeInfo>(kRootEndpointId,
    2748            0 :                                                                                    info.icd.userActiveModeTriggerInstruction);
    2749            0 :             if (err != CHIP_NO_ERROR)
    2750              :             {
    2751            0 :                 ChipLogError(Controller,
    2752              :                              "IcdManagement.UserActiveModeTriggerInstruction expected for given active mode trigger hint, but "
    2753              :                              "failed to read.");
    2754            0 :                 return err;
    2755              :             }
    2756              :         }
    2757              :     }
    2758              : 
    2759            0 :     if (!isICD)
    2760              :     {
    2761            0 :         info.icd.idleModeDuration    = 0;
    2762            0 :         info.icd.activeModeDuration  = 0;
    2763            0 :         info.icd.activeModeThreshold = 0;
    2764            0 :         return CHIP_NO_ERROR;
    2765              :     }
    2766              : 
    2767            0 :     err = mAttributeCache->Get<IdleModeDuration::TypeInfo>(kRootEndpointId, info.icd.idleModeDuration);
    2768            0 :     if (err != CHIP_NO_ERROR)
    2769              :     {
    2770            0 :         ChipLogError(Controller, "IcdManagement.IdleModeDuration expected, but failed to read: %" CHIP_ERROR_FORMAT, err.Format());
    2771            0 :         return err;
    2772              :     }
    2773              : 
    2774            0 :     err = mAttributeCache->Get<ActiveModeDuration::TypeInfo>(kRootEndpointId, info.icd.activeModeDuration);
    2775            0 :     if (err != CHIP_NO_ERROR)
    2776              :     {
    2777            0 :         ChipLogError(Controller, "IcdManagement.ActiveModeDuration expected, but failed to read: %" CHIP_ERROR_FORMAT,
    2778              :                      err.Format());
    2779            0 :         return err;
    2780              :     }
    2781              : 
    2782            0 :     err = mAttributeCache->Get<ActiveModeThreshold::TypeInfo>(kRootEndpointId, info.icd.activeModeThreshold);
    2783            0 :     if (err != CHIP_NO_ERROR)
    2784              :     {
    2785            0 :         ChipLogError(Controller, "IcdManagement.ActiveModeThreshold expected, but failed to read: %" CHIP_ERROR_FORMAT,
    2786              :                      err.Format());
    2787              :     }
    2788              : 
    2789            0 :     return err;
    2790              : }
    2791              : 
    2792              : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
    2793              : CHIP_ERROR DeviceCommissioner::ParseJFAdministratorInfo(ReadCommissioningInfo & info)
    2794              : {
    2795              :     using namespace JointFabricAdministrator::Attributes;
    2796              :     using namespace OperationalCredentials::Attributes;
    2797              :     ByteSpan rootKeySpan;
    2798              : 
    2799              :     CHIP_ERROR err = CHIP_NO_ERROR;
    2800              : 
    2801              :     err = mAttributeCache->ForEachAttribute(JointFabricAdministrator::Id, [this, &info](const ConcreteAttributePath & path) {
    2802              :         using namespace chip::app::Clusters::JointFabricAdministrator::Attributes;
    2803              :         AdministratorFabricIndex::TypeInfo::DecodableType administratorFabricIndex;
    2804              : 
    2805              :         VerifyOrReturnError(path.mAttributeId == AdministratorFabricIndex::Id, CHIP_NO_ERROR);
    2806              :         ReturnErrorOnFailure(this->mAttributeCache->Get<AdministratorFabricIndex::TypeInfo>(path, administratorFabricIndex));
    2807              : 
    2808              :         if (!administratorFabricIndex.IsNull())
    2809              :         {
    2810              :             ChipLogProgress(Controller, "JCM: AdministratorFabricIndex: %d", administratorFabricIndex.Value());
    2811              :             info.JFAdministratorFabricIndex = administratorFabricIndex.Value();
    2812              :             info.JFAdminEndpointId          = path.mEndpointId;
    2813              :         }
    2814              :         else
    2815              :         {
    2816              :             ChipLogError(Controller, "JCM: AdministratorFabricIndex attribute@JF Administrator Cluster not found!");
    2817              :             return CHIP_ERROR_NOT_FOUND;
    2818              :         }
    2819              :         return CHIP_NO_ERROR;
    2820              :     });
    2821              : 
    2822              :     if ((info.JFAdministratorFabricIndex == kUndefinedFabricIndex) || (err != CHIP_NO_ERROR))
    2823              :     {
    2824              :         info.JFAdministratorFabricIndex = kUndefinedFabricIndex;
    2825              :         return err;
    2826              :     }
    2827              : 
    2828              :     err = mAttributeCache->ForEachAttribute(
    2829              :         OperationalCredentials::Id, [this, &info, &rootKeySpan](const ConcreteAttributePath & path) {
    2830              :             using namespace chip::app::Clusters::OperationalCredentials::Attributes;
    2831              : 
    2832              :             switch (path.mAttributeId)
    2833              :             {
    2834              :             case Fabrics::Id: {
    2835              :                 Fabrics::TypeInfo::DecodableType fabrics;
    2836              :                 ReturnErrorOnFailure(this->mAttributeCache->Get<Fabrics::TypeInfo>(path, fabrics));
    2837              :                 bool foundMatchingFabricIndex = false;
    2838              : 
    2839              :                 auto iter = fabrics.begin();
    2840              :                 while (iter.Next())
    2841              :                 {
    2842              :                     auto & fabricDescriptor = iter.GetValue();
    2843              :                     if (fabricDescriptor.fabricIndex == info.JFAdministratorFabricIndex)
    2844              :                     {
    2845              :                         if (fabricDescriptor.rootPublicKey.size() != Crypto::kP256_PublicKey_Length)
    2846              :                         {
    2847              :                             ChipLogError(Controller,
    2848              :                                          "JCM: DeviceCommissioner::ParseJFAdministratorInfo - fabric root key size mismatch");
    2849              :                             return CHIP_ERROR_KEY_NOT_FOUND;
    2850              :                         }
    2851              :                         rootKeySpan                      = fabricDescriptor.rootPublicKey;
    2852              :                         info.JFAdminFabricTable.vendorId = fabricDescriptor.vendorID;
    2853              :                         info.JFAdminFabricTable.fabricId = fabricDescriptor.fabricID;
    2854              : 
    2855              :                         if (fabricDescriptor.VIDVerificationStatement.HasValue())
    2856              :                         {
    2857              :                             ChipLogError(Controller, "JCM: Per-home RCAC are not supported by JF for now!");
    2858              :                             return CHIP_ERROR_CANCELLED;
    2859              :                         }
    2860              :                         foundMatchingFabricIndex = true;
    2861              :                         ChipLogProgress(Controller, "JCM: Successfully parsed the Administrator Fabric Table");
    2862              :                         break;
    2863              :                     }
    2864              :                 }
    2865              :                 if (!foundMatchingFabricIndex)
    2866              :                 {
    2867              :                     return CHIP_ERROR_NOT_FOUND;
    2868              :                 }
    2869              :                 return CHIP_NO_ERROR;
    2870              :             }
    2871              :             case NOCs::Id: {
    2872              :                 NOCs::TypeInfo::DecodableType nocs;
    2873              :                 ReturnErrorOnFailure(this->mAttributeCache->Get<NOCs::TypeInfo>(path, nocs));
    2874              : 
    2875              :                 auto iter = nocs.begin();
    2876              :                 while (iter.Next())
    2877              :                 {
    2878              :                     auto & nocStruct = iter.GetValue();
    2879              : 
    2880              :                     if (nocStruct.fabricIndex == info.JFAdministratorFabricIndex)
    2881              :                     {
    2882              :                         info.JFAdminNOC = nocStruct.noc;
    2883              : 
    2884              :                         if (!nocStruct.icac.IsNull())
    2885              :                         {
    2886              :                             info.JFAdminICAC = nocStruct.icac.Value();
    2887              :                         }
    2888              :                         else
    2889              :                         {
    2890              :                             ChipLogError(Controller, "JCM: ICAC not present!");
    2891              :                             return CHIP_ERROR_CERT_NOT_FOUND;
    2892              :                         }
    2893              :                         ChipLogProgress(Controller, "JCM: Successfully parsed the Administrator NOC and ICAC");
    2894              :                         break;
    2895              :                     }
    2896              :                 }
    2897              :                 return CHIP_NO_ERROR;
    2898              :             }
    2899              :             default:
    2900              :                 return CHIP_NO_ERROR;
    2901              :             }
    2902              : 
    2903              :             return CHIP_NO_ERROR;
    2904              :         });
    2905              : 
    2906              :     if (!rootKeySpan.size() || (info.JFAdminFabricTable.fabricId == kUndefinedFabricId) || !info.JFAdminNOC.size() ||
    2907              :         !info.JFAdminICAC.size() || (err != CHIP_NO_ERROR))
    2908              :     {
    2909              :         info.JFAdministratorFabricIndex = kUndefinedFabricIndex;
    2910              :         return err;
    2911              :     }
    2912              : 
    2913              :     err = mAttributeCache->ForEachAttribute(
    2914              :         OperationalCredentials::Id, [this, &info, &rootKeySpan](const ConcreteAttributePath & path) {
    2915              :             using namespace chip::app::Clusters::OperationalCredentials::Attributes;
    2916              :             bool foundMatchingRcac = false;
    2917              : 
    2918              :             switch (path.mAttributeId)
    2919              :             {
    2920              :             case TrustedRootCertificates::Id: {
    2921              :                 TrustedRootCertificates::TypeInfo::DecodableType trustedCAs;
    2922              :                 ReturnErrorOnFailure(this->mAttributeCache->Get<TrustedRootCertificates::TypeInfo>(path, trustedCAs));
    2923              : 
    2924              :                 auto iter = trustedCAs.begin();
    2925              :                 while (iter.Next())
    2926              :                 {
    2927              :                     auto & trustedCA = iter.GetValue();
    2928              :                     P256PublicKeySpan trustedCAPublicKeySpan;
    2929              : 
    2930              :                     ReturnErrorOnFailure(ExtractPublicKeyFromChipCert(trustedCA, trustedCAPublicKeySpan));
    2931              :                     Crypto::P256PublicKey trustedCAPublicKey{ trustedCAPublicKeySpan };
    2932              : 
    2933              :                     P256PublicKeySpan rootPubKeySpan(rootKeySpan.data());
    2934              :                     Crypto::P256PublicKey fabricTableRootPublicKey{ rootPubKeySpan };
    2935              : 
    2936              :                     if (trustedCAPublicKey.Matches(fabricTableRootPublicKey))
    2937              :                     {
    2938              :                         info.JFAdminRCAC = trustedCA;
    2939              :                         ChipLogProgress(Controller, "JCM: Successfully parsed the Administrator RCAC");
    2940              :                         foundMatchingRcac = true;
    2941              :                         break;
    2942              :                     }
    2943              :                 }
    2944              :                 if (!foundMatchingRcac)
    2945              :                 {
    2946              :                     ChipLogError(Controller, "JCM: Cannot found a matching RCAC!");
    2947              :                     return CHIP_ERROR_CERT_NOT_FOUND;
    2948              :                 }
    2949              :                 return CHIP_NO_ERROR;
    2950              :             }
    2951              :             default:
    2952              :                 return CHIP_NO_ERROR;
    2953              :             }
    2954              :             return CHIP_NO_ERROR;
    2955              :         });
    2956              : 
    2957              :     if (!info.JFAdminRCAC.size())
    2958              :     {
    2959              :         info.JFAdministratorFabricIndex = kUndefinedFabricIndex;
    2960              :     }
    2961              : 
    2962              :     return err;
    2963              : }
    2964              : 
    2965              : CHIP_ERROR DeviceCommissioner::ValidateJFAdminNOC(const ByteSpan & adminNOC)
    2966              : {
    2967              :     CATValues cats;
    2968              : 
    2969              :     ExtractCATsFromOpCert(adminNOC, cats);
    2970              : 
    2971              :     if (!cats.ContainsIdentifier(kAdminCATIdentifier))
    2972              :     {
    2973              :         return CHIP_ERROR_NOT_FOUND;
    2974              :     }
    2975              : 
    2976              :     return CHIP_NO_ERROR;
    2977              : }
    2978              : 
    2979              : #endif // CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
    2980              : 
    2981            0 : void DeviceCommissioner::OnArmFailSafe(void * context,
    2982              :                                        const GeneralCommissioning::Commands::ArmFailSafeResponse::DecodableType & data)
    2983              : {
    2984            0 :     CommissioningDelegate::CommissioningReport report;
    2985            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    2986              : 
    2987            0 :     ChipLogProgress(Controller, "Received ArmFailSafe response errorCode=%u", to_underlying(data.errorCode));
    2988            0 :     if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
    2989              :     {
    2990            0 :         err = CHIP_ERROR_INTERNAL;
    2991            0 :         report.Set<CommissioningErrorInfo>(data.errorCode);
    2992              :     }
    2993              : 
    2994            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    2995            0 :     commissioner->CommissioningStageComplete(err, report);
    2996            0 : }
    2997              : 
    2998            0 : void DeviceCommissioner::OnSetRegulatoryConfigResponse(
    2999              :     void * context, const GeneralCommissioning::Commands::SetRegulatoryConfigResponse::DecodableType & data)
    3000              : {
    3001            0 :     CommissioningDelegate::CommissioningReport report;
    3002            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    3003              : 
    3004            0 :     ChipLogProgress(Controller, "Received SetRegulatoryConfig response errorCode=%u", to_underlying(data.errorCode));
    3005            0 :     if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
    3006              :     {
    3007            0 :         err = CHIP_ERROR_INTERNAL;
    3008            0 :         report.Set<CommissioningErrorInfo>(data.errorCode);
    3009              :     }
    3010            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3011            0 :     commissioner->CommissioningStageComplete(err, report);
    3012            0 : }
    3013              : 
    3014            0 : void DeviceCommissioner::OnSetTCAcknowledgementsResponse(
    3015              :     void * context, const GeneralCommissioning::Commands::SetTCAcknowledgementsResponse::DecodableType & data)
    3016              : {
    3017            0 :     CommissioningDelegate::CommissioningReport report;
    3018            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    3019              : 
    3020            0 :     ChipLogProgress(Controller, "Received SetTCAcknowledgements response errorCode=%u", to_underlying(data.errorCode));
    3021            0 :     if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
    3022              :     {
    3023            0 :         err = CHIP_ERROR_INTERNAL;
    3024            0 :         report.Set<CommissioningErrorInfo>(data.errorCode);
    3025              :     }
    3026            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3027            0 :     commissioner->CommissioningStageComplete(err, report);
    3028            0 : }
    3029              : 
    3030            0 : void DeviceCommissioner::OnSetTimeZoneResponse(void * context,
    3031              :                                                const TimeSynchronization::Commands::SetTimeZoneResponse::DecodableType & data)
    3032              : {
    3033            0 :     CommissioningDelegate::CommissioningReport report;
    3034            0 :     CHIP_ERROR err                    = CHIP_NO_ERROR;
    3035            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3036              :     TimeZoneResponseInfo info;
    3037            0 :     info.requiresDSTOffsets = data.DSTOffsetRequired;
    3038            0 :     report.Set<TimeZoneResponseInfo>(info);
    3039            0 :     commissioner->CommissioningStageComplete(err, report);
    3040            0 : }
    3041              : 
    3042            0 : void DeviceCommissioner::OnSetUTCError(void * context, CHIP_ERROR error)
    3043              : {
    3044              :     // For SetUTCTime, we don't actually care if the commissionee didn't want out time, that's its choice
    3045            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3046            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    3047            0 : }
    3048              : 
    3049            0 : void DeviceCommissioner::OnScanNetworksFailure(void * context, CHIP_ERROR error)
    3050              : {
    3051            0 :     ChipLogProgress(Controller, "Received ScanNetworks failure response %" CHIP_ERROR_FORMAT, error.Format());
    3052              : 
    3053            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3054              : 
    3055              :     // advance to the kNeedsNetworkCreds waiting step
    3056              :     // clear error so that we don't abort the commissioning when ScanNetworks fails
    3057            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    3058              : 
    3059            0 :     if (commissioner->GetPairingDelegate() != nullptr)
    3060              :     {
    3061            0 :         commissioner->GetPairingDelegate()->OnScanNetworksFailure(error);
    3062              :     }
    3063            0 : }
    3064              : 
    3065            0 : void DeviceCommissioner::OnScanNetworksResponse(void * context,
    3066              :                                                 const NetworkCommissioning::Commands::ScanNetworksResponse::DecodableType & data)
    3067              : {
    3068            0 :     CommissioningDelegate::CommissioningReport report;
    3069              : 
    3070            0 :     ChipLogProgress(Controller, "Received ScanNetwork response, networkingStatus=%u debugText=%s",
    3071              :                     to_underlying(data.networkingStatus),
    3072              :                     (data.debugText.HasValue() ? std::string(data.debugText.Value().data(), data.debugText.Value().size()).c_str()
    3073              :                                                : "none provided"));
    3074            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3075              : 
    3076              :     // advance to the kNeedsNetworkCreds waiting step
    3077            0 :     commissioner->CommissioningStageComplete(CHIP_NO_ERROR);
    3078              : 
    3079            0 :     if (commissioner->GetPairingDelegate() != nullptr)
    3080              :     {
    3081            0 :         commissioner->GetPairingDelegate()->OnScanNetworksSuccess(data);
    3082              :     }
    3083            0 : }
    3084              : 
    3085            0 : CHIP_ERROR DeviceCommissioner::NetworkCredentialsReady()
    3086              : {
    3087            0 :     VerifyOrReturnError(mCommissioningStage == CommissioningStage::kNeedsNetworkCreds, CHIP_ERROR_INCORRECT_STATE);
    3088              : 
    3089              :     // need to advance to next step
    3090            0 :     CommissioningStageComplete(CHIP_NO_ERROR);
    3091              : 
    3092            0 :     return CHIP_NO_ERROR;
    3093              : }
    3094              : 
    3095            0 : CHIP_ERROR DeviceCommissioner::ICDRegistrationInfoReady()
    3096              : {
    3097            0 :     VerifyOrReturnError(mCommissioningStage == CommissioningStage::kICDGetRegistrationInfo, CHIP_ERROR_INCORRECT_STATE);
    3098              : 
    3099              :     // need to advance to next step
    3100            0 :     CommissioningStageComplete(CHIP_NO_ERROR);
    3101              : 
    3102            0 :     return CHIP_NO_ERROR;
    3103              : }
    3104              : 
    3105            0 : void DeviceCommissioner::OnNetworkConfigResponse(void * context,
    3106              :                                                  const NetworkCommissioning::Commands::NetworkConfigResponse::DecodableType & data)
    3107              : {
    3108            0 :     CommissioningDelegate::CommissioningReport report;
    3109            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    3110              : 
    3111            0 :     ChipLogProgress(Controller, "Received NetworkConfig response, networkingStatus=%u", to_underlying(data.networkingStatus));
    3112            0 :     if (data.networkingStatus != NetworkCommissioning::NetworkCommissioningStatusEnum::kSuccess)
    3113              :     {
    3114            0 :         err = CHIP_ERROR_INTERNAL;
    3115            0 :         report.Set<NetworkCommissioningStatusInfo>(data.networkingStatus);
    3116              :     }
    3117            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3118            0 :     commissioner->CommissioningStageComplete(err, report);
    3119            0 : }
    3120              : 
    3121            0 : void DeviceCommissioner::OnConnectNetworkResponse(
    3122              :     void * context, const NetworkCommissioning::Commands::ConnectNetworkResponse::DecodableType & data)
    3123              : {
    3124            0 :     CommissioningDelegate::CommissioningReport report;
    3125            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    3126              : 
    3127            0 :     ChipLogProgress(Controller, "Received ConnectNetwork response, networkingStatus=%u", to_underlying(data.networkingStatus));
    3128            0 :     if (data.networkingStatus != NetworkCommissioning::NetworkCommissioningStatusEnum::kSuccess)
    3129              :     {
    3130            0 :         err = CHIP_ERROR_INTERNAL;
    3131            0 :         report.Set<NetworkCommissioningStatusInfo>(data.networkingStatus);
    3132              :     }
    3133            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3134            0 :     commissioner->CommissioningStageComplete(err, report);
    3135            0 : }
    3136              : 
    3137            0 : void DeviceCommissioner::OnCommissioningCompleteResponse(
    3138              :     void * context, const GeneralCommissioning::Commands::CommissioningCompleteResponse::DecodableType & data)
    3139              : {
    3140            0 :     CommissioningDelegate::CommissioningReport report;
    3141            0 :     CHIP_ERROR err = CHIP_NO_ERROR;
    3142              : 
    3143            0 :     ChipLogProgress(Controller, "Received CommissioningComplete response, errorCode=%u", to_underlying(data.errorCode));
    3144            0 :     if (data.errorCode != GeneralCommissioning::CommissioningErrorEnum::kOk)
    3145              :     {
    3146            0 :         err = CHIP_ERROR_INTERNAL;
    3147            0 :         report.Set<CommissioningErrorInfo>(data.errorCode);
    3148              :     }
    3149            0 :     DeviceCommissioner * commissioner = static_cast<DeviceCommissioner *>(context);
    3150            0 :     commissioner->CommissioningStageComplete(err, report);
    3151            0 : }
    3152              : 
    3153              : template <typename RequestObjectT>
    3154              : CHIP_ERROR
    3155            0 : DeviceCommissioner::SendCommissioningCommand(DeviceProxy * device, const RequestObjectT & request,
    3156              :                                              CommandResponseSuccessCallback<typename RequestObjectT::ResponseType> successCb,
    3157              :                                              CommandResponseFailureCallback failureCb, EndpointId endpoint,
    3158              :                                              Optional<System::Clock::Timeout> timeout, bool fireAndForget)
    3159              : 
    3160              : {
    3161              :     // Default behavior is to make sequential, cancellable calls tracked via mInvokeCancelFn.
    3162              :     // Fire-and-forget calls are not cancellable and don't receive `this` as context in callbacks.
    3163            0 :     VerifyOrDie(fireAndForget || !mInvokeCancelFn); // we don't make parallel (cancellable) calls
    3164              : 
    3165            0 :     void * context   = (!fireAndForget) ? this : nullptr;
    3166            0 :     auto onSuccessCb = [context, successCb](const app::ConcreteCommandPath & aPath, const app::StatusIB & aStatus,
    3167              :                                             const typename RequestObjectT::ResponseType & responseData) {
    3168            0 :         successCb(context, responseData);
    3169              :     };
    3170            0 :     auto onFailureCb = [context, failureCb](CHIP_ERROR aError) { failureCb(context, aError); };
    3171              : 
    3172            0 :     return InvokeCommandRequest(device->GetExchangeManager(), device->GetSecureSession().Value(), endpoint, request, onSuccessCb,
    3173            0 :                                 onFailureCb, NullOptional, timeout, (!fireAndForget) ? &mInvokeCancelFn : nullptr);
    3174              : }
    3175              : 
    3176              : template <typename AttrType>
    3177              : CHIP_ERROR DeviceCommissioner::SendCommissioningWriteRequest(DeviceProxy * device, EndpointId endpoint, ClusterId cluster,
    3178              :                                                              AttributeId attribute, const AttrType & requestData,
    3179              :                                                              WriteResponseSuccessCallback successCb,
    3180              :                                                              WriteResponseFailureCallback failureCb)
    3181              : {
    3182              :     VerifyOrDie(!mWriteCancelFn); // we don't make parallel (cancellable) calls
    3183              :     auto onSuccessCb = [this, successCb](const app::ConcreteAttributePath & aPath) { successCb(this); };
    3184              :     auto onFailureCb = [this, failureCb](const app::ConcreteAttributePath * aPath, CHIP_ERROR aError) { failureCb(this, aError); };
    3185              :     return WriteAttribute(device->GetSecureSession().Value(), endpoint, cluster, attribute, requestData, onSuccessCb, onFailureCb,
    3186              :                           /* aTimedWriteTimeoutMs = */ NullOptional, /* onDoneCb = */ nullptr, /* aDataVersion = */ NullOptional,
    3187              :                           /* outCancelFn = */ &mWriteCancelFn);
    3188              : }
    3189              : 
    3190            0 : void DeviceCommissioner::SendCommissioningReadRequest(DeviceProxy * proxy, Optional<System::Clock::Timeout> timeout,
    3191              :                                                       app::AttributePathParams * readPaths, size_t readPathsSize)
    3192              : {
    3193            0 :     VerifyOrDie(!mReadClient); // we don't perform parallel reads
    3194              : 
    3195            0 :     app::InteractionModelEngine * engine = app::InteractionModelEngine::GetInstance();
    3196            0 :     app::ReadPrepareParams readParams(proxy->GetSecureSession().Value());
    3197            0 :     readParams.mIsFabricFiltered = false;
    3198            0 :     if (timeout.HasValue())
    3199              :     {
    3200            0 :         readParams.mTimeout = timeout.Value();
    3201              :     }
    3202            0 :     readParams.mpAttributePathParamsList    = readPaths;
    3203            0 :     readParams.mAttributePathParamsListSize = readPathsSize;
    3204              : 
    3205              :     // Take ownership of the attribute cache, so it can be released if SendRequest fails.
    3206            0 :     auto attributeCache = std::move(mAttributeCache);
    3207              :     auto readClient     = chip::Platform::MakeUnique<app::ReadClient>(
    3208            0 :         engine, proxy->GetExchangeManager(), attributeCache->GetBufferedCallback(), app::ReadClient::InteractionType::Read);
    3209            0 :     CHIP_ERROR err = readClient->SendRequest(readParams);
    3210            0 :     if (err != CHIP_NO_ERROR)
    3211              :     {
    3212            0 :         ChipLogError(Controller, "Failed to send read request: %" CHIP_ERROR_FORMAT, err.Format());
    3213            0 :         CommissioningStageComplete(err);
    3214            0 :         return;
    3215              :     }
    3216            0 :     mAttributeCache = std::move(attributeCache);
    3217            0 :     mReadClient     = std::move(readClient);
    3218            0 : }
    3219              : 
    3220            0 : void DeviceCommissioner::PerformCommissioningStep(DeviceProxy * proxy, CommissioningStage step, CommissioningParameters & params,
    3221              :                                                   CommissioningDelegate * delegate, EndpointId endpoint,
    3222              :                                                   Optional<System::Clock::Timeout> timeout)
    3223              : 
    3224              : {
    3225              :     MATTER_LOG_METRIC(kMetricDeviceCommissionerCommissionStage, step);
    3226              :     MATTER_LOG_METRIC_BEGIN(MetricKeyForCommissioningStage(step));
    3227              : 
    3228            0 :     if (params.GetCompletionStatus().err == CHIP_NO_ERROR)
    3229              :     {
    3230            0 :         ChipLogProgress(Controller, "Performing next commissioning step '%s'", StageToString(step));
    3231              :     }
    3232              :     else
    3233              :     {
    3234            0 :         ChipLogProgress(Controller, "Performing next commissioning step '%s' with completion status = '%s'", StageToString(step),
    3235              :                         params.GetCompletionStatus().err.AsString());
    3236              :     }
    3237              : 
    3238            0 :     mCommissioningStepTimeout = timeout;
    3239            0 :     mCommissioningStage       = step;
    3240            0 :     mCommissioningDelegate    = delegate;
    3241            0 :     mDeviceBeingCommissioned  = proxy;
    3242              : 
    3243              :     // TODO: Extend timeouts to the DAC and Opcert requests.
    3244              :     // TODO(cecille): We probably want something better than this for breadcrumbs.
    3245            0 :     uint64_t breadcrumb = static_cast<uint64_t>(step);
    3246              : 
    3247            0 :     switch (step)
    3248              :     {
    3249            0 :     case CommissioningStage::kArmFailsafe: {
    3250            0 :         VerifyOrDie(endpoint == kRootEndpointId);
    3251              :         // Make sure the fail-safe value we set here actually ends up being used
    3252              :         // no matter what.
    3253            0 :         proxy->SetFailSafeExpirationTimestamp(System::Clock::kZero);
    3254            0 :         VerifyOrDie(ExtendArmFailSafeInternal(proxy, step, params.GetFailsafeTimerSeconds().ValueOr(kDefaultFailsafeTimeout),
    3255              :                                               timeout, OnArmFailSafe, OnBasicFailure, /* fireAndForget = */ false));
    3256              :     }
    3257            0 :     break;
    3258            0 :     case CommissioningStage::kReadCommissioningInfo: {
    3259            0 :         VerifyOrDie(endpoint == kRootEndpointId);
    3260            0 :         ChipLogProgress(Controller, "Sending read requests for commissioning information");
    3261              : 
    3262              :         // Allocate a ClusterStateCache to collect the data from our read requests.
    3263              :         // The cache will be released in:
    3264              :         // - SendCommissioningReadRequest when failing to send a read request.
    3265              :         // - FinishReadingCommissioningInfo when the ReadCommissioningInfo stage is completed.
    3266              :         // - CancelCommissioningInteractions
    3267            0 :         mAttributeCache = Platform::MakeUnique<app::ClusterStateCache>(*this);
    3268              : 
    3269              :         // Generally we need to make more than one read request, because as per spec a server only
    3270              :         // supports a limited number of paths per Read Interaction. Because the actual number of
    3271              :         // interactions we end up performing is dynamic, we track all of them within a single
    3272              :         // commissioning stage.
    3273            0 :         mReadCommissioningInfoProgress = 0;
    3274            0 :         ContinueReadingCommissioningInfo(params); // Note: assume params == delegate.GetCommissioningParameters()
    3275            0 :         break;
    3276              :     }
    3277            0 :     case CommissioningStage::kConfigureUTCTime: {
    3278            0 :         TimeSynchronization::Commands::SetUTCTime::Type request;
    3279            0 :         uint64_t kChipEpochUsSinceUnixEpoch = static_cast<uint64_t>(kChipEpochSecondsSinceUnixEpoch) * chip::kMicrosecondsPerSecond;
    3280              :         System::Clock::Microseconds64 utcTime;
    3281            0 :         if (System::SystemClock().GetClock_RealTime(utcTime) != CHIP_NO_ERROR || utcTime.count() <= kChipEpochUsSinceUnixEpoch)
    3282              :         {
    3283              :             // We have no time to give, but that's OK, just complete this stage
    3284            0 :             CommissioningStageComplete(CHIP_NO_ERROR);
    3285            0 :             return;
    3286              :         }
    3287              : 
    3288            0 :         request.UTCTime = utcTime.count() - kChipEpochUsSinceUnixEpoch;
    3289              :         // For now, we assume a seconds granularity
    3290            0 :         request.granularity = TimeSynchronization::GranularityEnum::kSecondsGranularity;
    3291            0 :         CHIP_ERROR err      = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnSetUTCError, endpoint, timeout);
    3292            0 :         if (err != CHIP_NO_ERROR)
    3293              :         {
    3294              :             // We won't get any async callbacks here, so just complete our stage.
    3295            0 :             ChipLogError(Controller, "Failed to send SetUTCTime command: %" CHIP_ERROR_FORMAT, err.Format());
    3296            0 :             CommissioningStageComplete(err);
    3297            0 :             return;
    3298              :         }
    3299            0 :         break;
    3300              :     }
    3301            0 :     case CommissioningStage::kConfigureTimeZone: {
    3302            0 :         if (!params.GetTimeZone().HasValue())
    3303              :         {
    3304            0 :             ChipLogError(Controller, "ConfigureTimeZone stage called with no time zone data");
    3305            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3306            0 :             return;
    3307              :         }
    3308            0 :         TimeSynchronization::Commands::SetTimeZone::Type request;
    3309            0 :         request.timeZone = params.GetTimeZone().Value();
    3310            0 :         CHIP_ERROR err   = SendCommissioningCommand(proxy, request, OnSetTimeZoneResponse, OnBasicFailure, endpoint, timeout);
    3311            0 :         if (err != CHIP_NO_ERROR)
    3312              :         {
    3313              :             // We won't get any async callbacks here, so just complete our stage.
    3314            0 :             ChipLogError(Controller, "Failed to send SetTimeZone command: %" CHIP_ERROR_FORMAT, err.Format());
    3315            0 :             CommissioningStageComplete(err);
    3316            0 :             return;
    3317              :         }
    3318            0 :         break;
    3319              :     }
    3320            0 :     case CommissioningStage::kConfigureDSTOffset: {
    3321            0 :         if (!params.GetDSTOffsets().HasValue())
    3322              :         {
    3323            0 :             ChipLogError(Controller, "ConfigureDSTOffset stage called with no DST data");
    3324            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3325            0 :             return;
    3326              :         }
    3327            0 :         TimeSynchronization::Commands::SetDSTOffset::Type request;
    3328            0 :         request.DSTOffset = params.GetDSTOffsets().Value();
    3329            0 :         CHIP_ERROR err    = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnBasicFailure, endpoint, timeout);
    3330            0 :         if (err != CHIP_NO_ERROR)
    3331              :         {
    3332              :             // We won't get any async callbacks here, so just complete our stage.
    3333            0 :             ChipLogError(Controller, "Failed to send SetDSTOffset command: %" CHIP_ERROR_FORMAT, err.Format());
    3334            0 :             CommissioningStageComplete(err);
    3335            0 :             return;
    3336              :         }
    3337            0 :         break;
    3338              :     }
    3339            0 :     case CommissioningStage::kConfigureDefaultNTP: {
    3340            0 :         if (!params.GetDefaultNTP().HasValue())
    3341              :         {
    3342            0 :             ChipLogError(Controller, "ConfigureDefaultNTP stage called with no default NTP data");
    3343            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3344            0 :             return;
    3345              :         }
    3346            0 :         TimeSynchronization::Commands::SetDefaultNTP::Type request;
    3347            0 :         request.defaultNTP = params.GetDefaultNTP().Value();
    3348            0 :         CHIP_ERROR err     = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnBasicFailure, endpoint, timeout);
    3349            0 :         if (err != CHIP_NO_ERROR)
    3350              :         {
    3351              :             // We won't get any async callbacks here, so just complete our stage.
    3352            0 :             ChipLogError(Controller, "Failed to send SetDefaultNTP command: %" CHIP_ERROR_FORMAT, err.Format());
    3353            0 :             CommissioningStageComplete(err);
    3354            0 :             return;
    3355              :         }
    3356            0 :         break;
    3357              :     }
    3358            0 :     case CommissioningStage::kScanNetworks: {
    3359            0 :         NetworkCommissioning::Commands::ScanNetworks::Type request;
    3360            0 :         if (params.GetWiFiCredentials().HasValue())
    3361              :         {
    3362            0 :             request.ssid.Emplace(params.GetWiFiCredentials().Value().ssid);
    3363              :         }
    3364            0 :         request.breadcrumb.Emplace(breadcrumb);
    3365            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnScanNetworksResponse, OnScanNetworksFailure, endpoint, timeout);
    3366            0 :         if (err != CHIP_NO_ERROR)
    3367              :         {
    3368              :             // We won't get any async callbacks here, so just complete our stage.
    3369            0 :             ChipLogError(Controller, "Failed to send ScanNetworks command: %" CHIP_ERROR_FORMAT, err.Format());
    3370            0 :             CommissioningStageComplete(err);
    3371            0 :             return;
    3372              :         }
    3373            0 :         break;
    3374              :     }
    3375            0 :     case CommissioningStage::kNeedsNetworkCreds: {
    3376              :         // nothing to do, the OnScanNetworksSuccess and OnScanNetworksFailure callbacks provide indication to the
    3377              :         // DevicePairingDelegate that network credentials are needed.
    3378            0 :         break;
    3379              :     }
    3380            0 :     case CommissioningStage::kConfigRegulatory: {
    3381              :         // TODO(cecille): Worthwhile to keep this around as part of the class?
    3382              :         // TODO(cecille): Where is the country config actually set?
    3383            0 :         ChipLogProgress(Controller, "Setting Regulatory Config");
    3384              :         auto capability =
    3385            0 :             params.GetLocationCapability().ValueOr(app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum::kOutdoor);
    3386              :         app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum regulatoryConfig;
    3387              :         // Value is only switchable on the devices with indoor/outdoor capability
    3388            0 :         if (capability == app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum::kIndoorOutdoor)
    3389              :         {
    3390              :             // If the device supports indoor and outdoor configs, use the setting from the commissioner, otherwise fall back to
    3391              :             // the current device setting then to outdoor (most restrictive)
    3392            0 :             if (params.GetDeviceRegulatoryLocation().HasValue())
    3393              :             {
    3394            0 :                 regulatoryConfig = params.GetDeviceRegulatoryLocation().Value();
    3395            0 :                 ChipLogProgress(Controller, "Setting regulatory config to %u from commissioner override",
    3396              :                                 static_cast<uint8_t>(regulatoryConfig));
    3397              :             }
    3398            0 :             else if (params.GetDefaultRegulatoryLocation().HasValue())
    3399              :             {
    3400            0 :                 regulatoryConfig = params.GetDefaultRegulatoryLocation().Value();
    3401            0 :                 ChipLogProgress(Controller, "No regulatory config supplied by controller, leaving as device default (%u)",
    3402              :                                 static_cast<uint8_t>(regulatoryConfig));
    3403              :             }
    3404              :             else
    3405              :             {
    3406            0 :                 regulatoryConfig = app::Clusters::GeneralCommissioning::RegulatoryLocationTypeEnum::kOutdoor;
    3407            0 :                 ChipLogProgress(Controller, "No overrride or device regulatory config supplied, setting to outdoor");
    3408              :             }
    3409              :         }
    3410              :         else
    3411              :         {
    3412            0 :             ChipLogProgress(Controller, "Device does not support configurable regulatory location");
    3413            0 :             regulatoryConfig = capability;
    3414              :         }
    3415              : 
    3416            0 :         CharSpan countryCode;
    3417            0 :         const auto & providedCountryCode = params.GetCountryCode();
    3418            0 :         if (providedCountryCode.HasValue())
    3419              :         {
    3420            0 :             countryCode = providedCountryCode.Value();
    3421              :         }
    3422              :         else
    3423              :         {
    3424              :             // Default to "XX", for lack of anything better.
    3425            0 :             countryCode = "XX"_span;
    3426              :         }
    3427              : 
    3428            0 :         GeneralCommissioning::Commands::SetRegulatoryConfig::Type request;
    3429            0 :         request.newRegulatoryConfig = regulatoryConfig;
    3430            0 :         request.countryCode         = countryCode;
    3431            0 :         request.breadcrumb          = breadcrumb;
    3432            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnSetRegulatoryConfigResponse, OnBasicFailure, endpoint, timeout);
    3433            0 :         if (err != CHIP_NO_ERROR)
    3434              :         {
    3435              :             // We won't get any async callbacks here, so just complete our stage.
    3436            0 :             ChipLogError(Controller, "Failed to send SetRegulatoryConfig command: %" CHIP_ERROR_FORMAT, err.Format());
    3437            0 :             CommissioningStageComplete(err);
    3438            0 :             return;
    3439              :         }
    3440              :     }
    3441            0 :     break;
    3442            0 :     case CommissioningStage::kConfigureTCAcknowledgments: {
    3443            0 :         ChipLogProgress(Controller, "Setting Terms and Conditions");
    3444              : 
    3445            0 :         if (!params.GetTermsAndConditionsAcknowledgement().HasValue())
    3446              :         {
    3447            0 :             ChipLogProgress(Controller, "Setting Terms and Conditions: Skipped");
    3448            0 :             CommissioningStageComplete(CHIP_NO_ERROR);
    3449            0 :             return;
    3450              :         }
    3451              : 
    3452            0 :         GeneralCommissioning::Commands::SetTCAcknowledgements::Type request;
    3453            0 :         TermsAndConditionsAcknowledgement termsAndConditionsAcknowledgement = params.GetTermsAndConditionsAcknowledgement().Value();
    3454            0 :         request.TCUserResponse = termsAndConditionsAcknowledgement.acceptedTermsAndConditions;
    3455            0 :         request.TCVersion      = termsAndConditionsAcknowledgement.acceptedTermsAndConditionsVersion;
    3456              : 
    3457            0 :         ChipLogProgress(Controller, "Setting Terms and Conditions: %hu, %hu", request.TCUserResponse, request.TCVersion);
    3458              :         CHIP_ERROR err =
    3459            0 :             SendCommissioningCommand(proxy, request, OnSetTCAcknowledgementsResponse, OnBasicFailure, endpoint, timeout);
    3460            0 :         if (err != CHIP_NO_ERROR)
    3461              :         {
    3462            0 :             ChipLogError(Controller, "Failed to send SetTCAcknowledgements command: %" CHIP_ERROR_FORMAT, err.Format());
    3463            0 :             CommissioningStageComplete(err);
    3464            0 :             return;
    3465              :         }
    3466            0 :         break;
    3467              :     }
    3468            0 :     case CommissioningStage::kSendPAICertificateRequest: {
    3469            0 :         ChipLogProgress(Controller, "Sending request for PAI certificate");
    3470            0 :         CHIP_ERROR err = SendCertificateChainRequestCommand(proxy, CertificateType::kPAI, timeout);
    3471            0 :         if (err != CHIP_NO_ERROR)
    3472              :         {
    3473              :             // We won't get any async callbacks here, so just complete our stage.
    3474            0 :             ChipLogError(Controller, "Failed to send CertificateChainRequest command to get PAI: %" CHIP_ERROR_FORMAT,
    3475              :                          err.Format());
    3476            0 :             CommissioningStageComplete(err);
    3477            0 :             return;
    3478              :         }
    3479            0 :         break;
    3480              :     }
    3481            0 :     case CommissioningStage::kSendDACCertificateRequest: {
    3482            0 :         ChipLogProgress(Controller, "Sending request for DAC certificate");
    3483            0 :         CHIP_ERROR err = SendCertificateChainRequestCommand(proxy, CertificateType::kDAC, timeout);
    3484            0 :         if (err != CHIP_NO_ERROR)
    3485              :         {
    3486              :             // We won't get any async callbacks here, so just complete our stage.
    3487            0 :             ChipLogError(Controller, "Failed to send CertificateChainRequest command to get DAC: %" CHIP_ERROR_FORMAT,
    3488              :                          err.Format());
    3489            0 :             CommissioningStageComplete(err);
    3490            0 :             return;
    3491              :         }
    3492            0 :         break;
    3493              :     }
    3494            0 :     case CommissioningStage::kSendAttestationRequest: {
    3495            0 :         ChipLogProgress(Controller, "Sending Attestation Request to the device.");
    3496            0 :         if (!params.GetAttestationNonce().HasValue())
    3497              :         {
    3498            0 :             ChipLogError(Controller, "No attestation nonce found");
    3499            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3500            0 :             return;
    3501              :         }
    3502            0 :         CHIP_ERROR err = SendAttestationRequestCommand(proxy, params.GetAttestationNonce().Value(), timeout);
    3503            0 :         if (err != CHIP_NO_ERROR)
    3504              :         {
    3505              :             // We won't get any async callbacks here, so just complete our stage.
    3506            0 :             ChipLogError(Controller, "Failed to send AttestationRequest command: %" CHIP_ERROR_FORMAT, err.Format());
    3507            0 :             CommissioningStageComplete(err);
    3508            0 :             return;
    3509              :         }
    3510            0 :         break;
    3511              :     }
    3512            0 :     case CommissioningStage::kAttestationVerification: {
    3513            0 :         ChipLogProgress(Controller, "Verifying attestation");
    3514            0 :         if (IsAttestationInformationMissing(params))
    3515              :         {
    3516            0 :             ChipLogError(Controller, "Missing attestation information");
    3517            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3518            0 :             return;
    3519              :         }
    3520              : 
    3521              :         DeviceAttestationVerifier::AttestationInfo info(
    3522            0 :             params.GetAttestationElements().Value(),
    3523            0 :             proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge(),
    3524            0 :             params.GetAttestationSignature().Value(), params.GetPAI().Value(), params.GetDAC().Value(),
    3525            0 :             params.GetAttestationNonce().Value(), params.GetRemoteVendorId().Value(), params.GetRemoteProductId().Value());
    3526              : 
    3527            0 :         if (ValidateAttestationInfo(info) != CHIP_NO_ERROR)
    3528              :         {
    3529            0 :             ChipLogError(Controller, "Error validating attestation information");
    3530            0 :             CommissioningStageComplete(CHIP_ERROR_FAILED_DEVICE_ATTESTATION);
    3531            0 :             return;
    3532              :         }
    3533              :     }
    3534            0 :     break;
    3535            0 :     case CommissioningStage::kAttestationRevocationCheck: {
    3536            0 :         ChipLogProgress(Controller, "Verifying device's DAC chain revocation status");
    3537            0 :         if (IsAttestationInformationMissing(params))
    3538              :         {
    3539            0 :             ChipLogError(Controller, "Missing attestation information");
    3540            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3541            0 :             return;
    3542              :         }
    3543              : 
    3544              :         DeviceAttestationVerifier::AttestationInfo info(
    3545            0 :             params.GetAttestationElements().Value(),
    3546            0 :             proxy->GetSecureSession().Value()->AsSecureSession()->GetCryptoContext().GetAttestationChallenge(),
    3547            0 :             params.GetAttestationSignature().Value(), params.GetPAI().Value(), params.GetDAC().Value(),
    3548            0 :             params.GetAttestationNonce().Value(), params.GetRemoteVendorId().Value(), params.GetRemoteProductId().Value());
    3549              : 
    3550            0 :         if (CheckForRevokedDACChain(info) != CHIP_NO_ERROR)
    3551              :         {
    3552            0 :             ChipLogError(Controller, "Error validating device's DAC chain revocation status");
    3553            0 :             CommissioningStageComplete(CHIP_ERROR_FAILED_DEVICE_ATTESTATION);
    3554            0 :             return;
    3555              :         }
    3556              :     }
    3557            0 :     break;
    3558              : 
    3559            0 :     case CommissioningStage::kJFValidateNOC:
    3560              : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
    3561              :     {
    3562              :         if (!params.GetJFAdministratorFabricIndex().HasValue() || !params.GetJFAdminNOC().HasValue() ||
    3563              :             params.GetJFAdministratorFabricIndex().Value() == kUndefinedFabricIndex)
    3564              :         {
    3565              :             ChipLogError(Controller, "JCM: No JF Admin Values found");
    3566              :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3567              :             return;
    3568              :         }
    3569              : 
    3570              :         CHIP_ERROR err = ValidateJFAdminNOC(params.GetJFAdminNOC().Value());
    3571              : 
    3572              :         if (err != CHIP_NO_ERROR)
    3573              :         {
    3574              :             ChipLogError(Controller, "JCM: Cannot validate JFAdminNOC");
    3575              :         }
    3576              : 
    3577              :         CommissioningStageComplete(err);
    3578              : 
    3579              :         break;
    3580              :     }
    3581              : #endif
    3582              : 
    3583              :     case CommissioningStage::kSendVIDVerificationRequest:
    3584              : #if CHIP_DEVICE_CONFIG_ENABLE_JOINT_FABRIC
    3585              :     {
    3586              :         /* TODO: send SignVidVerificationRequest */
    3587              :         CommissioningStageComplete(CHIP_NO_ERROR);
    3588              :         break;
    3589              :     }
    3590              : #endif
    3591              : 
    3592              :     case CommissioningStage::kSendOpCertSigningRequest: {
    3593            0 :         if (!params.GetCSRNonce().HasValue())
    3594              :         {
    3595            0 :             ChipLogError(Controller, "No CSR nonce found");
    3596            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3597            0 :             return;
    3598              :         }
    3599            0 :         CHIP_ERROR err = SendOperationalCertificateSigningRequestCommand(proxy, params.GetCSRNonce().Value(), timeout);
    3600            0 :         if (err != CHIP_NO_ERROR)
    3601              :         {
    3602              :             // We won't get any async callbacks here, so just complete our stage.
    3603            0 :             ChipLogError(Controller, "Failed to send CSR request: %" CHIP_ERROR_FORMAT, err.Format());
    3604            0 :             CommissioningStageComplete(err);
    3605            0 :             return;
    3606              :         }
    3607            0 :         break;
    3608              :     }
    3609            0 :     case CommissioningStage::kValidateCSR: {
    3610            0 :         if (!params.GetNOCChainGenerationParameters().HasValue() || !params.GetDAC().HasValue() || !params.GetCSRNonce().HasValue())
    3611              :         {
    3612            0 :             ChipLogError(Controller, "Unable to validate CSR");
    3613            0 :             return CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3614              :         }
    3615              :         // This is non-blocking, so send the callback immediately.
    3616            0 :         CHIP_ERROR err = ValidateCSR(proxy, params.GetNOCChainGenerationParameters().Value().nocsrElements,
    3617            0 :                                      params.GetNOCChainGenerationParameters().Value().signature, params.GetDAC().Value(),
    3618            0 :                                      params.GetCSRNonce().Value());
    3619            0 :         if (err != CHIP_NO_ERROR)
    3620              :         {
    3621            0 :             ChipLogError(Controller, "Unable to validate CSR");
    3622              :         }
    3623            0 :         CommissioningStageComplete(err);
    3624            0 :         return;
    3625              :     }
    3626              :     break;
    3627            0 :     case CommissioningStage::kGenerateNOCChain: {
    3628            0 :         if (!params.GetNOCChainGenerationParameters().HasValue() || !params.GetDAC().HasValue() || !params.GetPAI().HasValue() ||
    3629            0 :             !params.GetCSRNonce().HasValue())
    3630              :         {
    3631            0 :             ChipLogError(Controller, "Unable to generate NOC chain parameters");
    3632            0 :             return CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3633              :         }
    3634            0 :         CHIP_ERROR err = ProcessCSR(proxy, params.GetNOCChainGenerationParameters().Value().nocsrElements,
    3635            0 :                                     params.GetNOCChainGenerationParameters().Value().signature, params.GetDAC().Value(),
    3636            0 :                                     params.GetPAI().Value(), params.GetCSRNonce().Value());
    3637            0 :         if (err != CHIP_NO_ERROR)
    3638              :         {
    3639            0 :             ChipLogError(Controller, "Unable to process Op CSR");
    3640              :             // Handle error, and notify session failure to the commissioner application.
    3641            0 :             ChipLogError(Controller, "Failed to process the certificate signing request");
    3642              :             // TODO: Map error status to correct error code
    3643            0 :             CommissioningStageComplete(err);
    3644            0 :             return;
    3645              :         }
    3646              :     }
    3647            0 :     break;
    3648            0 :     case CommissioningStage::kSendTrustedRootCert: {
    3649            0 :         if (!params.GetRootCert().HasValue() || !params.GetNoc().HasValue())
    3650              :         {
    3651            0 :             ChipLogError(Controller, "No trusted root cert or NOC specified");
    3652            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3653            0 :             return;
    3654              :         }
    3655            0 :         CHIP_ERROR err = SendTrustedRootCertificate(proxy, params.GetRootCert().Value(), timeout);
    3656            0 :         if (err != CHIP_NO_ERROR)
    3657              :         {
    3658            0 :             ChipLogError(Controller, "Error sending trusted root certificate: %" CHIP_ERROR_FORMAT, err.Format());
    3659            0 :             CommissioningStageComplete(err);
    3660            0 :             return;
    3661              :         }
    3662              : 
    3663            0 :         err = proxy->SetPeerId(params.GetRootCert().Value(), params.GetNoc().Value());
    3664            0 :         if (err != CHIP_NO_ERROR)
    3665              :         {
    3666            0 :             ChipLogError(Controller, "Error setting peer id: %s", err.AsString());
    3667            0 :             CommissioningStageComplete(err);
    3668            0 :             return;
    3669              :         }
    3670            0 :         if (!IsOperationalNodeId(proxy->GetDeviceId()))
    3671              :         {
    3672            0 :             ChipLogError(Controller, "Given node ID is not an operational node ID");
    3673            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3674            0 :             return;
    3675              :         }
    3676              :     }
    3677            0 :     break;
    3678            0 :     case CommissioningStage::kSendNOC: {
    3679            0 :         if (!params.GetNoc().HasValue() || !params.GetIpk().HasValue() || !params.GetAdminSubject().HasValue())
    3680              :         {
    3681            0 :             ChipLogError(Controller, "AddNOC contents not specified");
    3682            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3683            0 :             return;
    3684              :         }
    3685            0 :         CHIP_ERROR err = SendOperationalCertificate(proxy, params.GetNoc().Value(), params.GetIcac(), params.GetIpk().Value(),
    3686            0 :                                                     params.GetAdminSubject().Value(), timeout);
    3687            0 :         if (err != CHIP_NO_ERROR)
    3688              :         {
    3689              :             // We won't get any async callbacks here, so just complete our stage.
    3690            0 :             ChipLogError(Controller, "Error sending operational certificate: %" CHIP_ERROR_FORMAT, err.Format());
    3691            0 :             CommissioningStageComplete(err);
    3692            0 :             return;
    3693              :         }
    3694            0 :         break;
    3695              :     }
    3696            0 :     case CommissioningStage::kConfigureTrustedTimeSource: {
    3697            0 :         if (!params.GetTrustedTimeSource().HasValue())
    3698              :         {
    3699            0 :             ChipLogError(Controller, "ConfigureTrustedTimeSource stage called with no trusted time source data");
    3700            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3701            0 :             return;
    3702              :         }
    3703            0 :         TimeSynchronization::Commands::SetTrustedTimeSource::Type request;
    3704            0 :         request.trustedTimeSource = params.GetTrustedTimeSource().Value();
    3705            0 :         CHIP_ERROR err            = SendCommissioningCommand(proxy, request, OnBasicSuccess, OnBasicFailure, endpoint, timeout);
    3706            0 :         if (err != CHIP_NO_ERROR)
    3707              :         {
    3708              :             // We won't get any async callbacks here, so just complete our stage.
    3709            0 :             ChipLogError(Controller, "Failed to send SendTrustedTimeSource command: %" CHIP_ERROR_FORMAT, err.Format());
    3710            0 :             CommissioningStageComplete(err);
    3711            0 :             return;
    3712              :         }
    3713            0 :         break;
    3714              :     }
    3715            0 :     case CommissioningStage::kWiFiNetworkSetup: {
    3716            0 :         if (!params.GetWiFiCredentials().HasValue())
    3717              :         {
    3718            0 :             ChipLogError(Controller, "No wifi credentials specified");
    3719            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3720            0 :             return;
    3721              :         }
    3722              : 
    3723            0 :         NetworkCommissioning::Commands::AddOrUpdateWiFiNetwork::Type request;
    3724            0 :         request.ssid        = params.GetWiFiCredentials().Value().ssid;
    3725            0 :         request.credentials = params.GetWiFiCredentials().Value().credentials;
    3726            0 :         request.breadcrumb.Emplace(breadcrumb);
    3727            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
    3728            0 :         if (err != CHIP_NO_ERROR)
    3729              :         {
    3730              :             // We won't get any async callbacks here, so just complete our stage.
    3731            0 :             ChipLogError(Controller, "Failed to send AddOrUpdateWiFiNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3732            0 :             CommissioningStageComplete(err);
    3733            0 :             return;
    3734              :         }
    3735              :     }
    3736            0 :     break;
    3737            0 :     case CommissioningStage::kThreadNetworkSetup: {
    3738            0 :         if (!params.GetThreadOperationalDataset().HasValue())
    3739              :         {
    3740            0 :             ChipLogError(Controller, "No thread credentials specified");
    3741            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3742            0 :             return;
    3743              :         }
    3744            0 :         NetworkCommissioning::Commands::AddOrUpdateThreadNetwork::Type request;
    3745            0 :         request.operationalDataset = params.GetThreadOperationalDataset().Value();
    3746            0 :         request.breadcrumb.Emplace(breadcrumb);
    3747            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
    3748            0 :         if (err != CHIP_NO_ERROR)
    3749              :         {
    3750              :             // We won't get any async callbacks here, so just complete our stage.
    3751            0 :             ChipLogError(Controller, "Failed to send AddOrUpdateThreadNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3752            0 :             CommissioningStageComplete(err);
    3753            0 :             return;
    3754              :         }
    3755              :     }
    3756            0 :     break;
    3757            0 :     case CommissioningStage::kFailsafeBeforeWiFiEnable:
    3758              :         FALLTHROUGH;
    3759              :     case CommissioningStage::kFailsafeBeforeThreadEnable:
    3760              :         // Before we try to do network enablement, make sure that our fail-safe
    3761              :         // is set far enough out that we can later try to do operational
    3762              :         // discovery without it timing out.
    3763            0 :         ExtendFailsafeBeforeNetworkEnable(proxy, params, step);
    3764            0 :         break;
    3765            0 :     case CommissioningStage::kWiFiNetworkEnable: {
    3766            0 :         if (!params.GetWiFiCredentials().HasValue())
    3767              :         {
    3768            0 :             ChipLogError(Controller, "No wifi credentials specified");
    3769            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3770            0 :             return;
    3771              :         }
    3772            0 :         NetworkCommissioning::Commands::ConnectNetwork::Type request;
    3773            0 :         request.networkID = params.GetWiFiCredentials().Value().ssid;
    3774            0 :         request.breadcrumb.Emplace(breadcrumb);
    3775              : 
    3776            0 :         CHIP_ERROR err = CHIP_NO_ERROR;
    3777            0 :         ChipLogProgress(Controller, "SendCommand kWiFiNetworkEnable, supportsConcurrentConnection=%s",
    3778              :                         params.GetSupportsConcurrentConnection().HasValue()
    3779              :                             ? (params.GetSupportsConcurrentConnection().Value() ? "true" : "false")
    3780              :                             : "missing");
    3781            0 :         err = SendCommissioningCommand(proxy, request, OnConnectNetworkResponse, OnBasicFailure, endpoint, timeout);
    3782              : 
    3783            0 :         if (err != CHIP_NO_ERROR)
    3784              :         {
    3785              :             // We won't get any async callbacks here, so just complete our stage.
    3786            0 :             ChipLogError(Controller, "Failed to send WiFi ConnectNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3787            0 :             CommissioningStageComplete(err);
    3788            0 :             return;
    3789              :         }
    3790              :     }
    3791            0 :     break;
    3792            0 :     case CommissioningStage::kThreadNetworkEnable: {
    3793            0 :         ByteSpan extendedPanId;
    3794            0 :         chip::Thread::OperationalDataset operationalDataset;
    3795            0 :         if (!params.GetThreadOperationalDataset().HasValue() ||
    3796            0 :             operationalDataset.Init(params.GetThreadOperationalDataset().Value()) != CHIP_NO_ERROR ||
    3797            0 :             operationalDataset.GetExtendedPanIdAsByteSpan(extendedPanId) != CHIP_NO_ERROR)
    3798              :         {
    3799            0 :             ChipLogError(Controller, "Unable to get extended pan ID for thread operational dataset\n");
    3800            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3801            0 :             return;
    3802              :         }
    3803            0 :         NetworkCommissioning::Commands::ConnectNetwork::Type request;
    3804            0 :         request.networkID = extendedPanId;
    3805            0 :         request.breadcrumb.Emplace(breadcrumb);
    3806            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnConnectNetworkResponse, OnBasicFailure, endpoint, timeout);
    3807            0 :         if (err != CHIP_NO_ERROR)
    3808              :         {
    3809              :             // We won't get any async callbacks here, so just complete our stage.
    3810            0 :             ChipLogError(Controller, "Failed to send Thread ConnectNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3811            0 :             CommissioningStageComplete(err);
    3812            0 :             return;
    3813              :         }
    3814              :     }
    3815            0 :     break;
    3816            0 :     case CommissioningStage::kICDGetRegistrationInfo: {
    3817            0 :         GetPairingDelegate()->OnICDRegistrationInfoRequired();
    3818            0 :         return;
    3819              :     }
    3820              :     break;
    3821            0 :     case CommissioningStage::kICDRegistration: {
    3822            0 :         IcdManagement::Commands::RegisterClient::Type request;
    3823              : 
    3824            0 :         if (!(params.GetICDCheckInNodeId().HasValue() && params.GetICDMonitoredSubject().HasValue() &&
    3825            0 :               params.GetICDSymmetricKey().HasValue()))
    3826              :         {
    3827            0 :             ChipLogError(Controller, "No ICD Registration information provided!");
    3828            0 :             CommissioningStageComplete(CHIP_ERROR_INCORRECT_STATE);
    3829            0 :             return;
    3830              :         }
    3831              : 
    3832            0 :         request.checkInNodeID    = params.GetICDCheckInNodeId().Value();
    3833            0 :         request.monitoredSubject = params.GetICDMonitoredSubject().Value();
    3834            0 :         request.key              = params.GetICDSymmetricKey().Value();
    3835              : 
    3836              :         CHIP_ERROR err =
    3837            0 :             SendCommissioningCommand(proxy, request, OnICDManagementRegisterClientResponse, OnBasicFailure, endpoint, timeout);
    3838            0 :         if (err != CHIP_NO_ERROR)
    3839              :         {
    3840              :             // We won't get any async callbacks here, so just complete our stage.
    3841            0 :             ChipLogError(Controller, "Failed to send IcdManagement.RegisterClient command: %" CHIP_ERROR_FORMAT, err.Format());
    3842            0 :             CommissioningStageComplete(err);
    3843            0 :             return;
    3844              :         }
    3845              :     }
    3846            0 :     break;
    3847            0 :     case CommissioningStage::kEvictPreviousCaseSessions: {
    3848            0 :         auto scopedPeerId = GetPeerScopedId(proxy->GetDeviceId());
    3849              : 
    3850              :         // If we ever had a commissioned device with this node ID before, we may
    3851              :         // have stale sessions to it.  Make sure we don't re-use any of those,
    3852              :         // because clearly they are not related to this new device we are
    3853              :         // commissioning.  We only care about sessions we might reuse, so just
    3854              :         // clearing the ones associated with our fabric index is good enough and
    3855              :         // we don't need to worry about ExpireAllSessionsOnLogicalFabric.
    3856            0 :         mSystemState->SessionMgr()->ExpireAllSessions(scopedPeerId);
    3857            0 :         CommissioningStageComplete(CHIP_NO_ERROR);
    3858            0 :         return;
    3859              :     }
    3860            0 :     case CommissioningStage::kFindOperationalForStayActive:
    3861              :     case CommissioningStage::kFindOperationalForCommissioningComplete: {
    3862              :         // If there is an error, CommissioningStageComplete will be called from OnDeviceConnectionFailureFn.
    3863            0 :         auto scopedPeerId = GetPeerScopedId(proxy->GetDeviceId());
    3864              :         MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissioningOperationalSetup);
    3865            0 :         mSystemState->CASESessionMgr()->FindOrEstablishSession(scopedPeerId, &mOnDeviceConnectedCallback,
    3866              :                                                                &mOnDeviceConnectionFailureCallback
    3867              : #if CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
    3868              :                                                                ,
    3869              :                                                                /* attemptCount = */ 3, &mOnDeviceConnectionRetryCallback
    3870              : #endif // CHIP_DEVICE_CONFIG_ENABLE_AUTOMATIC_CASE_RETRIES
    3871              :         );
    3872              :     }
    3873            0 :     break;
    3874            0 :     case CommissioningStage::kPrimaryOperationalNetworkFailed: {
    3875              :         // nothing to do. This stage indicates that the primary operational network failed and the network config should be
    3876              :         // removed later.
    3877            0 :         break;
    3878              :     }
    3879            0 :     case CommissioningStage::kRemoveWiFiNetworkConfig: {
    3880            0 :         NetworkCommissioning::Commands::RemoveNetwork::Type request;
    3881            0 :         request.networkID = params.GetWiFiCredentials().Value().ssid;
    3882            0 :         request.breadcrumb.Emplace(breadcrumb);
    3883            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
    3884            0 :         if (err != CHIP_NO_ERROR)
    3885              :         {
    3886              :             // We won't get any async callbacks here, so just complete our stage.
    3887            0 :             ChipLogError(Controller, "Failed to send RemoveNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3888            0 :             CommissioningStageComplete(err);
    3889            0 :             return;
    3890              :         }
    3891            0 :         break;
    3892              :     }
    3893            0 :     case CommissioningStage::kRemoveThreadNetworkConfig: {
    3894            0 :         ByteSpan extendedPanId;
    3895            0 :         chip::Thread::OperationalDataset operationalDataset;
    3896            0 :         if (!params.GetThreadOperationalDataset().HasValue() ||
    3897            0 :             operationalDataset.Init(params.GetThreadOperationalDataset().Value()) != CHIP_NO_ERROR ||
    3898            0 :             operationalDataset.GetExtendedPanIdAsByteSpan(extendedPanId) != CHIP_NO_ERROR)
    3899              :         {
    3900            0 :             ChipLogError(Controller, "Unable to get extended pan ID for thread operational dataset\n");
    3901            0 :             CommissioningStageComplete(CHIP_ERROR_INVALID_ARGUMENT);
    3902            0 :             return;
    3903              :         }
    3904            0 :         NetworkCommissioning::Commands::RemoveNetwork::Type request;
    3905            0 :         request.networkID = extendedPanId;
    3906            0 :         request.breadcrumb.Emplace(breadcrumb);
    3907            0 :         CHIP_ERROR err = SendCommissioningCommand(proxy, request, OnNetworkConfigResponse, OnBasicFailure, endpoint, timeout);
    3908            0 :         if (err != CHIP_NO_ERROR)
    3909              :         {
    3910              :             // We won't get any async callbacks here, so just complete our stage.
    3911            0 :             ChipLogError(Controller, "Failed to send RemoveNetwork command: %" CHIP_ERROR_FORMAT, err.Format());
    3912            0 :             CommissioningStageComplete(err);
    3913            0 :             return;
    3914              :         }
    3915            0 :         break;
    3916              :     }
    3917            0 :     case CommissioningStage::kICDSendStayActive: {
    3918            0 :         if (!(params.GetICDStayActiveDurationMsec().HasValue()))
    3919              :         {
    3920            0 :             ChipLogProgress(Controller, "Skipping kICDSendStayActive");
    3921            0 :             CommissioningStageComplete(CHIP_NO_ERROR);
    3922            0 :             return;
    3923              :         }
    3924              : 
    3925              :         // StayActive Command happens over CASE Connection
    3926            0 :         IcdManagement::Commands::StayActiveRequest::Type request;
    3927            0 :         request.stayActiveDuration = params.GetICDStayActiveDurationMsec().Value();
    3928            0 :         ChipLogError(Controller, "Send ICD StayActive with Duration %u", request.stayActiveDuration);
    3929              :         CHIP_ERROR err =
    3930            0 :             SendCommissioningCommand(proxy, request, OnICDManagementStayActiveResponse, OnBasicFailure, endpoint, timeout);
    3931            0 :         if (err != CHIP_NO_ERROR)
    3932              :         {
    3933              :             // We won't get any async callbacks here, so just complete our stage.
    3934            0 :             ChipLogError(Controller, "Failed to send IcdManagement.StayActive command: %" CHIP_ERROR_FORMAT, err.Format());
    3935            0 :             CommissioningStageComplete(err);
    3936            0 :             return;
    3937              :         }
    3938              :     }
    3939            0 :     break;
    3940            0 :     case CommissioningStage::kSendComplete: {
    3941              :         // CommissioningComplete command happens over the CASE connection.
    3942              :         GeneralCommissioning::Commands::CommissioningComplete::Type request;
    3943              :         CHIP_ERROR err =
    3944            0 :             SendCommissioningCommand(proxy, request, OnCommissioningCompleteResponse, OnBasicFailure, endpoint, timeout);
    3945            0 :         if (err != CHIP_NO_ERROR)
    3946              :         {
    3947              :             // We won't get any async callbacks here, so just complete our stage.
    3948            0 :             ChipLogError(Controller, "Failed to send CommissioningComplete command: %" CHIP_ERROR_FORMAT, err.Format());
    3949            0 :             CommissioningStageComplete(err);
    3950            0 :             return;
    3951              :         }
    3952              :     }
    3953            0 :     break;
    3954            0 :     case CommissioningStage::kCleanup:
    3955            0 :         CleanupCommissioning(proxy, proxy->GetDeviceId(), params.GetCompletionStatus());
    3956            0 :         break;
    3957            0 :     case CommissioningStage::kError:
    3958            0 :         mCommissioningStage = CommissioningStage::kSecurePairing;
    3959            0 :         break;
    3960            0 :     case CommissioningStage::kSecurePairing:
    3961            0 :         break;
    3962              :     }
    3963              : }
    3964              : 
    3965            0 : void DeviceCommissioner::ExtendFailsafeBeforeNetworkEnable(DeviceProxy * device, CommissioningParameters & params,
    3966              :                                                            CommissioningStage step)
    3967              : {
    3968            0 :     auto * commissioneeDevice = FindCommissioneeDevice(device->GetDeviceId());
    3969            0 :     if (device != commissioneeDevice)
    3970              :     {
    3971              :         // Not a commissionee device; just return.
    3972            0 :         ChipLogError(Controller, "Trying to extend fail-safe for an unknown commissionee with device id " ChipLogFormatX64,
    3973              :                      ChipLogValueX64(device->GetDeviceId()));
    3974            0 :         CommissioningStageComplete(CHIP_ERROR_INCORRECT_STATE, CommissioningDelegate::CommissioningReport());
    3975            0 :         return;
    3976              :     }
    3977              : 
    3978              :     // Try to make sure we have at least enough time for our expected
    3979              :     // commissioning bits plus the MRP retries for a Sigma1.
    3980            0 :     uint16_t failSafeTimeoutSecs = params.GetFailsafeTimerSeconds().ValueOr(kDefaultFailsafeTimeout);
    3981            0 :     auto sigma1Timeout           = CASESession::ComputeSigma1ResponseTimeout(commissioneeDevice->GetPairing().GetRemoteMRPConfig());
    3982            0 :     uint16_t sigma1TimeoutSecs   = std::chrono::duration_cast<System::Clock::Seconds16>(sigma1Timeout).count();
    3983            0 :     if (UINT16_MAX - failSafeTimeoutSecs < sigma1TimeoutSecs)
    3984              :     {
    3985            0 :         failSafeTimeoutSecs = UINT16_MAX;
    3986              :     }
    3987              :     else
    3988              :     {
    3989            0 :         failSafeTimeoutSecs = static_cast<uint16_t>(failSafeTimeoutSecs + sigma1TimeoutSecs);
    3990              :     }
    3991              : 
    3992            0 :     if (!ExtendArmFailSafeInternal(commissioneeDevice, step, failSafeTimeoutSecs, MakeOptional(kMinimumCommissioningStepTimeout),
    3993              :                                    OnArmFailSafe, OnBasicFailure, /* fireAndForget = */ false))
    3994              :     {
    3995              :         // A false return is fine; we don't want to make the fail-safe shorter here.
    3996            0 :         CommissioningStageComplete(CHIP_NO_ERROR, CommissioningDelegate::CommissioningReport());
    3997              :     }
    3998              : }
    3999              : 
    4000            0 : bool DeviceCommissioner::IsAttestationInformationMissing(const CommissioningParameters & params)
    4001              : {
    4002            0 :     if (!params.GetAttestationElements().HasValue() || !params.GetAttestationSignature().HasValue() ||
    4003            0 :         !params.GetAttestationNonce().HasValue() || !params.GetDAC().HasValue() || !params.GetPAI().HasValue() ||
    4004            0 :         !params.GetRemoteVendorId().HasValue() || !params.GetRemoteProductId().HasValue())
    4005              :     {
    4006            0 :         return true;
    4007              :     }
    4008              : 
    4009            0 :     return false;
    4010              : }
    4011              : 
    4012            0 : CHIP_ERROR DeviceController::GetCompressedFabricIdBytes(MutableByteSpan & outBytes) const
    4013              : {
    4014            0 :     const auto * fabricInfo = GetFabricInfo();
    4015            0 :     VerifyOrReturnError(fabricInfo != nullptr, CHIP_ERROR_INVALID_FABRIC_INDEX);
    4016            0 :     return fabricInfo->GetCompressedFabricIdBytes(outBytes);
    4017              : }
    4018              : 
    4019            0 : CHIP_ERROR DeviceController::GetRootPublicKey(Crypto::P256PublicKey & outRootPublicKey) const
    4020              : {
    4021            0 :     const auto * fabricTable = GetFabricTable();
    4022            0 :     VerifyOrReturnError(fabricTable != nullptr, CHIP_ERROR_INCORRECT_STATE);
    4023            0 :     return fabricTable->FetchRootPubkey(mFabricIndex, outRootPublicKey);
    4024              : }
    4025              : 
    4026              : } // namespace Controller
    4027              : } // namespace chip
        

Generated by: LCOV version 2.0-1