forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMTRDeviceController_Concrete.mm
2024 lines (1694 loc) · 85.9 KB
/
MTRDeviceController_Concrete.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-2024 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 <Matter/MTRDefines.h>
#import <Matter/MTRDeviceControllerParameters.h>
#import "MTRDeviceController_Internal.h"
#import "MTRAsyncWorkQueue.h"
#import "MTRAttestationTrustStoreBridge.h"
#import "MTRBaseDevice_Internal.h"
#import "MTRCommissionableBrowser.h"
#import "MTRCommissionableBrowserResult_Internal.h"
#import "MTRCommissioningParameters.h"
#import "MTRConversion.h"
#import "MTRDeviceControllerDelegateBridge.h"
#import "MTRDeviceControllerFactory_Internal.h"
#import "MTRDeviceControllerLocalTestStorage.h"
#import "MTRDeviceControllerStartupParams.h"
#import "MTRDeviceControllerStartupParams_Internal.h"
#import "MTRDeviceController_Concrete.h"
#import "MTRDevice_Concrete.h"
#import "MTRDevice_Internal.h"
#import "MTREndpointInfo_Internal.h"
#import "MTRError_Internal.h"
#import "MTRKeypair.h"
#import "MTRLogging_Internal.h"
#import "MTRMetricKeys.h"
#import "MTRMetricsCollector.h"
#import "MTROperationalCredentialsDelegate.h"
#import "MTRP256KeypairBridge.h"
#import "MTRPersistentStorageDelegateBridge.h"
#import "MTRServerEndpoint_Internal.h"
#import "MTRSetupPayload.h"
#import "MTRTimeUtils.h"
#import "MTRUnfairLock.h"
#import "MTRUtilities.h"
#import "NSDataSpanConversion.h"
#import "NSStringSpanConversion.h"
#import <setup_payload/ManualSetupPayloadGenerator.h>
#import <setup_payload/SetupPayload.h>
#import <zap-generated/MTRBaseClusters.h>
#import "MTRDeviceAttestationDelegateBridge.h"
#import "MTRDeviceConnectionBridge.h"
#include <platform/CHIPDeviceConfig.h>
#include <app-common/zap-generated/cluster-objects.h>
#include <app/data-model/List.h>
#include <app/server/Dnssd.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 <inet/InetInterface.h>
#include <lib/core/CHIPVendorIdentifiers.hpp>
#include <platform/LockTracker.h>
#include <platform/PlatformManager.h>
#include <setup_payload/ManualSetupPayloadGenerator.h>
#include <system/SystemClock.h>
#include <atomic>
#include <dns_sd.h>
#include <optional>
#include <string>
#import <os/lock.h>
typedef void (^SyncWorkQueueBlock)(void);
typedef id (^SyncWorkQueueBlockWithReturnValue)(void);
typedef BOOL (^SyncWorkQueueBlockWithBoolReturnValue)(void);
using namespace chip::Tracing::DarwinFramework;
@interface MTRDeviceController_Concrete ()
// MTRDeviceController ivar internal access
@property (nonatomic, readonly) chip::Controller::DeviceCommissioner * cppCommissioner;
@property (nonatomic, readonly) chip::Credentials::PartialDACVerifier * partialDACVerifier;
@property (nonatomic, readonly) chip::Credentials::DefaultDACVerifier * defaultDACVerifier;
@property (nonatomic, readonly) MTRDeviceControllerDelegateBridge * deviceControllerDelegateBridge;
@property (nonatomic, readonly) MTROperationalCredentialsDelegate * operationalCredentialsDelegate;
@property (nonatomic, readonly) MTRDeviceAttestationDelegateBridge * deviceAttestationDelegateBridge;
@property (nonatomic, readonly) dispatch_queue_t chipWorkQueue;
@property (nonatomic, readonly, nullable) MTRDeviceControllerFactory * factory;
@property (nonatomic, readonly, nullable) id<MTROTAProviderDelegate> otaProviderDelegate;
@property (nonatomic, readonly, nullable) dispatch_queue_t otaProviderDelegateQueue;
@property (nonatomic, readonly, nullable) MTRCommissionableBrowser * commissionableBrowser;
@property (nonatomic, readonly, nullable) MTRAttestationTrustStoreBridge * attestationTrustStoreBridge;
@property (nonatomic, readonly, nullable) NSMutableArray<MTRServerEndpoint *> * serverEndpoints;
@property (nonatomic, readonly) MTRDeviceStorageBehaviorConfiguration * storageBehaviorConfiguration;
// Whether we should be advertising our operational identity when we are not suspended.
@property (nonatomic, readonly) BOOL shouldAdvertiseOperational;
@end
@implementation MTRDeviceController_Concrete {
std::atomic<chip::FabricIndex> _storedFabricIndex;
std::atomic<std::optional<uint64_t>> _storedCompressedFabricID;
MTRP256KeypairBridge _signingKeypairBridge;
MTRP256KeypairBridge _operationalKeypairBridge;
// Counters to track assertion status and access controlled by the _assertionLock
// TODO: Figure out whether they should live here or in the base class (or
// go away completely!), which depends on how the shutdown codepaths get set up.
NSUInteger _keepRunningAssertionCounter;
BOOL _shutdownPending;
os_unfair_lock _assertionLock;
}
// TODO: Figure out whether the work queue storage lives here or in the superclass
// Right now we seem to have both?
@synthesize chipWorkQueue = _chipWorkQueue;
@synthesize controllerDataStore = _controllerDataStore;
// TODO: For these remaining ivars, figure out whether they should live here or
// on the superclass. Should not be both.
@synthesize factory = _factory;
@synthesize otaProviderDelegate = _otaProviderDelegate;
@synthesize otaProviderDelegateQueue = _otaProviderDelegateQueue;
@synthesize commissionableBrowser = _commissionableBrowser;
@synthesize concurrentSubscriptionPool = _concurrentSubscriptionPool;
@synthesize storageBehaviorConfiguration = _storageBehaviorConfiguration;
@synthesize controllerNodeID = _controllerNodeID;
- (nullable instancetype)initWithParameters:(MTRDeviceControllerAbstractParameters *)parameters
error:(NSError * __autoreleasing *)error
{
if (![parameters isKindOfClass:MTRDeviceControllerParameters.class]) {
MTR_LOG_ERROR("Expected MTRDeviceControllerParameters but got: %@", parameters);
if (error) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT];
}
return nil;
}
auto * controllerParameters = static_cast<MTRDeviceControllerParameters *>(parameters);
// Start us up normally. MTRDeviceControllerFactory will auto-start in per-controller-storage mode if necessary.
MTRDeviceControllerFactory * factory = MTRDeviceControllerFactory.sharedInstance;
auto * controller = [factory initializeController:self
withParameters:controllerParameters
error:error];
return controller;
}
- (nullable instancetype)initWithFactory:(MTRDeviceControllerFactory *)factory
queue:(dispatch_queue_t)queue
storageDelegate:(id<MTRDeviceControllerStorageDelegate> _Nullable)storageDelegate
storageDelegateQueue:(dispatch_queue_t _Nullable)storageDelegateQueue
otaProviderDelegate:(id<MTROTAProviderDelegate> _Nullable)otaProviderDelegate
otaProviderDelegateQueue:(dispatch_queue_t _Nullable)otaProviderDelegateQueue
uniqueIdentifier:(NSUUID *)uniqueIdentifier
concurrentSubscriptionPoolSize:(NSUInteger)concurrentSubscriptionPoolSize
storageBehaviorConfiguration:(MTRDeviceStorageBehaviorConfiguration *)storageBehaviorConfiguration
startSuspended:(BOOL)startSuspended
{
if (self = [super initForSubclasses:startSuspended]) {
// Make sure our storage is all set up to work as early as possible,
// before we start doing anything else with the controller.
self.uniqueIdentifier = uniqueIdentifier;
// Setup assertion variables
_keepRunningAssertionCounter = 0;
_shutdownPending = NO;
_assertionLock = OS_UNFAIR_LOCK_INIT;
if (storageDelegate != nil) {
if (storageDelegateQueue == nil) {
MTR_LOG_ERROR("storageDelegate provided without storageDelegateQueue");
return nil;
}
id<MTRDeviceControllerStorageDelegate> storageDelegateToUse = storageDelegate;
if (MTRDeviceControllerLocalTestStorage.localTestStorageEnabled) {
storageDelegateToUse = [[MTRDeviceControllerLocalTestStorage alloc] initWithPassThroughStorage:storageDelegate];
}
_controllerDataStore = [[MTRDeviceControllerDataStore alloc] initWithController:self
storageDelegate:storageDelegateToUse
storageDelegateQueue:storageDelegateQueue];
if (_controllerDataStore == nil) {
return nil;
}
} else {
if (MTRDeviceControllerLocalTestStorage.localTestStorageEnabled) {
dispatch_queue_t localTestStorageQueue = dispatch_queue_create("org.csa-iot.matter.framework.devicecontroller.localteststorage", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
MTRDeviceControllerLocalTestStorage * localTestStorage = [[MTRDeviceControllerLocalTestStorage alloc] initWithPassThroughStorage:nil];
_controllerDataStore = [[MTRDeviceControllerDataStore alloc] initWithController:self
storageDelegate:localTestStorage
storageDelegateQueue:localTestStorageQueue];
if (_controllerDataStore == nil) {
return nil;
}
}
}
// Ensure the otaProviderDelegate, if any, is valid.
if (otaProviderDelegate == nil && otaProviderDelegateQueue != nil) {
MTR_LOG_ERROR("Must have otaProviderDelegate when we have otaProviderDelegateQueue");
return nil;
}
if (otaProviderDelegate != nil && otaProviderDelegateQueue == nil) {
MTR_LOG_ERROR("Must have otaProviderDelegateQueue when we have otaProviderDelegate");
return nil;
}
if (otaProviderDelegate != nil) {
if (![otaProviderDelegate respondsToSelector:@selector(handleQueryImageForNodeID:controller:params:completion:)]
&& ![otaProviderDelegate respondsToSelector:@selector(handleQueryImageForNodeID:controller:params:completionHandler:)]) {
MTR_LOG_ERROR("Error: MTROTAProviderDelegate does not support handleQueryImageForNodeID");
return nil;
}
if (![otaProviderDelegate respondsToSelector:@selector(handleApplyUpdateRequestForNodeID:controller:params:completion:)]
&& ![otaProviderDelegate respondsToSelector:@selector(handleApplyUpdateRequestForNodeID:controller:params:completionHandler:)]) {
MTR_LOG_ERROR("Error: MTROTAProviderDelegate does not support handleApplyUpdateRequestForNodeID");
return nil;
}
if (![otaProviderDelegate respondsToSelector:@selector(handleNotifyUpdateAppliedForNodeID:controller:params:completion:)]
&& ![otaProviderDelegate
respondsToSelector:@selector(handleNotifyUpdateAppliedForNodeID:controller:params:completionHandler:)]) {
MTR_LOG_ERROR("Error: MTROTAProviderDelegate does not support handleNotifyUpdateAppliedForNodeID");
return nil;
}
if (![otaProviderDelegate respondsToSelector:@selector(handleBDXTransferSessionBeginForNodeID:controller:fileDesignator:offset:completion:)]
&& ![otaProviderDelegate respondsToSelector:@selector(handleBDXTransferSessionBeginForNodeID:controller:fileDesignator:offset:completionHandler:)]) {
MTR_LOG_ERROR("Error: MTROTAProviderDelegate does not support handleBDXTransferSessionBeginForNodeID");
return nil;
}
if (![otaProviderDelegate respondsToSelector:@selector(handleBDXQueryForNodeID:controller:blockSize:blockIndex:bytesToSkip:completion:)]
&& ![otaProviderDelegate respondsToSelector:@selector(handleBDXQueryForNodeID:controller:blockSize:blockIndex:bytesToSkip:completionHandler:)]) {
MTR_LOG_ERROR("Error: MTROTAProviderDelegate does not support handleBDXQueryForNodeID");
return nil;
}
}
_otaProviderDelegate = otaProviderDelegate;
_otaProviderDelegateQueue = otaProviderDelegateQueue;
_chipWorkQueue = queue;
_factory = factory;
_serverEndpoints = [[NSMutableArray alloc] init];
_commissionableBrowser = nil;
_deviceControllerDelegateBridge = new MTRDeviceControllerDelegateBridge();
if ([self checkForInitError:(_deviceControllerDelegateBridge != nullptr) logMsg:kDeviceControllerErrorPairingInit]) {
return nil;
}
_partialDACVerifier = new chip::Credentials::PartialDACVerifier();
if ([self checkForInitError:(_partialDACVerifier != nullptr) logMsg:kDeviceControllerErrorPartialDacVerifierInit]) {
return nil;
}
_operationalCredentialsDelegate = new MTROperationalCredentialsDelegate(self);
if ([self checkForInitError:(_operationalCredentialsDelegate != nullptr) logMsg:kDeviceControllerErrorOperationalCredentialsInit]) {
return nil;
}
// Provide a way to test different subscription pool sizes without code change
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:kDefaultSubscriptionPoolSizeOverrideKey]) {
NSInteger subscriptionPoolSizeOverride = [defaults integerForKey:kDefaultSubscriptionPoolSizeOverrideKey];
if (subscriptionPoolSizeOverride < 1) {
concurrentSubscriptionPoolSize = 1;
} else {
concurrentSubscriptionPoolSize = static_cast<NSUInteger>(subscriptionPoolSizeOverride);
}
MTR_LOG(" *** Overriding pool size of MTRDeviceController with: %lu", static_cast<unsigned long>(concurrentSubscriptionPoolSize));
}
if (!concurrentSubscriptionPoolSize) {
concurrentSubscriptionPoolSize = 1;
}
MTR_LOG("%@ Setting up pool size of MTRDeviceController with: %lu", self, static_cast<unsigned long>(concurrentSubscriptionPoolSize));
_concurrentSubscriptionPool = [[MTRAsyncWorkQueue alloc] initWithContext:self width:concurrentSubscriptionPoolSize];
_storedFabricIndex = chip::kUndefinedFabricIndex;
_storedCompressedFabricID = std::nullopt;
self.nodeID = nil;
self.fabricID = nil;
self.rootPublicKey = nil;
_storageBehaviorConfiguration = storageBehaviorConfiguration;
// We let the operational browser know about ourselves here, because
// after this point we are guaranteed to have shutDownCppController
// called by the factory.
if (!startSuspended) {
dispatch_async(_chipWorkQueue, ^{
factory.operationalBrowser->ControllerActivated();
});
}
}
return self;
}
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@: %p, uuid: %@, suspended: %@>", NSStringFromClass(self.class), self, self.uniqueIdentifier, MTR_YES_NO(self.suspended)];
}
- (BOOL)isRunning
{
return _cppCommissioner != nullptr;
}
- (void)_controllerSuspended
{
MTRDeviceControllerFactory * factory = _factory;
dispatch_async(_chipWorkQueue, ^{
factory.operationalBrowser->ControllerDeactivated();
if (self.shouldAdvertiseOperational) {
auto * fabricTable = factory.fabricTable;
if (fabricTable) {
// We don't care about errors here. If our fabric is gone, nothing to do.
fabricTable->SetShouldAdvertiseIdentity(self->_storedFabricIndex, chip::FabricTable::AdvertiseIdentity::No);
[factory resetOperationalAdvertising];
}
}
});
}
- (void)_controllerResumed
{
MTRDeviceControllerFactory * factory = _factory;
dispatch_async(_chipWorkQueue, ^{
factory.operationalBrowser->ControllerActivated();
if (self.shouldAdvertiseOperational) {
auto * fabricTable = factory.fabricTable;
if (fabricTable) {
// We don't care about errors here. If our fabric is gone, nothing to do.
fabricTable->SetShouldAdvertiseIdentity(self->_storedFabricIndex, chip::FabricTable::AdvertiseIdentity::Yes);
[factory resetOperationalAdvertising];
}
}
});
}
- (BOOL)matchesPendingShutdownControllerWithOperationalCertificate:(nullable MTRCertificateDERBytes)operationalCertificate andRootCertificate:(nullable MTRCertificateDERBytes)rootCertificate
{
if (!operationalCertificate || !rootCertificate) {
return FALSE;
}
NSNumber * nodeID = [MTRDeviceControllerParameters nodeIDFromNOC:operationalCertificate];
NSNumber * fabricID = [MTRDeviceControllerParameters fabricIDFromNOC:operationalCertificate];
NSData * publicKey = [MTRDeviceControllerParameters publicKeyFromCertificate:rootCertificate];
std::lock_guard lock(_assertionLock);
// If any of the local above are nil, the return will be false since MTREqualObjects handles them correctly
return _keepRunningAssertionCounter > 0 && _shutdownPending && MTREqualObjects(nodeID, self.nodeID) && MTREqualObjects(fabricID, self.fabricID) && MTREqualObjects(publicKey, self.rootPublicKey);
}
- (void)addRunAssertion
{
std::lock_guard lock(_assertionLock);
// Only take an assertion if running
if ([self isRunning]) {
++_keepRunningAssertionCounter;
MTR_LOG("%@ Adding keep running assertion, total %lu", self, static_cast<unsigned long>(_keepRunningAssertionCounter));
}
}
- (void)removeRunAssertion;
{
std::lock_guard lock(_assertionLock);
if (_keepRunningAssertionCounter > 0) {
--_keepRunningAssertionCounter;
MTR_LOG("%@ Removing keep running assertion, total %lu", self, static_cast<unsigned long>(_keepRunningAssertionCounter));
if ([self isRunning] && _keepRunningAssertionCounter == 0 && _shutdownPending) {
MTR_LOG("%@ All assertions removed and shutdown is pending, shutting down", self);
[self finalShutdown];
}
}
}
- (void)clearPendingShutdown
{
std::lock_guard lock(_assertionLock);
_shutdownPending = NO;
}
- (void)shutdown
{
std::lock_guard lock(_assertionLock);
if (_keepRunningAssertionCounter > 0) {
MTR_LOG("%@ Pending shutdown since %lu assertions are present", self, static_cast<unsigned long>(_keepRunningAssertionCounter));
_shutdownPending = YES;
return;
}
[self finalShutdown];
[super shutdown];
}
- (void)finalShutdown
{
os_unfair_lock_assert_owner(&_assertionLock);
MTR_LOG("%@ shutdown called", self);
if (_cppCommissioner == nullptr) {
// Already shut down.
return;
}
MTR_LOG("Shutting down %@: %@", NSStringFromClass(self.class), self);
[self cleanupAfterStartup];
}
// Clean up from a state where startup was called.
- (void)cleanupAfterStartup
{
// Invalidate our MTRDevice instances before we shut down our secure
// sessions and whatnot, so they don't start trying to resubscribe when we
// do the secure session shutdowns. Since we don't want to hold the lock
// while calling out into arbitrary invalidation code, snapshot the list of
// devices before we start invalidating.
MTR_LOG("%s: %@", __PRETTY_FUNCTION__, self);
os_unfair_lock_lock(self.deviceMapLock);
auto * devices = [self.nodeIDToDeviceMap objectEnumerator].allObjects;
[self.nodeIDToDeviceMap removeAllObjects];
os_unfair_lock_unlock(self.deviceMapLock);
for (MTRDevice * device in devices) {
[device invalidate];
}
// Since MTRDevice invalidate may issue asynchronous writes to storage, perform a
// block synchronously on the storage delegate queue so the async write operations
// get to run, in case the API client tears down the storage backend afterwards.
[self.controllerDataStore synchronouslyPerformBlock:^{
MTR_LOG("%@ Finished flushing data write operations", self);
}];
[self stopBrowseForCommissionables];
[_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
{
MTR_LOG("%s: %p", __PRETTY_FUNCTION__, self);
assertChipStackLockedByCurrentThread();
// Shut down all our endpoints.
for (MTRServerEndpoint * endpoint in [_serverEndpoints copy]) {
[self removeServerEndpointOnMatterQueue:endpoint];
}
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();
// Don't clear out our fabric index association until controller
// shutdown completes, in case it wants to write to storage as it
// shuts down.
_storedFabricIndex = chip::kUndefinedFabricIndex;
_storedCompressedFabricID = std::nullopt;
self.nodeID = nil;
self.fabricID = nil;
self.rootPublicKey = nil;
delete commissionerToShutDown;
if (_operationalCredentialsDelegate != nil) {
_operationalCredentialsDelegate->SetDeviceCommissioner(nullptr);
}
}
if (!self.suspended) {
_factory.operationalBrowser->ControllerDeactivated();
}
_shutdownPending = NO;
}
- (void)deinitFromFactory
{
[self cleanup];
}
// Clean up any members we might have allocated.
- (void)cleanup
{
VerifyOrDie(_cppCommissioner == nullptr);
if (_defaultDACVerifier) {
delete _defaultDACVerifier;
_defaultDACVerifier = nullptr;
}
if (_attestationTrustStoreBridge) {
delete _attestationTrustStoreBridge;
_attestationTrustStoreBridge = 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", self);
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", self, 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", self);
return;
}
if ([startupParams keypairsMatchCertificates] == NO) {
MTR_LOG_ERROR("%@ Provided keypairs do not match certificates", self);
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", self);
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:kDeviceControllerErrorSigningKeypairInit]) {
return;
}
signingKeypair = &_signingKeypairBridge;
}
errorCode = _operationalCredentialsDelegate->Init(
signingKeypair, startupParams.ipk, startupParams.rootCertificate, startupParams.intermediateCertificate);
if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorOperationalCredentialsInit]) {
return;
}
_cppCommissioner = new chip::Controller::DeviceCommissioner();
// 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:kDeviceControllerErrorOperationalKeypairInit]) {
return;
}
commissionerParams.operationalKeypair = &_operationalKeypairBridge;
commissionerParams.hasExternallyOwnedOperationalKeypair = true;
}
if (startupParams.operationalCertificate) {
commissionerParams.controllerNOC = AsByteSpan(startupParams.operationalCertificate);
} else {
chip::MutableByteSpan noc(nocBuffer);
chip::CATValues cats = chip::kUndefinedCATs;
if (startupParams.caseAuthenticatedTags != nil) {
errorCode = SetToCATValues(startupParams.caseAuthenticatedTags, cats);
if (errorCode != CHIP_NO_ERROR) {
// SetToCATValues already handles logging.
return;
}
}
if (commissionerParams.operationalKeypair != nullptr) {
errorCode = _operationalCredentialsDelegate->GenerateNOC(startupParams.nodeID.unsignedLongLongValue,
startupParams.fabricID.unsignedLongLongValue, cats, commissionerParams.operationalKeypair->Pubkey(), noc);
if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorGenerateNOC]) {
return;
}
} else {
// Generate a new random keypair.
uint8_t csrBuffer[chip::Crypto::kMIN_CSR_Buffer_Size];
chip::MutableByteSpan csr(csrBuffer);
errorCode = startupParams.fabricTable->AllocatePendingOperationalKey(startupParams.fabricIndex, csr);
if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorKeyAllocation]) {
return;
}
chip::Crypto::P256PublicKey pubKey;
errorCode = VerifyCertificateSigningRequest(csr.data(), csr.size(), pubKey);
if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorCSRValidation]) {
return;
}
errorCode = _operationalCredentialsDelegate->GenerateNOC(
startupParams.nodeID.unsignedLongLongValue, startupParams.fabricID.unsignedLongLongValue, cats, pubKey, noc);
if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorGenerateNOC]) {
return;
}
}
commissionerParams.controllerNOC = noc;
}
commissionerParams.controllerVendorId = static_cast<chip::VendorId>([startupParams.vendorID unsignedShortValue]);
_shouldAdvertiseOperational = startupParams.advertiseOperational;
commissionerParams.enableServerInteractions = !self.suspended && self.shouldAdvertiseOperational;
// We never want plain "removal" from the fabric table since this leaves
// the in-memory state out of sync with what's in storage. In per-controller
// storage mode, have the controller delete itself from the fabric table on shutdown.
// In factory storage mode we need to keep fabric information around so we can
// start another controller on that existing fabric at a later time.
commissionerParams.removeFromFabricTableOnShutdown = false;
commissionerParams.deleteFromFabricTableOnShutdown = (startupParams.storageDelegate != nil);
commissionerParams.permitMultiControllerFabrics = startupParams.allowMultipleControllersPerFabric;
// Set up our attestation verifier. Assume we want to use the default
// one, until something tells us otherwise.
const chip::Credentials::AttestationTrustStore * trustStore;
if (startupParams.productAttestationAuthorityCertificates) {
_attestationTrustStoreBridge
= new MTRAttestationTrustStoreBridge(startupParams.productAttestationAuthorityCertificates);
trustStore = _attestationTrustStoreBridge;
} else {
// TODO: Replace testingRootStore with a AttestationTrustStore that has the necessary official PAA roots available
trustStore = chip::Credentials::GetTestAttestationTrustStore();
}
_defaultDACVerifier = new chip::Credentials::DefaultDACVerifier(trustStore);
if (startupParams.certificationDeclarationCertificates) {
auto cdTrustStore = _defaultDACVerifier->GetCertificationDeclarationTrustStore();
if (cdTrustStore == nullptr) {
errorCode = CHIP_ERROR_INCORRECT_STATE;
}
if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorCDCertStoreInit]) {
return;
}
for (NSData * cdSigningCert in startupParams.certificationDeclarationCertificates) {
errorCode = cdTrustStore->AddTrustedKey(AsByteSpan(cdSigningCert));
if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorCDCertStoreInit]) {
return;
}
}
}
commissionerParams.deviceAttestationVerifier = _defaultDACVerifier;
auto & factory = chip::Controller::DeviceControllerFactory::GetInstance();
errorCode = factory.SetupCommissioner(commissionerParams, *_cppCommissioner);
if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorCommissionerInit]) {
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:kDeviceControllerErrorIPKInit]) {
return;
}
errorCode = chip::Credentials::SetSingleIpkEpochKey(
_factory.groupDataProvider, fabricIdx, _operationalCredentialsDelegate->GetIPK(), compressedId);
if ([self checkForStartError:errorCode logMsg:kDeviceControllerErrorIPKInit]) {
return;
}
self->_storedFabricIndex = fabricIdx;
self->_storedCompressedFabricID = _cppCommissioner->GetCompressedFabricId();
self->_controllerNodeID = @(_cppCommissioner->GetNodeId());
chip::Crypto::P256PublicKey rootPublicKey;
if (_cppCommissioner->GetRootPublicKey(rootPublicKey) == CHIP_NO_ERROR) {
self.rootPublicKey = [NSData dataWithBytes:rootPublicKey.Bytes() length:rootPublicKey.Length()];
self.nodeID = @(_cppCommissioner->GetNodeId());
self.fabricID = @(_cppCommissioner->GetFabricId());
}
commissionerInitialized = YES;
// Set self as delegate, which fans out delegate callbacks to all added delegates
id<MTRDeviceControllerDelegate> selfDelegate = static_cast<id<MTRDeviceControllerDelegate>>(self);
self->_deviceControllerDelegateBridge->setDelegate(self, selfDelegate, _chipWorkQueue);
MTR_LOG("%@ startup succeeded for nodeID 0x%016llX", self, self->_cppCommissioner->GetNodeId());
});
if (commissionerInitialized == NO) {
MTR_LOG_ERROR("%@ startup failed", self);
[self cleanupAfterStartup];
return NO;
}
// TODO: Once setNocChainIssuer no longer needs to be supported,
// we can just move the internals of
// setOperationalCertificateIssuer into the sync-dispatched block
// above.
if (![self setOperationalCertificateIssuer:startupParams.operationalCertificateIssuer
queue:startupParams.operationalCertificateIssuerQueue]) {
MTR_LOG_ERROR("%@ operationalCertificateIssuer and operationalCertificateIssuerQueue must both be nil or both be non-nil", self);
[self cleanupAfterStartup];
return NO;
}
if (_controllerDataStore) {
// If the storage delegate supports the bulk read API, then a dictionary of nodeID => cluster data dictionary would be passed to the handler. Otherwise this would be a no-op, and stored attributes for MTRDevice objects will be loaded lazily in -deviceForNodeID:.
[_controllerDataStore fetchAttributeDataForAllDevices:^(NSDictionary<NSNumber *, NSDictionary<MTRClusterPath *, MTRDeviceClusterData *> *> * _Nonnull clusterDataByNode) {
MTR_LOG("%@ Loaded attribute values for %lu nodes from storage for controller uuid %@", self, static_cast<unsigned long>(clusterDataByNode.count), self.uniqueIdentifier);
std::lock_guard lock(*self.deviceMapLock);
NSMutableArray * deviceList = [NSMutableArray array];
for (NSNumber * nodeID in clusterDataByNode) {
NSDictionary * clusterData = clusterDataByNode[nodeID];
MTRDevice * device = [self _setupDeviceForNodeID:nodeID prefetchedClusterData:clusterData];
MTR_LOG("%@ Loaded %lu cluster data from storage for %@", self, static_cast<unsigned long>(clusterData.count), device);
[deviceList addObject:device];
}
#define kSecondsToWaitBeforeAPIClientRetainsMTRDevice 60
// Keep the devices retained for a while, in case API client doesn't immediately retain them.
//
// Note that this is just an optimization to avoid throwing the information away and immediately
// re-reading it from storage.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (kSecondsToWaitBeforeAPIClientRetainsMTRDevice * NSEC_PER_SEC)), dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{
MTR_LOG("%@ un-retain devices loaded at startup %lu", self, static_cast<unsigned long>(deviceList.count));
});
}];
}
MTR_LOG("%@ startup: %@", NSStringFromClass(self.class), self);
return YES;
}
static inline void emitMetricForSetupPayload(MTRSetupPayload * payload)
{
MATTER_LOG_METRIC(kMetricDeviceVendorID, [payload.vendorID unsignedIntValue]);
MATTER_LOG_METRIC(kMetricDeviceProductID, [payload.productID unsignedIntValue]);
}
- (BOOL)setupCommissioningSessionWithPayload:(MTRSetupPayload *)payload
newNodeID:(NSNumber *)newNodeID
error:(NSError * __autoreleasing *)error
{
if (self.suspended) {
MTR_LOG_ERROR("%@ suspended: can't set up commissioning session for device ID 0x%016llX with setup payload %@", self, newNodeID.unsignedLongLongValue, payload);
// TODO: Can we do a better error here?
if (error) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE];
}
return NO;
}
MTR_LOG("%@ Setting up commissioning session for device ID 0x%016llX with setup payload %@", self, newNodeID.unsignedLongLongValue, payload);
[[MTRMetricsCollector sharedInstance] resetMetrics];
// Track overall commissioning
MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissioning);
emitMetricForSetupPayload(payload);
// Capture in a block variable to avoid losing granularity for metrics,
// when translating CHIP_ERROR to NSError
__block CHIP_ERROR errorCode = CHIP_NO_ERROR;
auto block = ^BOOL {
// Track work until end of scope
MATTER_LOG_METRIC_SCOPE(kMetricSetupWithPayload, errorCode);
// 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) {
errorCode = CHIP_ERROR_INVALID_ARGUMENT;
return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorSetupCodeGen error:error];
}
chip::NodeId nodeId = [newNodeID unsignedLongLongValue];
self->_operationalCredentialsDelegate->SetDeviceID(nodeId);
MATTER_LOG_METRIC_BEGIN(kMetricSetupPASESession);
errorCode = self->_cppCommissioner->EstablishPASEConnection(nodeId, [pairingCode UTF8String]);
if (CHIP_NO_ERROR == errorCode) {
self->_deviceControllerDelegateBridge->SetDeviceNodeID(nodeId);
} else {
MATTER_LOG_METRIC_END(kMetricSetupPASESession, errorCode);
}
return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorPairDevice error:error];
};
auto success = [self syncRunOnWorkQueueWithBoolReturnValue:block error:error];
if (!success) {
MATTER_LOG_METRIC_END(kMetricDeviceCommissioning, errorCode);
}
return success;
}
- (BOOL)setupCommissioningSessionWithDiscoveredDevice:(MTRCommissionableBrowserResult *)discoveredDevice
payload:(MTRSetupPayload *)payload
newNodeID:(NSNumber *)newNodeID
error:(NSError * __autoreleasing *)error
{
MTR_LOG("%@ Setting up commissioning session for already-discovered device %@ and device ID 0x%016llX with setup payload %@", self, discoveredDevice, newNodeID.unsignedLongLongValue, payload);
[[MTRMetricsCollector sharedInstance] resetMetrics];
// Track overall commissioning
MATTER_LOG_METRIC_BEGIN(kMetricDeviceCommissioning);
emitMetricForSetupPayload(payload);
// Capture in a block variable to avoid losing granularity for metrics,
// when translating CHIP_ERROR to NSError
__block CHIP_ERROR errorCode = CHIP_NO_ERROR;
auto block = ^BOOL {
// Track work until end of scope
MATTER_LOG_METRIC_SCOPE(kMetricSetupWithDiscovered, errorCode);
chip::NodeId nodeId = [newNodeID unsignedLongLongValue];
self->_operationalCredentialsDelegate->SetDeviceID(nodeId);
errorCode = CHIP_ERROR_INVALID_ARGUMENT;
chip::Optional<chip::Controller::SetUpCodePairerParameters> params = discoveredDevice.params;
if (params.HasValue()) {
auto pinCode = static_cast<uint32_t>(payload.setupPasscode.unsignedLongValue);
params.Value().SetSetupPINCode(pinCode);
MATTER_LOG_METRIC_BEGIN(kMetricSetupPASESession);
errorCode = self->_cppCommissioner->EstablishPASEConnection(nodeId, params.Value());
if (CHIP_NO_ERROR == errorCode) {
self->_deviceControllerDelegateBridge->SetDeviceNodeID(nodeId);
} else {
MATTER_LOG_METRIC_END(kMetricSetupPASESession, errorCode);
}
} else {
// 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) {
errorCode = CHIP_ERROR_INVALID_ARGUMENT;
return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorSetupCodeGen error:error];
}
for (id key in discoveredDevice.interfaces) {
auto resolutionData = discoveredDevice.interfaces[key].resolutionData;
if (!resolutionData.HasValue()) {
continue;
}
MATTER_LOG_METRIC_BEGIN(kMetricSetupPASESession);
errorCode = self->_cppCommissioner->EstablishPASEConnection(
nodeId, [pairingCode UTF8String], chip::Controller::DiscoveryType::kDiscoveryNetworkOnly, resolutionData);
if (CHIP_NO_ERROR == errorCode) {
self->_deviceControllerDelegateBridge->SetDeviceNodeID(nodeId);
} else {
MATTER_LOG_METRIC_END(kMetricSetupPASESession, errorCode);
break;
}
}
}
return ![MTRDeviceController_Concrete checkForError:errorCode logMsg:kDeviceControllerErrorPairDevice error:error];
};
auto success = [self syncRunOnWorkQueueWithBoolReturnValue:block error:error];
if (!success) {
MATTER_LOG_METRIC_END(kMetricDeviceCommissioning, errorCode);
}
return success;
}
- (BOOL)commissionNodeWithID:(NSNumber *)nodeID
commissioningParams:(MTRCommissioningParameters *)commissioningParams
error:(NSError * __autoreleasing *)error
{
MTR_LOG("%@ trying to commission node with ID 0x%016llX parameters %@", self, nodeID.unsignedLongLongValue, commissioningParams);
if (self.suspended) {
MTR_LOG_ERROR("%@ suspended: can't commission device ID 0x%016llX with parameters %@", self, nodeID.unsignedLongLongValue, commissioningParams);
// TODO: Can we do a better error here?
if (error) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE];
}
return NO;
}
auto block = ^BOOL {
chip::Controller::CommissioningParameters params;
if (commissioningParams.readEndpointInformation) {
params.SetExtraReadPaths(MTREndpointInfo.requiredAttributePaths);
}
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.acceptedTermsAndConditions && commissioningParams.acceptedTermsAndConditionsVersion) {
if (!chip::CanCastTo<uint16_t>([commissioningParams.acceptedTermsAndConditions unsignedIntValue])) {
MTR_LOG_ERROR("%@ Error: acceptedTermsAndConditions value should be between 0 and 65535", self);
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_INTEGER_VALUE];
return NO;
}
if (!chip::CanCastTo<uint16_t>([commissioningParams.acceptedTermsAndConditionsVersion unsignedIntValue])) {
MTR_LOG_ERROR("%@ Error: acceptedTermsAndConditionsVersion value should be between 0 and 65535", self);
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_INTEGER_VALUE];
return NO;
}
chip::Controller::TermsAndConditionsAcknowledgement termsAndConditionsAcknowledgement = {
.acceptedTermsAndConditions = static_cast<uint16_t>([commissioningParams.acceptedTermsAndConditions unsignedIntValue]),
.acceptedTermsAndConditionsVersion = static_cast<uint16_t>([commissioningParams.acceptedTermsAndConditionsVersion unsignedIntValue])
};
params.SetTermsAndConditionsAcknowledgement(termsAndConditionsAcknowledgement);
}
params.SetSkipCommissioningComplete(commissioningParams.skipCommissioningComplete);
if (commissioningParams.wifiSSID) {
chip::ByteSpan ssid = AsByteSpan(commissioningParams.wifiSSID);
chip::ByteSpan credentials;