forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPairingCommand.cpp
More file actions
1429 lines (1250 loc) · 57.8 KB
/
Copy pathPairingCommand.cpp
File metadata and controls
1429 lines (1250 loc) · 57.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2020-2024 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "PairingCommand.h"
#include <commands/common/DeviceScanner.h>
#include <controller/ExampleOperationalCredentialsIssuer.h>
#include <crypto/CHIPCryptoPAL.h>
#include <inet/IPAddress.h>
#include <inet/InetInterface.h>
#include <lib/core/CHIPEncoding.h>
#include <lib/core/CHIPError.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/dnssd/Types.h>
#include <lib/support/BytesToHex.h>
#include <lib/support/CHIPMemString.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/Span.h>
#include <lib/support/ThreadDiscoveryCode.h>
#include <lib/support/ThreadOperationalDataset.h>
#include <lib/support/logging/CHIPLogging.h>
#include <protocols/secure_channel/PASESession.h>
#include <setup_payload/ManualSetupPayloadParser.h>
#include <setup_payload/QRCodeSetupPayloadParser.h>
#include "../dcl/DCLClient.h"
#include "../dcl/DisplayTermsAndConditions.h"
#include <algorithm>
#include <app/CommandSender.h>
#include <app/InteractionModelEngine.h>
#include <app/data-model/Encode.h>
#include <clusters/CommissioningProxy/Commands.h>
#include <inttypes.h>
#include <iostream>
#include <memory>
#include <netdb.h>
#include <netinet/in.h>
#include <string>
#include <sys/socket.h>
using namespace ::chip;
using namespace ::chip::Controller;
namespace {
// Endpoint used for the CommissioningProxy cluster when --proxy-endpoint is not given.
constexpr chip::EndpointId kDefaultProxyEndpointId = 1;
// Endpoint used for the Network Identity Management cluster when --pdc-netim-endpoint-id is not given.
constexpr chip::EndpointId kDefaultNETIMEndpointId = 1;
bool IsNoPasswordMarker(chip::ByteSpan password)
{
// Use a one-character marker value (which is invalid in every supported Wi-Fi password encoding)
// to signal that no password is to be used. An empty string, which would otherwise be the more
// obvious choice, is used by the Network Commissioning Cluster to represent an open network.
return password.data_equal(ByteSpan::fromCharSpan("-"_span));
}
// Upper bound on back-to-back null-Message polls that yield a message but no reply.
// A conformant proxy drains in a handful; the bound only stops a misbehaving one from
// spinning the commissioner.
constexpr uint8_t kMaxConsecutiveProxyPolls = 8;
[[maybe_unused]] CHIP_ERROR ParseSetupPayload(SetupPayload & setupPayload, const char * onboardingPayload)
{
bool isQRCode = strncmp(onboardingPayload, kQRCodePrefix, strlen(kQRCodePrefix)) == 0;
if (isQRCode)
{
ReturnErrorOnFailure(QRCodeSetupPayloadParser(onboardingPayload).populatePayload(setupPayload));
VerifyOrReturnError(setupPayload.isValidQRCodePayload(), CHIP_ERROR_INVALID_ARGUMENT);
}
else
{
ReturnErrorOnFailure(ManualSetupPayloadParser(onboardingPayload).populatePayload(setupPayload));
VerifyOrReturnError(setupPayload.isValidManualCode(), CHIP_ERROR_INVALID_ARGUMENT);
}
return CHIP_NO_ERROR;
}
class DeviceDiscoveryDelegateRegistry
{
public:
DeviceDiscoveryDelegateRegistry() = delete;
DeviceDiscoveryDelegateRegistry(DeviceController & controller, DeviceDiscoveryDelegate * delegate) : mController(controller)
{
mController.RegisterDeviceDiscoveryDelegate(delegate);
}
~DeviceDiscoveryDelegateRegistry() { mController.RegisterDeviceDiscoveryDelegate(nullptr); }
private:
DeviceController & mController;
};
} // namespace
CHIP_ERROR PairingCommand::RunCommand()
{
CurrentCommissioner().RegisterPairingDelegate(this);
// Clear the CATs in OperationalCredentialsIssuer
mCredIssuerCmds->SetCredentialIssuerCATValues(kUndefinedCATs);
mDeviceIsICD = false;
if (mPDCRegistrarNodeId.HasValue())
{
mPDCRegistrar.emplace(CurrentCommissioner(), mPDCRegistrarNodeId.Value(),
mPDCRegistrarEndpointId.ValueOr(kDefaultNETIMEndpointId));
}
else if (IsNoPasswordMarker(mPassword))
{
ChipLogError(chipTool, "Either a password (or '') or --pdc-netim-node-id is required");
return CHIP_ERROR_INVALID_ARGUMENT;
}
if (mCASEAuthTags.HasValue() && mCASEAuthTags.Value().size() <= kMaxSubjectCATAttributeCount)
{
CATValues cats = kUndefinedCATs;
for (size_t index = 0; index < mCASEAuthTags.Value().size(); ++index)
{
cats.values[index] = mCASEAuthTags.Value()[index];
}
if (cats.AreValid())
{
mCredIssuerCmds->SetCredentialIssuerCATValues(cats);
}
}
return RunInternal(mNodeId);
}
CHIP_ERROR PairingCommand::RunInternal(NodeId remoteId)
{
CHIP_ERROR err = CHIP_NO_ERROR;
switch (mPairingMode)
{
case PairingMode::None:
err = Unpair(remoteId);
break;
case PairingMode::Code:
#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
chip::DeviceLayer::ConnectivityMgr().WiFiPafSetApFreq(
mApFreqStr.HasValue() ? static_cast<uint16_t>(std::stol(mApFreqStr.Value())) : 0);
#endif
err = PairWithCode(remoteId);
break;
case PairingMode::CodePaseOnly:
err = PaseWithCode(remoteId);
break;
case PairingMode::Ble:
err = Pair(remoteId, PeerAddress::BLE());
break;
case PairingMode::Nfc:
if (mDiscriminator.has_value())
{
err = Pair(remoteId, PeerAddress::NFC(mDiscriminator.value()));
}
else
{
// Discriminator is mandatory
err = CHIP_ERROR_MESSAGE_INCOMPLETE;
}
break;
case PairingMode::OnNetwork:
err = PairWithMdns(remoteId);
break;
case PairingMode::SoftAP:
err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort, mRemoteAddr.interfaceId));
break;
#if CHIP_DEVICE_CONFIG_ENABLE_WIFIPAF
case PairingMode::WiFiPAF:
chip::DeviceLayer::ConnectivityMgr().WiFiPafSetApFreq(
mApFreqStr.HasValue() ? static_cast<uint16_t>(std::stol(mApFreqStr.Value())) : 0);
err = Pair(remoteId, PeerAddress::WiFiPAF(remoteId));
break;
#endif
#if CHIP_SUPPORT_THREAD_MESHCOP
case PairingMode::ThreadMeshcop: {
Inet::IPAddress ipAddr;
VerifyOrReturnError(mThreadBaHost.HasValue(), CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(mThreadBaPort.HasValue(), CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(Inet::IPAddress::FromString(mThreadBaHost.Value(), ipAddr), CHIP_ERROR_INVALID_ADDRESS);
err = Pair(remoteId, PeerAddress::ThreadMeshcop(ipAddr, mThreadBaPort.Value()));
break;
}
#endif
case PairingMode::AlreadyDiscovered:
err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort, mRemoteAddr.interfaceId));
break;
case PairingMode::AlreadyDiscoveredByIndex:
err = PairWithMdnsOrBleByIndex(remoteId, mIndex);
break;
case PairingMode::AlreadyDiscoveredByIndexWithCode:
err = PairWithMdnsOrBleByIndexWithCode(remoteId, mIndex);
break;
case PairingMode::Proxy:
err = PairViaProxy(remoteId);
break;
}
return err;
}
void PairingCommand::Shutdown()
{
if (mPDCRegistrar.has_value())
{
// Release the registrar before ResetArguments() invalidates the arguments it was built from.
// Stop the pairing first, as the NetworkIdentityRegistrar contract requires: this run may have
// ended on a timeout, with commissioning still under way and the commissioner still pointing at
// the registrar. An error just means there was nothing left to stop.
RETURN_SAFELY_IGNORED CurrentCommissioner().StopPairing(mNodeId);
// Drop the idle notification before releasing the registrar: destroying it aborts whatever
// is in flight, which would otherwise release the waiter and set an exit status from here,
// re-entering StopWaiting() while the rest of the shutdown is still running.
mPDCRegistrarIdleCallback.Cancel();
// Anything still in flight is a revocation the run did not last long enough to see through;
// the destructor aborts it and the commissioner reports the identity left behind.
mPDCRegistrar.reset();
}
CHIPCommand::Shutdown();
}
void PairingCommand::FinishCommand(CHIP_ERROR aExitErr)
{
// A rollback of the Network Client Identity may still be under way; the commissioner does not
// generally wait (letting it complete in the background), but we should before quitting.
VerifyOrReturn(!DeferExitForPDCRegistrar(aExitErr));
SetCommandExitStatus(aExitErr);
}
bool PairingCommand::DeferExitForPDCRegistrar(CHIP_ERROR aExitErr)
{
VerifyOrReturnValue(mPDCRegistrar.has_value() && !mPDCRegistrar->IsIdle(), false);
ChipLogProgress(chipTool, "Waiting for the Network Client Identity revocation to complete");
mPDCRegistrarExitErr = aExitErr;
// Stop the registrar taking on anything new, so that the revocation in flight is all we wait for.
mPDCRegistrar->StopAcceptingRequests();
mPDCRegistrar->WaitForIdle(&mPDCRegistrarIdleCallback);
return true;
}
void PairingCommand::OnPDCRegistrarIdle(void * context)
{
auto * self = static_cast<PairingCommand *>(context);
self->SetCommandExitStatus(self->mPDCRegistrarExitErr);
}
WiFiCredentials PairingCommand::GetWiFiCredentials()
{
if (!mPDCRegistrar.has_value())
{
return WiFiCredentials(mSSID, mPassword);
}
if (IsNoPasswordMarker(mPassword))
{
return WiFiCredentials(mSSID, &mPDCRegistrar.value()); // PDC only
}
return WiFiCredentials(mSSID, &mPDCRegistrar.value(), mPassword); // PDC if supported
}
CommissioningParameters PairingCommand::GetCommissioningParameters()
{
auto params = CommissioningParameters();
params.SetSkipCommissioningComplete(mSkipCommissioningComplete.ValueOr(false));
if (mBypassAttestationVerifier.ValueOr(false))
{
params.SetDeviceAttestationDelegate(this);
}
switch (mNetworkType)
{
case PairingNetworkType::WiFi:
params.SetWiFiCredentials(GetWiFiCredentials());
break;
case PairingNetworkType::Thread:
params.SetThreadOperationalDataset(mOperationalDataset);
break;
case PairingNetworkType::WiFiOrThread:
params.SetWiFiCredentials(GetWiFiCredentials());
params.SetThreadOperationalDataset(mOperationalDataset);
break;
case PairingNetworkType::None:
break;
}
if (mCountryCode.HasValue())
{
params.SetCountryCode(CharSpan::fromCharString(mCountryCode.Value()));
}
// mTCAcknowledgements and mTCAcknowledgementVersion are optional, but related. When one is missing, default the value to 0, to
// increase the test tools ability to test the applications.
if (mTCAcknowledgements.HasValue() || mTCAcknowledgementVersion.HasValue())
{
TermsAndConditionsAcknowledgement termsAndConditionsAcknowledgement = {
.acceptedTermsAndConditions = mTCAcknowledgements.ValueOr(0),
.acceptedTermsAndConditionsVersion = mTCAcknowledgementVersion.ValueOr(0),
};
params.SetTermsAndConditionsAcknowledgement(termsAndConditionsAcknowledgement);
}
// mTimeZoneList is an optional argument managed by TypedComplexArgument mComplex_TimeZones.
// Since optional Complex arguments are not currently supported via the <chip::Optional> class,
// we will use mTimeZoneList.data() value to determine if the argument was provided.
if (mTimeZoneList.data())
{
params.SetTimeZone(mTimeZoneList);
}
// miDSTOffsetList is an optional argument managed by TypedComplexArgument mComplex_DSTOffsets.
// Since optional Complex arguments are not currently supported via the <chip::Optional> class,
// we will use mTimeZoneList.data() value to determine if the argument was provided.
if (mDSTOffsetList.data())
{
params.SetDSTOffsets(mDSTOffsetList);
}
if (mICDRegistration.ValueOr(false))
{
params.SetICDRegistrationStrategy(ICDRegistrationStrategy::kBeforeComplete);
if (!mICDSymmetricKey.HasValue())
{
VerifyOrDieWithMsg(Crypto::DRBG_get_bytes(mRandomGeneratedICDSymmetricKey, sizeof(mRandomGeneratedICDSymmetricKey)) ==
CHIP_NO_ERROR,
NotSpecified, "Failed to generate ICD symmetric key (DRBG failure)");
mICDSymmetricKey.SetValue(ByteSpan(mRandomGeneratedICDSymmetricKey));
}
if (!mICDCheckInNodeId.HasValue())
{
TEMPORARY_RETURN_IGNORED mICDCheckInNodeId.SetValue(CurrentCommissioner().GetNodeId());
}
if (!mICDMonitoredSubject.HasValue())
{
mICDMonitoredSubject.SetValue(mICDCheckInNodeId.Value());
}
if (!mICDClientType.HasValue())
{
mICDClientType.SetValue(app::Clusters::IcdManagement::ClientTypeEnum::kPermanent);
}
// These Optionals must have values now.
// The commissioner will verify these values.
params.SetICDSymmetricKey(mICDSymmetricKey.Value());
if (mICDStayActiveDurationMsec.HasValue())
{
params.SetICDStayActiveDurationMsec(mICDStayActiveDurationMsec.Value());
}
params.SetICDCheckInNodeId(mICDCheckInNodeId.Value());
params.SetICDMonitoredSubject(mICDMonitoredSubject.Value());
params.SetICDClientType(mICDClientType.Value());
}
return params;
}
CHIP_ERROR PairingCommand::PaseWithCode(NodeId remoteId)
{
auto discoveryType = DiscoveryType::kAll;
if (mUseOnlyOnNetworkDiscovery.ValueOr(false))
{
discoveryType = DiscoveryType::kDiscoveryNetworkOnly;
}
if (mDiscoverOnce.ValueOr(false))
{
discoveryType = DiscoveryType::kDiscoveryNetworkOnlyWithoutPASEAutoRetry;
}
return CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload, discoveryType);
}
CHIP_ERROR
PairingCommand::GetMeshcopCommissionParams(chip::Controller::SetUpCodePairer::ThreadMeshcopCommissionParameters & meshcopParams)
{
#if CHIP_SUPPORT_THREAD_MESHCOP
Inet::IPAddress ipAddr;
VerifyOrReturnError(Inet::IPAddress::FromString(mThreadBaHost.Value(), ipAddr), CHIP_ERROR_INVALID_ADDRESS);
meshcopParams.mBorderAgentAddress = PeerAddress::ThreadMeshcop(ipAddr, mThreadBaPort.Value());
Thread::OperationalDatasetView dataset;
ReturnErrorOnFailure(dataset.Init(mOperationalDataset));
ReturnErrorOnFailure(dataset.GetPSKc(meshcopParams.mPSKcBuffer));
return CHIP_NO_ERROR;
#else
return CHIP_ERROR_NOT_IMPLEMENTED;
#endif // CHIP_SUPPORT_THREAD_MESHCOP
}
CHIP_ERROR PairingCommand::PairWithCode(NodeId remoteId)
{
CommissioningParameters commissioningParams = GetCommissioningParameters();
// If no network discovery behavior and no network credentials are provided, assume that the pairing command is trying to pair
// with an on-network device.
if (!mUseOnlyOnNetworkDiscovery.HasValue())
{
auto threadCredentials = commissioningParams.GetThreadOperationalDataset();
auto wiFiCredentials = commissioningParams.GetWiFiCredentials();
mUseOnlyOnNetworkDiscovery.SetValue(!threadCredentials.HasValue() && !wiFiCredentials.HasValue());
}
auto discoveryType = DiscoveryType::kAll;
if (mUseOnlyOnNetworkDiscovery.ValueOr(false))
{
discoveryType = DiscoveryType::kDiscoveryNetworkOnly;
}
if (mDiscoverOnce.ValueOr(false))
{
discoveryType = DiscoveryType::kDiscoveryNetworkOnlyWithoutPASEAutoRetry;
}
ReturnErrorOnFailure(MaybeDisplayTermsAndConditions(commissioningParams));
return CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams, discoveryType);
}
CHIP_ERROR PairingCommand::Pair(NodeId remoteId, PeerAddress address)
{
auto params = RendezvousParameters().SetPeerAddress(address);
if (mOnboardingPayload != nullptr)
{
SetupPayload payload;
ReturnErrorOnFailure(ParseSetupPayload(payload, mOnboardingPayload));
params.SetSetupPINCode(payload.setUpPINCode);
params.SetSetupDiscriminator(payload.discriminator);
}
else
{
VerifyOrDieWithMsg(mSetupPINCode.has_value(), chipTool, "Using mSetupPINCode in a mode when we have not gotten one");
params.SetSetupPINCode(mSetupPINCode.value());
if (mDiscriminator.has_value())
{
params.SetDiscriminator(mDiscriminator.value());
}
}
if (address.GetTransportType() == Transport::Type::kThreadMeshcop && mOnboardingPayload)
{
SetUpCodePairer::ThreadMeshcopCommissionParameters meshcopParams;
DeviceDiscoveryDelegateRegistry registry(CurrentCommissioner(), this);
ReturnErrorOnFailure(GetMeshcopCommissionParams(meshcopParams));
if (mPaseOnly.ValueOr(false))
{
return CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload, DiscoveryType::kAll, NullOptional,
MakeOptional(meshcopParams));
}
auto commissioningParams = GetCommissioningParameters();
return CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams, DiscoveryType::kAll,
NullOptional, MakeOptional(meshcopParams));
}
if (mPaseOnly.ValueOr(false))
{
return CurrentCommissioner().EstablishPASEConnection(remoteId, params);
}
auto commissioningParams = GetCommissioningParameters();
return CurrentCommissioner().PairDevice(remoteId, params, commissioningParams);
}
CHIP_ERROR PairingCommand::PairWithMdnsOrBleByIndex(NodeId remoteId, uint16_t index)
{
#if CHIP_DEVICE_LAYER_TARGET_DARWIN
VerifyOrReturnError(IsInteractive(), CHIP_ERROR_INCORRECT_STATE);
VerifyOrDieWithMsg(mSetupPINCode.has_value(), chipTool, "Using mSetupPINCode in a mode when we have not gotten one");
RendezvousParameters params;
ReturnErrorOnFailure(GetDeviceScanner().Get(index, params));
params.SetSetupPINCode(mSetupPINCode.value());
CHIP_ERROR err = CHIP_NO_ERROR;
if (mPaseOnly.ValueOr(false))
{
err = CurrentCommissioner().EstablishPASEConnection(remoteId, params);
}
else
{
auto commissioningParams = GetCommissioningParameters();
err = CurrentCommissioner().PairDevice(remoteId, params, commissioningParams);
}
return err;
#else
return CHIP_ERROR_NOT_IMPLEMENTED;
#endif // CHIP_DEVICE_LAYER_TARGET_DARWIN
}
CHIP_ERROR PairingCommand::PairWithMdnsOrBleByIndexWithCode(NodeId remoteId, uint16_t index)
{
// We might or might not have a setup code. We don't know yet, but if we
// do, we'll emplace it at that point.
mSetupPINCode.reset();
#if CHIP_DEVICE_LAYER_TARGET_DARWIN
VerifyOrReturnError(IsInteractive(), CHIP_ERROR_INCORRECT_STATE);
Dnssd::CommonResolutionData resolutionData;
auto err = GetDeviceScanner().Get(index, resolutionData);
if (CHIP_ERROR_NOT_FOUND == err)
{
// There is no device with this index that has some resolution data. This could simply
// be because the device is a ble device. In this case let's fall back to looking for
// a device with this index and some RendezvousParameters.
SetupPayload payload;
ReturnErrorOnFailure(ParseSetupPayload(payload, mOnboardingPayload));
mSetupPINCode.emplace(payload.setUpPINCode);
return PairWithMdnsOrBleByIndex(remoteId, index);
}
err = CHIP_NO_ERROR;
if (mPaseOnly.ValueOr(false))
{
err = CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload, DiscoveryType::kDiscoveryNetworkOnly,
MakeOptional(resolutionData));
}
else
{
auto commissioningParams = GetCommissioningParameters();
err = CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams,
DiscoveryType::kDiscoveryNetworkOnly, MakeOptional(resolutionData));
}
return err;
#else
return CHIP_ERROR_NOT_IMPLEMENTED;
#endif // CHIP_DEVICE_LAYER_TARGET_DARWIN
}
CHIP_ERROR PairingCommand::PairWithMdns(NodeId remoteId)
{
Dnssd::DiscoveryFilter filter(mFilterType);
switch (mFilterType)
{
case Dnssd::DiscoveryFilterType::kNone:
break;
case Dnssd::DiscoveryFilterType::kShortDiscriminator:
case Dnssd::DiscoveryFilterType::kLongDiscriminator:
case Dnssd::DiscoveryFilterType::kCompressedFabricId:
case Dnssd::DiscoveryFilterType::kVendorId:
case Dnssd::DiscoveryFilterType::kDeviceType:
filter.code = mDiscoveryFilterCode;
break;
case Dnssd::DiscoveryFilterType::kCommissioningMode:
break;
case Dnssd::DiscoveryFilterType::kCommissioner:
filter.code = 1;
break;
case Dnssd::DiscoveryFilterType::kInstanceName:
filter.code = 0;
filter.instanceName = mDiscoveryFilterInstanceName;
break;
}
CurrentCommissioner().RegisterDeviceDiscoveryDelegate(this);
return CurrentCommissioner().DiscoverCommissionableNodes(filter);
}
CHIP_ERROR PairingCommand::Unpair(NodeId remoteId)
{
mCurrentFabricRemover = Platform::MakeUnique<Controller::CurrentFabricRemover>(&CurrentCommissioner());
return mCurrentFabricRemover->RemoveCurrentFabric(remoteId, &mCurrentFabricRemoveCallback);
}
void PairingCommand::OnStatusUpdate(DevicePairingDelegate::Status status)
{
switch (status)
{
case DevicePairingDelegate::Status::SecurePairingSuccess:
ChipLogProgress(chipTool, "Secure Pairing Success");
ChipLogProgress(chipTool, "CASE establishment successful");
break;
case DevicePairingDelegate::Status::SecurePairingFailed:
ChipLogError(chipTool, "Secure Pairing Failed");
SetCommandExitStatus(CHIP_ERROR_INCORRECT_STATE);
break;
}
}
void PairingCommand::OnPairingComplete(CHIP_ERROR err)
{
if (err == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Pairing Success");
ChipLogProgress(chipTool, "PASE establishment successful");
if (mPairingMode == PairingMode::CodePaseOnly || mPaseOnly.ValueOr(false))
{
SetCommandExitStatus(err);
}
}
else
{
ChipLogProgress(chipTool, "Pairing Failure: %s", ErrorStr(err));
// PASE failed — commissioning will not proceed, so clean up the proxy session now.
if (mPairingMode == PairingMode::Proxy)
{
SendProxyDisconnect(err);
return;
}
SetCommandExitStatus(err);
}
}
void PairingCommand::OnPairingDeleted(CHIP_ERROR err)
{
if (err == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Pairing Deleted Success");
}
else
{
ChipLogProgress(chipTool, "Pairing Deleted Failure: %s", ErrorStr(err));
}
SetCommandExitStatus(err);
}
void PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err)
{
if (err == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Device commissioning completed with success");
}
else
{
// When ICD device commissioning fails, the ICDClientInfo stored in OnICDRegistrationComplete needs to be removed.
if (mDeviceIsICD)
{
CHIP_ERROR deleteEntryError =
CHIPCommand::sICDClientStorage.DeleteEntry(ScopedNodeId(mNodeId, CurrentCommissioner().GetFabricIndex()));
if (deleteEntryError != CHIP_NO_ERROR)
{
ChipLogError(chipTool, "Failed to delete ICD entry: %s", ErrorStr(err));
}
}
ChipLogProgress(chipTool, "Device commissioning Failure: %s", ErrorStr(err));
}
if (mPairingMode == PairingMode::Proxy)
{
// Clean up the proxy session before exiting, regardless of success or failure.
// The disconnect completing is what eventually reaches FinishCommand().
SendProxyDisconnect(err);
return;
}
FinishCommand(err);
}
void PairingCommand::OnReadCommissioningInfo(const Controller::ReadCommissioningInfo & info)
{
ChipLogProgress(AppServer, "OnReadCommissioningInfo - vendorId=0x%04X productId=0x%04X", info.basic.vendorId,
info.basic.productId);
// The string in CharSpan received from the device is not null-terminated, we use std::string here for coping and
// appending a numm-terminator at the end of the string.
std::string userActiveModeTriggerInstruction;
// Note: the callback doesn't own the buffer, should make a copy if it will be used it later.
if (info.icd.userActiveModeTriggerInstruction.size() != 0)
{
userActiveModeTriggerInstruction =
std::string(info.icd.userActiveModeTriggerInstruction.data(), info.icd.userActiveModeTriggerInstruction.size());
}
if (info.icd.userActiveModeTriggerHint.HasAny())
{
ChipLogProgress(AppServer, "OnReadCommissioningInfo - LIT UserActiveModeTriggerHint=0x%08x",
info.icd.userActiveModeTriggerHint.Raw());
ChipLogProgress(AppServer, "OnReadCommissioningInfo - LIT UserActiveModeTriggerInstruction=%s",
userActiveModeTriggerInstruction.c_str());
}
ChipLogProgress(AppServer, "OnReadCommissioningInfo ICD - IdleModeDuration=%u activeModeDuration=%u activeModeThreshold=%u",
info.icd.idleModeDuration, info.icd.activeModeDuration, info.icd.activeModeThreshold);
}
void PairingCommand::OnICDRegistrationComplete(ScopedNodeId nodeId, uint32_t icdCounter)
{
char icdSymmetricKeyHex[Crypto::kAES_CCM128_Key_Length * 2 + 1];
TEMPORARY_RETURN_IGNORED Encoding::BytesToHex(mICDSymmetricKey.Value().data(), mICDSymmetricKey.Value().size(),
icdSymmetricKeyHex, sizeof(icdSymmetricKeyHex),
Encoding::HexFlags::kNullTerminate);
app::ICDClientInfo clientInfo;
clientInfo.check_in_node = ScopedNodeId(mICDCheckInNodeId.Value(), nodeId.GetFabricIndex());
clientInfo.peer_node = nodeId;
clientInfo.monitored_subject = mICDMonitoredSubject.Value();
clientInfo.start_icd_counter = icdCounter;
CHIP_ERROR err = CHIPCommand::sICDClientStorage.SetKey(clientInfo, mICDSymmetricKey.Value());
if (err == CHIP_NO_ERROR)
{
err = CHIPCommand::sICDClientStorage.StoreEntry(clientInfo);
}
if (err != CHIP_NO_ERROR)
{
TEMPORARY_RETURN_IGNORED CHIPCommand::sICDClientStorage.RemoveKey(clientInfo);
ChipLogError(chipTool, "Failed to persist symmetric key for " ChipLogFormatX64 ": %s", ChipLogValueX64(nodeId.GetNodeId()),
err.AsString());
SetCommandExitStatus(err);
return;
}
mDeviceIsICD = true;
ChipLogProgress(chipTool, "Saved ICD Symmetric key for " ChipLogFormatX64, ChipLogValueX64(nodeId.GetNodeId()));
ChipLogProgress(chipTool,
"ICD Registration Complete for device " ChipLogFormatX64 " / Check-In NodeID: " ChipLogFormatX64
" / Monitored Subject: " ChipLogFormatX64 " / Symmetric Key: %s / ICDCounter %u",
ChipLogValueX64(nodeId.GetNodeId()), ChipLogValueX64(mICDCheckInNodeId.Value()),
ChipLogValueX64(mICDMonitoredSubject.Value()), icdSymmetricKeyHex, icdCounter);
}
void PairingCommand::OnICDStayActiveComplete(ScopedNodeId deviceId, uint32_t promisedActiveDuration)
{
ChipLogProgress(chipTool, "ICD Stay Active Complete for device " ChipLogFormatX64 " / promisedActiveDuration: %u",
ChipLogValueX64(deviceId.GetNodeId()), promisedActiveDuration);
}
void PairingCommand::OnCommissioningStageStart(PeerId peerId, CommissioningStage stageStarting)
{
ChipLogDetail(chipTool, "Starting commissioning stage '%s'", StageToString(stageStarting));
}
CHIP_ERROR PairingCommand::WiFiCredentialsNeeded(EndpointId endpoint)
{
if (mNetworkType != PairingNetworkType::None)
{
// We only support prompting for credentials when no credentials were
// provided up front, for now.
return CHIP_ERROR_NOT_IMPLEMENTED;
}
// We block while prompting for the information, and that does not seem to
// work well if we do it synchronously: we seem to lose the BLE connection
// to the commissionee. So do all the rest of the work async. The
// outermost ScheduleLambda is only there to avoid the prompt interleaving
// with logging that happens on the Matter thread after this function
// returns.
TEMPORARY_RETURN_IGNORED DeviceLayer::SystemLayer().ScheduleLambda([this] {
mPrompterThread.emplace([this] {
do
{
std::cout << "Enter the Wi-Fi SSID: ";
std::getline(std::cin, mPromptedSSID);
if (OctetStringFromCharString(mPromptedSSID.data(), &mSSID))
{
break;
}
ChipLogError(chipTool, "Invalid value for SSID");
} while (true);
do
{
std::cout << "Enter the Wi-Fi password (empty for an open network): ";
std::getline(std::cin, mPromptedPassword);
if (OctetStringFromCharString(mPromptedPassword.data(), &mPassword))
{
break;
}
ChipLogError(chipTool, "Invalid value for password");
} while (true);
TEMPORARY_RETURN_IGNORED DeviceLayer::SystemLayer().ScheduleLambda([this] {
// Ensure that the background thread (and its writes to our members) is done.
mPrompterThread->join();
mPrompterThread.reset();
auto & commissioner = CurrentCommissioner();
CommissioningParameters params = commissioner.GetCommissioningParameters();
params.SetWiFiCredentials(GetWiFiCredentials());
TEMPORARY_RETURN_IGNORED commissioner.UpdateCommissioningParameters(params);
TEMPORARY_RETURN_IGNORED commissioner.NetworkCredentialsReady();
});
});
});
return CHIP_NO_ERROR;
}
CHIP_ERROR PairingCommand::ThreadCredentialsNeeded(EndpointId endpoint)
{
if (mNetworkType != PairingNetworkType::None)
{
// We only support prompting for credentials when no credentials were
// provided up front, for now.
return CHIP_ERROR_NOT_IMPLEMENTED;
}
// We block while prompting for the information, and that does not seem to
// work well if we do it synchronously: we seem to lose the BLE connection
// to the commissionee. So do all the rest of the work async. The
// outermost ScheduleLambda is only there to avoid the prompt interleaving
// with logging that happens on the Matter thread after this function
// returns.
TEMPORARY_RETURN_IGNORED DeviceLayer::SystemLayer().ScheduleLambda([this] {
mPrompterThread.emplace([this] {
do
{
std::cout << "Enter the operational dataset (probably as a hex string prefixed with \"hex:\"): ";
std::getline(std::cin, mPromptedOperationalDataset);
if (OctetStringFromCharString(mPromptedOperationalDataset.data(), &mOperationalDataset))
{
break;
}
ChipLogError(chipTool, "Invalid value for operational dataset");
} while (true);
TEMPORARY_RETURN_IGNORED DeviceLayer::SystemLayer().ScheduleLambda([this] {
// Ensure that the background thread (and its writes to our members) is done.
mPrompterThread->join();
mPrompterThread.reset();
auto & commissioner = CurrentCommissioner();
CommissioningParameters params = commissioner.GetCommissioningParameters();
params.SetThreadOperationalDataset(mOperationalDataset);
TEMPORARY_RETURN_IGNORED commissioner.UpdateCommissioningParameters(params);
TEMPORARY_RETURN_IGNORED commissioner.NetworkCredentialsReady();
});
});
});
return CHIP_NO_ERROR;
}
void PairingCommand::OnDiscoveredDevice(const Dnssd::CommissionNodeData & nodeData)
{
// Ignore nodes with closed commissioning window
VerifyOrReturn(nodeData.commissioningMode != 0);
auto & resolutionData = nodeData;
const uint16_t port = resolutionData.port;
char buf[Inet::IPAddress::kMaxStringLength];
resolutionData.ipAddress[0].ToString(buf);
ChipLogProgress(chipTool, "Discovered Device: %s:%u", buf, port);
// Stop Mdns discovery.
auto err = CurrentCommissioner().StopCommissionableDiscovery();
// Some platforms does not implement a mechanism to stop mdns browse, so
// we just ignore CHIP_ERROR_NOT_IMPLEMENTED instead of bailing out.
if (CHIP_NO_ERROR != err && CHIP_ERROR_NOT_IMPLEMENTED != err)
{
SetCommandExitStatus(err);
return;
}
CurrentCommissioner().RegisterDeviceDiscoveryDelegate(nullptr);
auto interfaceId = resolutionData.ipAddress[0].IsIPv6LinkLocal() ? resolutionData.interfaceId : Inet::InterfaceId::Null();
auto peerAddress = PeerAddress::UDP(resolutionData.ipAddress[0], port, interfaceId);
err = Pair(mNodeId, peerAddress);
if (CHIP_NO_ERROR != err)
{
SetCommandExitStatus(err);
}
}
void PairingCommand::OnCurrentFabricRemove(void * context, NodeId nodeId, CHIP_ERROR err)
{
PairingCommand * command = reinterpret_cast<PairingCommand *>(context);
VerifyOrReturn(command != nullptr, ChipLogError(chipTool, "OnCurrentFabricRemove: context is null"));
if (err == CHIP_NO_ERROR)
{
ChipLogProgress(chipTool, "Device unpair completed with success: " ChipLogFormatX64, ChipLogValueX64(nodeId));
}
else
{
ChipLogProgress(chipTool, "Device unpair Failure: " ChipLogFormatX64 " %s", ChipLogValueX64(nodeId), ErrorStr(err));
}
command->SetCommandExitStatus(err);
}
Optional<uint16_t> PairingCommand::FailSafeExpiryTimeoutSecs() const
{
// We don't need to set additional failsafe timeout as we don't ask the final user if he wants to continue
return Optional<uint16_t>();
}
void PairingCommand::OnDeviceAttestationCompleted(Controller::DeviceCommissioner * deviceCommissioner, DeviceProxy * device,
const Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info,
Credentials::AttestationVerificationResult attestationResult)
{
// Bypass attestation verification, continue with success
auto err = deviceCommissioner->ContinueCommissioningAfterDeviceAttestation(
device, Credentials::AttestationVerificationResult::kSuccess);
if (CHIP_NO_ERROR != err)
{
SetCommandExitStatus(err);
}
}
CHIP_ERROR PairingCommand::MaybeDisplayTermsAndConditions(CommissioningParameters & params)
{
VerifyOrReturnError(mUseDCL.ValueOr(false), CHIP_NO_ERROR);
Json::Value tc;
auto client = tool::dcl::DCLClient(mDCLHostName, mDCLPort);
ReturnErrorOnFailure(client.TermsAndConditions(mOnboardingPayload, tc));
if (tc != Json::nullValue)
{
uint16_t version = 0;
uint16_t userResponse = 0;
ReturnErrorOnFailure(tool::dcl::DisplayTermsAndConditions(tc, version, userResponse, mCountryCode));
TermsAndConditionsAcknowledgement termsAndConditionsAcknowledgement = {
.acceptedTermsAndConditions = userResponse,
.acceptedTermsAndConditionsVersion = version,
};
params.SetTermsAndConditionsAcknowledgement(termsAndConditionsAcknowledgement);
}
return CHIP_NO_ERROR;
}
// ==========================================================================
// Proxy commissioning support
// ==========================================================================
CHIP_ERROR PairingCommand::ParseProxyTransportArguments()
{
using namespace chip::app::Clusters::CommissioningProxy;
// Interactive mode reuses this command instance, and Command::ResetArguments() only
// clears registered arguments, not what was derived from them. Set() ORs, so without
// this a second run would send the union of both transports.
mProxyTransportBits.ClearAll();
mProxyWiFiBandBits.ClearValue();
VerifyOrReturnError(mProxyTransport != nullptr, CHIP_ERROR_INVALID_ARGUMENT,
ChipLogError(chipTool, "PairViaProxy: --proxy-transport is required (one of: ble | wifipaf)"));
if (strcmp(mProxyTransport, "wifipaf") == 0)
{
mProxyTransportBits.Set(CapabilitiesBitmap::kWiFiPAF);
if (mProxyWiFiBand.HasValue())
{
if (strcmp(mProxyWiFiBand.Value(), "2g4") == 0)
{
mProxyWiFiBandBits.SetValue(chip::BitMask<WiFiBandBitmap>(WiFiBandBitmap::k2g4));
}
else if (strcmp(mProxyWiFiBand.Value(), "5g") == 0)
{
mProxyWiFiBandBits.SetValue(chip::BitMask<WiFiBandBitmap>(WiFiBandBitmap::k5g));
}
else
{
ChipLogError(chipTool, "PairViaProxy: --proxy-wifi-band must be 2g4 or 5g (got '%s')", mProxyWiFiBand.Value());
return CHIP_ERROR_INVALID_ARGUMENT;
}
}
}
else if (strcmp(mProxyTransport, "ble") == 0)
{
mProxyTransportBits.Set(CapabilitiesBitmap::kBle);
VerifyOrReturnError(!mProxyWiFiBand.HasValue(), CHIP_ERROR_INVALID_ARGUMENT,
ChipLogError(chipTool, "PairViaProxy: --proxy-wifi-band only valid with --proxy-transport=wifipaf"));
}
else
{
ChipLogError(chipTool, "PairViaProxy: --proxy-transport must be 'ble' or 'wifipaf' (got '%s')", mProxyTransport);
return CHIP_ERROR_INVALID_ARGUMENT;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR PairingCommand::PairViaProxy(NodeId remoteId)
{
// Refuse a new flow while a previous one still has a sender outstanding. Interactive
// mode reuses this instance, and SendProxyDisconnect() only clears mProxySessionActive;