forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMTRDeviceController.mm
1109 lines (914 loc) · 41 KB
/
MTRDeviceController.mm
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-2022 Project CHIP Authors
*
* 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.
*/
#import <os/lock.h>
#import "MTRDeviceController.h"
#import "MTRBaseDevice_Internal.h"
#import "MTRCommissioningParameters.h"
#import "MTRDeviceControllerDelegateBridge.h"
#import "MTRDeviceControllerFactory_Internal.h"
#import "MTRDeviceControllerStartupParams.h"
#import "MTRDeviceControllerStartupParams_Internal.h"
#import "MTRDevice_Internal.h"
#import "MTRError_Internal.h"
#import "MTRKeypair.h"
#import "MTRLogging.h"
#import "MTROperationalCredentialsDelegate.h"
#import "MTRP256KeypairBridge.h"
#import "MTRPersistentStorageDelegateBridge.h"
#import "MTRSetupPayload.h"
#import "NSDataSpanConversion.h"
#import <setup_payload/ManualSetupPayloadGenerator.h>
#import <setup_payload/SetupPayload.h>
#import <zap-generated/MTRBaseClusters.h>
#import "MTRDeviceAttestationDelegateBridge.h"
#import "MTRDeviceConnectionBridge.h"
#include <platform/CHIPDeviceBuildConfig.h>
#include <controller/CHIPDeviceController.h>
#include <controller/CHIPDeviceControllerFactory.h>
#include <controller/CommissioningWindowOpener.h>
#include <credentials/FabricTable.h>
#include <credentials/GroupDataProvider.h>
#include <credentials/attestation_verifier/DacOnlyPartialAttestationVerifier.h>
#include <credentials/attestation_verifier/DefaultDeviceAttestationVerifier.h>
#include <lib/core/CHIPVendorIdentifiers.hpp>
#include <platform/PlatformManager.h>
#include <setup_payload/ManualSetupPayloadGenerator.h>
#include <system/SystemClock.h>
static NSString * const kErrorCommissionerInit = @"Init failure while initializing a commissioner";
static NSString * const kErrorIPKInit = @"Init failure while initializing IPK";
static NSString * const kErrorSigningKeypairInit = @"Init failure while creating signing keypair bridge";
static NSString * const kErrorOperationalCredentialsInit = @"Init failure while creating operational credentials delegate";
static NSString * const kErrorOperationalKeypairInit = @"Init failure while creating operational keypair bridge";
static NSString * const kErrorPairingInit = @"Init failure while creating a pairing delegate";
static NSString * const kErrorPartialDacVerifierInit = @"Init failure while creating a partial DAC verifier";
static NSString * const kErrorPairDevice = @"Failure while pairing the device";
static NSString * const kErrorUnpairDevice = @"Failure while unpairing the device";
static NSString * const kErrorStopPairing = @"Failure while trying to stop the pairing process";
static NSString * const kErrorOpenPairingWindow = @"Open Pairing Window failed";
static NSString * const kErrorGetPairedDevice = @"Failure while trying to retrieve a paired device";
static NSString * const kErrorNotRunning = @"Controller is not running. Call startup first.";
static NSString * const kInfoStackShutdown = @"Shutting down the Matter Stack";
static NSString * const kErrorSetupCodeGen = @"Generating Manual Pairing Code failed";
static NSString * const kErrorGenerateNOC = @"Generating operational certificate failed";
static NSString * const kErrorKeyAllocation = @"Generating new operational key failed";
static NSString * const kErrorCSRValidation = @"Extracting public key from CSR failed";
static NSString * const kErrorGetCommissionee = @"Failure obtaining device being commissioned";
static NSString * const kErrorGetAttestationChallenge = @"Failure getting attestation challenge";
static NSString * const kErrorSpake2pVerifierGenerationFailed = @"PASE verifier generation failed";
static NSString * const kErrorSpake2pVerifierSerializationFailed = @"PASE verifier serialization failed";
@interface MTRDeviceController ()
// queue used to serialize all work performed by the MTRDeviceController
@property (atomic, readonly) dispatch_queue_t chipWorkQueue;
@property (readonly) chip::Controller::DeviceCommissioner * cppCommissioner;
@property (readonly) chip::Credentials::PartialDACVerifier * partialDACVerifier;
@property (readonly) MTRDeviceControllerDelegateBridge * deviceControllerDelegateBridge;
@property (readonly) MTROperationalCredentialsDelegate * operationalCredentialsDelegate;
@property (readonly) MTRP256KeypairBridge signingKeypairBridge;
@property (readonly) MTRP256KeypairBridge operationalKeypairBridge;
@property (readonly) MTRDeviceAttestationDelegateBridge * deviceAttestationDelegateBridge;
@property (readonly) MTRDeviceControllerFactory * factory;
@property (readonly) NSMutableDictionary * nodeIDToDeviceMap;
@property (readonly) os_unfair_lock deviceMapLock; // protects nodeIDToDeviceMap
@end
@implementation MTRDeviceController
- (instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory queue:(dispatch_queue_t)queue
{
if (self = [super init]) {
_chipWorkQueue = queue;
_factory = factory;
_deviceMapLock = OS_UNFAIR_LOCK_INIT;
_nodeIDToDeviceMap = [NSMutableDictionary dictionary];
_deviceControllerDelegateBridge = new MTRDeviceControllerDelegateBridge();
if ([self checkForInitError:(_deviceControllerDelegateBridge != nullptr) logMsg:kErrorPairingInit]) {
return nil;
}
_partialDACVerifier = new chip::Credentials::PartialDACVerifier();
if ([self checkForInitError:(_partialDACVerifier != nullptr) logMsg:kErrorPartialDacVerifierInit]) {
return nil;
}
_operationalCredentialsDelegate = new MTROperationalCredentialsDelegate();
if ([self checkForInitError:(_operationalCredentialsDelegate != nullptr) logMsg:kErrorOperationalCredentialsInit]) {
return nil;
}
_operationalCredentialsDelegate->setChipWorkQueue(_chipWorkQueue);
}
return self;
}
- (BOOL)isRunning
{
return self.cppCommissioner != nullptr;
}
- (void)shutdown
{
if (_cppCommissioner == nullptr) {
// Already shut down.
return;
}
[self cleanupAfterStartup];
}
// Clean up from a state where startup was called.
- (void)cleanupAfterStartup
{
[_factory controllerShuttingDown:self];
}
// Part of cleanupAfterStartup that has to interact with the Matter work queue
// in a very specific way that only MTRDeviceControllerFactory knows about.
- (void)shutDownCppController
{
if (_cppCommissioner) {
auto * commissionerToShutDown = _cppCommissioner;
// Flag ourselves as not running before we start shutting down
// _cppCommissioner, so we're not in a state where we claim to be
// running but are actually partially shut down.
_cppCommissioner = nullptr;
commissionerToShutDown->Shutdown();
delete commissionerToShutDown;
if (_operationalCredentialsDelegate != nil) {
_operationalCredentialsDelegate->SetDeviceCommissioner(nullptr);
}
}
}
- (void)deinitFromFactory
{
[self cleanup];
}
// Clean up any members we might have allocated.
- (void)cleanup
{
VerifyOrDie(_cppCommissioner == nullptr);
[self clearDeviceAttestationDelegateBridge];
if (_operationalCredentialsDelegate) {
delete _operationalCredentialsDelegate;
_operationalCredentialsDelegate = nullptr;
}
if (_partialDACVerifier) {
delete _partialDACVerifier;
_partialDACVerifier = nullptr;
}
if (_deviceControllerDelegateBridge) {
delete _deviceControllerDelegateBridge;
_deviceControllerDelegateBridge = nullptr;
}
}
- (BOOL)startup:(MTRDeviceControllerStartupParamsInternal *)startupParams
{
__block BOOL commissionerInitialized = NO;
if ([self isRunning]) {
MTR_LOG_ERROR("Unexpected duplicate call to startup");
return NO;
}
dispatch_sync(_chipWorkQueue, ^{
if ([self isRunning]) {
return;
}
if (startupParams.vendorID == nil || [startupParams.vendorID unsignedShortValue] == chip::VendorId::Common) {
// Shouldn't be using the "standard" vendor ID for actual devices.
MTR_LOG_ERROR("%@ is not a valid vendorID to initialize a device controller with", startupParams.vendorID);
return;
}
if (startupParams.operationalCertificate == nil && startupParams.nodeID == nil) {
MTR_LOG_ERROR("Can't start a controller if we don't know what node id it is");
return;
}
if ([startupParams keypairsMatchCertificates] == NO) {
MTR_LOG_ERROR("Provided keypairs do not match certificates");
return;
}
if (startupParams.operationalCertificate != nil && startupParams.operationalKeypair == nil
&& (!startupParams.fabricIndex.HasValue()
|| !startupParams.keystore->HasOpKeypairForFabric(startupParams.fabricIndex.Value()))) {
MTR_LOG_ERROR("Have no operational keypair for our operational certificate");
return;
}
CHIP_ERROR errorCode = CHIP_ERROR_INCORRECT_STATE;
// create a MTRP256KeypairBridge here and pass it to the operationalCredentialsDelegate
chip::Crypto::P256Keypair * signingKeypair = nullptr;
if (startupParams.nocSigner) {
errorCode = _signingKeypairBridge.Init(startupParams.nocSigner);
if ([self checkForStartError:errorCode logMsg:kErrorSigningKeypairInit]) {
return;
}
signingKeypair = &_signingKeypairBridge;
}
errorCode = _operationalCredentialsDelegate->Init(_factory.storageDelegateBridge, signingKeypair, startupParams.ipk,
startupParams.rootCertificate, startupParams.intermediateCertificate);
if ([self checkForStartError:errorCode logMsg:kErrorOperationalCredentialsInit]) {
return;
}
_cppCommissioner = new chip::Controller::DeviceCommissioner();
if (_cppCommissioner == nullptr) {
[self checkForStartError:CHIP_ERROR_NO_MEMORY logMsg:kErrorCommissionerInit];
return;
}
// nocBuffer might not be used, but if it is it needs to live
// long enough (until after we are done using
// commissionerParams).
uint8_t nocBuffer[chip::Controller::kMaxCHIPDERCertLength];
chip::Controller::SetupParams commissionerParams;
commissionerParams.pairingDelegate = _deviceControllerDelegateBridge;
_operationalCredentialsDelegate->SetDeviceCommissioner(_cppCommissioner);
commissionerParams.operationalCredentialsDelegate = _operationalCredentialsDelegate;
commissionerParams.controllerRCAC = _operationalCredentialsDelegate->RootCertSpan();
commissionerParams.controllerICAC = _operationalCredentialsDelegate->IntermediateCertSpan();
if (startupParams.operationalKeypair != nil) {
errorCode = _operationalKeypairBridge.Init(startupParams.operationalKeypair);
if ([self checkForStartError:errorCode logMsg:kErrorOperationalKeypairInit]) {
return;
}
commissionerParams.operationalKeypair = &_operationalKeypairBridge;
commissionerParams.hasExternallyOwnedOperationalKeypair = true;
}
if (startupParams.operationalCertificate) {
commissionerParams.controllerNOC = AsByteSpan(startupParams.operationalCertificate);
} else {
chip::MutableByteSpan noc(nocBuffer);
if (commissionerParams.operationalKeypair != nullptr) {
errorCode = _operationalCredentialsDelegate->GenerateNOC(startupParams.nodeID.unsignedLongLongValue,
startupParams.fabricID.unsignedLongLongValue, chip::kUndefinedCATs,
commissionerParams.operationalKeypair->Pubkey(), noc);
if ([self checkForStartError:errorCode logMsg:kErrorGenerateNOC]) {
return;
}
} else {
// Generate a new random keypair.
uint8_t csrBuffer[chip::Crypto::kMAX_CSR_Length];
chip::MutableByteSpan csr(csrBuffer);
errorCode = startupParams.fabricTable->AllocatePendingOperationalKey(startupParams.fabricIndex, csr);
if ([self checkForStartError:errorCode logMsg:kErrorKeyAllocation]) {
return;
}
chip::Crypto::P256PublicKey pubKey;
errorCode = VerifyCertificateSigningRequest(csr.data(), csr.size(), pubKey);
if ([self checkForStartError:errorCode logMsg:kErrorCSRValidation]) {
return;
}
errorCode = _operationalCredentialsDelegate->GenerateNOC(startupParams.nodeID.unsignedLongLongValue,
startupParams.fabricID.unsignedLongLongValue, chip::kUndefinedCATs, pubKey, noc);
if ([self checkForStartError:errorCode logMsg:kErrorGenerateNOC]) {
return;
}
}
commissionerParams.controllerNOC = noc;
}
commissionerParams.controllerVendorId = static_cast<chip::VendorId>([startupParams.vendorID unsignedShortValue]);
commissionerParams.deviceAttestationVerifier = _factory.deviceAttestationVerifier;
auto & factory = chip::Controller::DeviceControllerFactory::GetInstance();
errorCode = factory.SetupCommissioner(commissionerParams, *_cppCommissioner);
if ([self checkForStartError:errorCode logMsg:kErrorCommissionerInit]) {
return;
}
chip::FabricIndex fabricIdx = _cppCommissioner->GetFabricIndex();
uint8_t compressedIdBuffer[sizeof(uint64_t)];
chip::MutableByteSpan compressedId(compressedIdBuffer);
errorCode = _cppCommissioner->GetCompressedFabricIdBytes(compressedId);
if ([self checkForStartError:errorCode logMsg:kErrorIPKInit]) {
return;
}
errorCode = chip::Credentials::SetSingleIpkEpochKey(
_factory.groupData, fabricIdx, _operationalCredentialsDelegate->GetIPK(), compressedId);
if ([self checkForStartError:errorCode logMsg:kErrorIPKInit]) {
return;
}
commissionerInitialized = YES;
});
if (commissionerInitialized == NO) {
[self cleanupAfterStartup];
}
return commissionerInitialized;
}
- (NSNumber *)controllerNodeID
{
if (![self isRunning]) {
MTR_LOG_ERROR("A controller has no node id if it has not been started");
return nil;
}
__block NSNumber * nodeID;
dispatch_sync(_chipWorkQueue, ^{
if (![self isRunning]) {
MTR_LOG_ERROR("A controller has no node id if it has not been started");
nodeID = nil;
} else {
nodeID = @(_cppCommissioner->GetNodeId());
}
});
return nodeID;
}
- (BOOL)setupCommissioningSessionWithPayload:(MTRSetupPayload *)payload
newNodeID:(NSNumber *)newNodeID
error:(NSError * __autoreleasing *)error
{
VerifyOrReturnValue([self checkIsRunning:error], NO);
__block BOOL success = NO;
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning:error]);
// Try to get a QR code if possible (because it has a better
// discriminator, etc), then fall back to manual code if that fails.
NSString * pairingCode = [payload qrCodeString:nil];
if (pairingCode == nil) {
pairingCode = [payload manualEntryCode];
}
if (pairingCode == nil) {
success = ![MTRDeviceController checkForError:CHIP_ERROR_INVALID_ARGUMENT logMsg:kErrorSetupCodeGen error:error];
return;
}
chip::NodeId nodeId = [newNodeID unsignedLongLongValue];
_operationalCredentialsDelegate->SetDeviceID(nodeId);
CHIP_ERROR errorCode = self.cppCommissioner->EstablishPASEConnection(nodeId, [pairingCode UTF8String]);
success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error];
});
return success;
}
- (BOOL)commissionNodeWithID:(NSNumber *)nodeID
commissioningParams:(MTRCommissioningParameters *)commissioningParams
error:(NSError * __autoreleasing *)error
{
VerifyOrReturnValue([self checkIsRunning:error], NO);
__block BOOL success = NO;
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning:error]);
chip::Controller::CommissioningParameters params;
if (commissioningParams.csrNonce) {
params.SetCSRNonce(AsByteSpan(commissioningParams.csrNonce));
}
if (commissioningParams.attestationNonce) {
params.SetAttestationNonce(AsByteSpan(commissioningParams.attestationNonce));
}
if (commissioningParams.threadOperationalDataset) {
params.SetThreadOperationalDataset(AsByteSpan(commissioningParams.threadOperationalDataset));
}
if (commissioningParams.wifiSSID) {
chip::ByteSpan ssid = AsByteSpan(commissioningParams.wifiSSID);
chip::ByteSpan credentials;
if (commissioningParams.wifiCredentials != nil) {
credentials = AsByteSpan(commissioningParams.wifiCredentials);
}
chip::Controller::WiFiCredentials wifiCreds(ssid, credentials);
params.SetWiFiCredentials(wifiCreds);
}
if (commissioningParams.deviceAttestationDelegate) {
[self clearDeviceAttestationDelegateBridge];
chip::Optional<uint16_t> timeoutSecs;
if (commissioningParams.failSafeExpiryTimeout) {
timeoutSecs
= chip::MakeOptional(static_cast<uint16_t>([commissioningParams.failSafeExpiryTimeout unsignedIntValue]));
}
BOOL shouldWaitAfterDeviceAttestation = NO;
if ([commissioningParams.deviceAttestationDelegate
respondsToSelector:@selector(deviceAttestation:completedForDevice:attestationDeviceInfo:error:)]) {
shouldWaitAfterDeviceAttestation = YES;
}
_deviceAttestationDelegateBridge = new MTRDeviceAttestationDelegateBridge(
self, commissioningParams.deviceAttestationDelegate, _chipWorkQueue, timeoutSecs, shouldWaitAfterDeviceAttestation);
params.SetDeviceAttestationDelegate(_deviceAttestationDelegateBridge);
}
chip::NodeId deviceId = [nodeID unsignedLongLongValue];
_operationalCredentialsDelegate->SetDeviceID(deviceId);
auto errorCode = self.cppCommissioner->Commission(deviceId, params);
success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error];
});
return success;
}
- (BOOL)continueCommissioningDevice:(void *)device
ignoreAttestationFailure:(BOOL)ignoreAttestationFailure
error:(NSError * __autoreleasing *)error
{
VerifyOrReturnValue([self checkIsRunning:error], NO);
__block BOOL success = NO;
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning:error]);
auto lastAttestationResult = _deviceAttestationDelegateBridge
? _deviceAttestationDelegateBridge->attestationVerificationResult()
: chip::Credentials::AttestationVerificationResult::kSuccess;
auto deviceProxy = static_cast<chip::DeviceProxy *>(device);
auto errorCode = self.cppCommissioner->ContinueCommissioningAfterDeviceAttestation(deviceProxy,
ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult);
success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error];
});
return success;
}
- (BOOL)cancelCommissioningForNodeID:(NSNumber *)nodeID error:(NSError * __autoreleasing *)error
{
VerifyOrReturnValue([self checkIsRunning:error], NO);
__block BOOL success = NO;
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning:error]);
_operationalCredentialsDelegate->ResetDeviceID();
auto errorCode = self.cppCommissioner->StopPairing([nodeID unsignedLongLongValue]);
success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorStopPairing error:error];
});
return success;
}
- (MTRBaseDevice *)deviceBeingCommissionedWithNodeID:(NSNumber *)nodeID error:(NSError * __autoreleasing *)error
{
VerifyOrReturnValue([self checkIsRunning:error], nil);
__block MTRBaseDevice * device;
__block BOOL success = NO;
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning:error]);
chip::CommissioneeDeviceProxy * deviceProxy;
auto errorCode = self->_cppCommissioner->GetDeviceBeingCommissioned(nodeID.unsignedLongLongValue, &deviceProxy);
success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorStopPairing error:error];
device = [[MTRBaseDevice alloc] initWithPASEDevice:deviceProxy controller:self];
});
VerifyOrReturnValue(success, nil);
return device;
}
- (MTRBaseDevice *)baseDeviceForNodeID:(NSNumber *)nodeID
{
return [[MTRBaseDevice alloc] initWithNodeID:nodeID controller:self];
}
- (MTRDevice *)deviceForNodeID:(NSNumber *)nodeID
{
os_unfair_lock_lock(&_deviceMapLock);
MTRDevice * deviceToReturn = self.nodeIDToDeviceMap[nodeID];
if (!deviceToReturn) {
deviceToReturn = [[MTRDevice alloc] initWithNodeID:nodeID controller:self];
self.nodeIDToDeviceMap[nodeID] = deviceToReturn;
}
os_unfair_lock_unlock(&_deviceMapLock);
return deviceToReturn;
}
- (void)removeDevice:(MTRDevice *)device
{
os_unfair_lock_lock(&_deviceMapLock);
MTRDevice * deviceToRemove = self.nodeIDToDeviceMap[device.nodeID];
if (deviceToRemove == device) {
self.nodeIDToDeviceMap[device.nodeID] = nil;
} else {
MTR_LOG_ERROR("Error: Cannot remove device %p with nodeID %llu", device, device.nodeID.unsignedLongLongValue);
}
os_unfair_lock_unlock(&_deviceMapLock);
}
- (void)setDeviceControllerDelegate:(id<MTRDeviceControllerDelegate>)delegate queue:(dispatch_queue_t)queue
{
VerifyOrReturn([self checkIsRunning]);
dispatch_async(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning]);
self->_deviceControllerDelegateBridge->setDelegate(delegate, queue);
});
}
- (void)setNocChainIssuer:(id<MTRNOCChainIssuer>)nocChainIssuer queue:(dispatch_queue_t)queue
{
VerifyOrReturn([self checkIsRunning]);
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning]);
if (nocChainIssuer != nil) {
self->_operationalCredentialsDelegate->SetNocChainIssuer(nocChainIssuer, queue);
self->_cppCommissioner->SetDeviceAttestationVerifier(_partialDACVerifier);
} else {
self->_cppCommissioner->SetDeviceAttestationVerifier(chip::Credentials::GetDeviceAttestationVerifier());
}
});
}
+ (nullable NSData *)computePASEVerifierForSetupPasscode:(NSNumber *)setupPasscode
iterations:(NSNumber *)iterations
salt:(NSData *)salt
error:(NSError * __autoreleasing *)error
{
chip::Spake2pVerifier verifier;
CHIP_ERROR err = verifier.Generate(iterations.unsignedIntValue, AsByteSpan(salt), setupPasscode.unsignedIntValue);
if ([MTRDeviceController checkForError:err logMsg:kErrorSpake2pVerifierGenerationFailed error:error]) {
return nil;
}
uint8_t serializedBuffer[chip::Crypto::kSpake2p_VerifierSerialized_Length];
chip::MutableByteSpan serializedBytes(serializedBuffer);
err = verifier.Serialize(serializedBytes);
if ([MTRDeviceController checkForError:err logMsg:kErrorSpake2pVerifierSerializationFailed error:error]) {
return nil;
}
return AsData(serializedBytes);
}
- (NSData * _Nullable)attestationChallengeForDeviceID:(NSNumber *)deviceID
{
VerifyOrReturnValue([self checkIsRunning], nil);
__block NSData * attestationChallenge;
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning]);
chip::CommissioneeDeviceProxy * deviceProxy;
auto errorCode = self.cppCommissioner->GetDeviceBeingCommissioned([deviceID unsignedLongLongValue], &deviceProxy);
auto success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorGetCommissionee error:nil];
VerifyOrReturn(success);
uint8_t challengeBuffer[chip::Crypto::kAES_CCM128_Key_Length];
chip::ByteSpan challenge(challengeBuffer);
errorCode = deviceProxy->GetAttestationChallenge(challenge);
success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorGetAttestationChallenge error:nil];
VerifyOrReturn(success);
attestationChallenge = AsData(challenge);
});
return attestationChallenge;
}
- (BOOL)checkForInitError:(BOOL)condition logMsg:(NSString *)logMsg
{
if (condition) {
return NO;
}
MTR_LOG_ERROR("Error: %@", logMsg);
[self cleanup];
return YES;
}
- (void)clearDeviceAttestationDelegateBridge
{
if (_deviceAttestationDelegateBridge) {
delete _deviceAttestationDelegateBridge;
_deviceAttestationDelegateBridge = nullptr;
}
}
- (BOOL)checkForStartError:(CHIP_ERROR)errorCode logMsg:(NSString *)logMsg
{
if (CHIP_NO_ERROR == errorCode) {
return NO;
}
MTR_LOG_ERROR("Error(%" CHIP_ERROR_FORMAT "): %@", errorCode.Format(), logMsg);
return YES;
}
+ (BOOL)checkForError:(CHIP_ERROR)errorCode logMsg:(NSString *)logMsg error:(NSError * __autoreleasing *)error
{
if (CHIP_NO_ERROR == errorCode) {
return NO;
}
MTR_LOG_ERROR("Error(%" CHIP_ERROR_FORMAT "): %s", errorCode.Format(), [logMsg UTF8String]);
if (error) {
*error = [MTRError errorForCHIPErrorCode:errorCode];
}
return YES;
}
- (BOOL)checkIsRunning
{
return [self checkIsRunning:nil];
}
- (BOOL)checkIsRunning:(NSError * __autoreleasing *)error
{
if ([self isRunning]) {
return YES;
}
MTR_LOG_ERROR("Error: %s", [kErrorNotRunning UTF8String]);
if (error) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE];
}
return NO;
}
- (BOOL)_deviceBeingCommissionedOverBLE:(uint64_t)deviceID
{
VerifyOrReturnValue([self checkIsRunning], NO);
chip::CommissioneeDeviceProxy * deviceProxy;
auto errorCode = self->_cppCommissioner->GetDeviceBeingCommissioned(deviceID, &deviceProxy);
VerifyOrReturnValue(errorCode == CHIP_NO_ERROR, NO);
return deviceProxy->GetDeviceTransportType() == chip::Transport::Type::kBle;
}
- (BOOL)getSessionForNode:(chip::NodeId)nodeID completion:(MTRInternalDeviceConnectionCallback)completion
{
if (![self checkIsRunning]) {
return NO;
}
dispatch_async(_chipWorkQueue, ^{
NSError * error;
if (![self checkIsRunning:&error]) {
completion(nullptr, chip::NullOptional, error);
return;
}
auto connectionBridge = new MTRDeviceConnectionBridge(completion);
// MTRDeviceConnectionBridge always delivers errors async via
// completion.
connectionBridge->connect(self->_cppCommissioner, nodeID);
});
return YES;
}
- (BOOL)getSessionForCommissioneeDevice:(chip::NodeId)deviceID completion:(MTRInternalDeviceConnectionCallback)completion
{
if (![self checkIsRunning]) {
return NO;
}
dispatch_async(_chipWorkQueue, ^{
NSError * error;
if (![self checkIsRunning:&error]) {
completion(nullptr, chip::NullOptional, error);
return;
}
chip::CommissioneeDeviceProxy * deviceProxy;
CHIP_ERROR err = self->_cppCommissioner->GetDeviceBeingCommissioned(deviceID, &deviceProxy);
if (err != CHIP_NO_ERROR) {
completion(nullptr, chip::NullOptional, [MTRError errorForCHIPErrorCode:err]);
return;
}
chip::Optional<chip::SessionHandle> session = deviceProxy->GetSecureSession();
if (!session.HasValue() || !session.Value()->AsSecureSession()->IsPASESession()) {
completion(nullptr, chip::NullOptional, [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE]);
return;
}
completion(deviceProxy->GetExchangeManager(), session, nil);
});
return YES;
}
- (void)asyncDispatchToMatterQueue:(void (^)(chip::Controller::DeviceCommissioner *))block
errorHandler:(void (^)(NSError *))errorHandler
{
{
NSError * error;
if (![self checkIsRunning:&error]) {
errorHandler(error);
return;
}
}
dispatch_async(_chipWorkQueue, ^{
NSError * error;
if (![self checkIsRunning:&error]) {
errorHandler(error);
return;
}
block(self.cppCommissioner);
});
}
@end
@implementation MTRDeviceController (InternalMethods)
- (chip::FabricIndex)fabricIndex
{
if (!_cppCommissioner) {
return chip::kUndefinedFabricIndex;
}
return _cppCommissioner->GetFabricIndex();
}
- (CHIP_ERROR)isRunningOnFabric:(chip::FabricTable *)fabricTable
fabricIndex:(chip::FabricIndex)fabricIndex
isRunning:(BOOL *)isRunning
{
if (![self isRunning]) {
*isRunning = NO;
return CHIP_NO_ERROR;
}
const chip::FabricInfo * otherFabric = fabricTable->FindFabricWithIndex(fabricIndex);
if (!otherFabric) {
// Should not happen...
return CHIP_ERROR_INCORRECT_STATE;
}
if (_cppCommissioner->GetFabricId() != otherFabric->GetFabricId()) {
*isRunning = NO;
return CHIP_NO_ERROR;
}
chip::Crypto::P256PublicKey ourRootPublicKey, otherRootPublicKey;
ReturnErrorOnFailure(_cppCommissioner->GetRootPublicKey(ourRootPublicKey));
ReturnErrorOnFailure(fabricTable->FetchRootPubkey(otherFabric->GetFabricIndex(), otherRootPublicKey));
*isRunning = (ourRootPublicKey.Matches(otherRootPublicKey));
return CHIP_NO_ERROR;
}
- (void)invalidateCASESessionForNode:(chip::NodeId)nodeID;
{
if (![self checkIsRunning]) {
return;
}
dispatch_sync(_chipWorkQueue, ^{
if (![self checkIsRunning]) {
return;
}
auto sessionMgr = self->_cppCommissioner->SessionMgr();
VerifyOrDie(sessionMgr != nullptr);
sessionMgr->MarkSessionsAsDefunct(
self->_cppCommissioner->GetPeerScopedId(nodeID), chip::MakeOptional(chip::Transport::SecureSession::Type::kCASE));
});
}
@end
/**
* Shim to allow us to treat an MTRDevicePairingDelegate as an
* MTRDeviceControllerDelegate.
*/
@interface MTRDevicePairingDelegateShim : NSObject <MTRDeviceControllerDelegate>
@property (nonatomic, readonly) id<MTRDevicePairingDelegate> delegate;
- (instancetype)initWithDelegate:(id<MTRDevicePairingDelegate>)delegate;
@end
@implementation MTRDevicePairingDelegateShim
- (instancetype)initWithDelegate:(id<MTRDevicePairingDelegate>)delegate
{
if (self = [super init]) {
_delegate = delegate;
}
return self;
}
- (BOOL)respondsToSelector:(SEL)selector
{
// This logic will need to change a bit when the MTRDeviceControllerDelegate
// signatures change. It's shaped the way it is to make those changes
// easier.
if (selector == @selector(onStatusUpdate:)) {
return [self.delegate respondsToSelector:@selector(onStatusUpdate:)];
}
if (selector == @selector(onCommissioningSessionEstablishmentDone:)) {
return [self.delegate respondsToSelector:@selector(onPairingComplete:)];
}
if (selector == @selector(onCommissioningComplete:)) {
return [self.delegate respondsToSelector:@selector(onCommissioningComplete:)];
}
return [super respondsToSelector:selector];
}
- (void)onStatusUpdate:(MTRCommissioningStatus)status
{
[self.delegate onStatusUpdate:static_cast<MTRPairingStatus>(status)];
}
- (void)onCommissioningSessionEstablishmentDone:(NSError * _Nullable)error
{
[self.delegate onPairingComplete:error];
}
- (void)onCommissioningComplete:(NSError * _Nullable)error
{
[self.delegate onCommissioningComplete:error];
}
- (void)onPairingDeleted:(NSError * _Nullable)error
{
[self.delegate onPairingDeleted:error];
}
@end
@implementation MTRDeviceController (Deprecated)
- (NSNumber *)controllerNodeId
{
return self.controllerNodeID;
}
- (nullable NSData *)fetchAttestationChallengeForDeviceId:(uint64_t)deviceId
{
return [self attestationChallengeForDeviceID:@(deviceId)];
}
- (BOOL)getBaseDevice:(uint64_t)deviceID queue:(dispatch_queue_t)queue completionHandler:(MTRDeviceConnectionCallback)completion
{
NSError * error;
if (![self checkIsRunning:&error]) {
dispatch_async(queue, ^{
completion(nil, error);
});
return NO;
}
// We know getSessionForNode will return YES here, since we already checked
// that we are running.
return [self getSessionForNode:deviceID
completion:^(chip::Messaging::ExchangeManager * _Nullable exchangeManager,
const chip::Optional<chip::SessionHandle> & session, NSError * _Nullable error) {
// Create an MTRBaseDevice for the node id involved, now that our
// CASE session is primed. We don't actually care about the session
// information here.
dispatch_async(queue, ^{
MTRBaseDevice * device;
if (error == nil) {
device = [[MTRBaseDevice alloc] initWithNodeID:@(deviceID) controller:self];
} else {
device = nil;
}
completion(device, error);
});
}];
}
- (BOOL)pairDevice:(uint64_t)deviceID
discriminator:(uint16_t)discriminator
setupPINCode:(uint32_t)setupPINCode
error:(NSError * __autoreleasing *)error
{
VerifyOrReturnValue([self checkIsRunning:error], NO);
__block BOOL success = NO;
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning:error]);
std::string manualPairingCode;
chip::SetupPayload payload;
payload.discriminator.SetLongValue(discriminator);
payload.setUpPINCode = setupPINCode;
auto errorCode = chip::ManualSetupPayloadGenerator(payload).payloadDecimalStringRepresentation(manualPairingCode);
success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorSetupCodeGen error:error];
VerifyOrReturn(success);
_operationalCredentialsDelegate->SetDeviceID(deviceID);
errorCode = self.cppCommissioner->EstablishPASEConnection(deviceID, manualPairingCode.c_str());
success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error];
});
return success;
}
- (BOOL)pairDevice:(uint64_t)deviceID
address:(NSString *)address
port:(uint16_t)port
setupPINCode:(uint32_t)setupPINCode
error:(NSError * __autoreleasing *)error
{
VerifyOrReturnValue([self checkIsRunning:error], NO);
__block BOOL success = NO;
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning:error]);
chip::Inet::IPAddress addr;
chip::Inet::IPAddress::FromString([address UTF8String], addr);
chip::Transport::PeerAddress peerAddress = chip::Transport::PeerAddress::UDP(addr, port);
_operationalCredentialsDelegate->SetDeviceID(deviceID);
auto params = chip::RendezvousParameters().SetSetupPINCode(setupPINCode).SetPeerAddress(peerAddress);
auto errorCode = self.cppCommissioner->EstablishPASEConnection(deviceID, params);
success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error];
});
return success;
}
- (BOOL)pairDevice:(uint64_t)deviceID onboardingPayload:(NSString *)onboardingPayload error:(NSError * __autoreleasing *)error
{
VerifyOrReturnValue([self checkIsRunning:error], NO);
__block BOOL success = NO;
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn([self checkIsRunning:error]);
_operationalCredentialsDelegate->SetDeviceID(deviceID);
auto errorCode = self.cppCommissioner->EstablishPASEConnection(deviceID, [onboardingPayload UTF8String]);
success = ![MTRDeviceController checkForError:errorCode logMsg:kErrorPairDevice error:error];
});
return success;
}
- (BOOL)commissionDevice:(uint64_t)deviceID
commissioningParams:(MTRCommissioningParameters *)commissioningParams
error:(NSError * __autoreleasing *)error
{