forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMTRDeviceControllerFactory.mm
1356 lines (1150 loc) · 53.7 KB
/
MTRDeviceControllerFactory.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) 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 "MTRDeviceControllerFactory.h"
#import "MTRDeviceControllerFactory_Internal.h"
#import <Matter/MTRDefines.h>
#import <Matter/MTRClusterConstants.h>
#import <Matter/MTRDeviceControllerParameters.h>
#import <Matter/MTRServerCluster.h>
#import "MTRCertificates.h"
#import "MTRDemuxingStorage.h"
#import "MTRDeviceController.h"
#import "MTRDeviceControllerStartupParams.h"
#import "MTRDeviceControllerStartupParams_Internal.h"
#import "MTRDeviceController_Internal.h"
#import "MTRDiagnosticLogsDownloader.h"
#import "MTRError_Internal.h"
#import "MTRFabricInfo_Internal.h"
#import "MTRFramework.h"
#import "MTRLogging_Internal.h"
#import "MTRMetricKeys.h"
#import "MTRMetricsCollector.h"
#import "MTROTAProviderDelegateBridge.h"
#import "MTROperationalBrowser.h"
#import "MTRP256KeypairBridge.h"
#import "MTRPersistentStorageDelegateBridge.h"
#import "MTRServerAccessControl.h"
#import "MTRServerCluster_Internal.h"
#import "MTRServerEndpoint_Internal.h"
#import "MTRSessionResumptionStorageBridge.h"
#import "MTRUnfairLock.h"
#import "NSDataSpanConversion.h"
#import <os/lock.h>
#include <app/server/Dnssd.h>
#include <controller/CHIPDeviceControllerFactory.h>
#include <credentials/CHIPCert.h>
#include <credentials/FabricTable.h>
#include <credentials/GroupDataProviderImpl.h>
#include <credentials/PersistentStorageOpCertStore.h>
#include <crypto/PersistentStorageOperationalKeystore.h>
#include <crypto/RawKeySessionKeystore.h>
#include <lib/support/Pool.h>
#include <lib/support/TestPersistentStorageDelegate.h>
#include <messaging/ReliableMessageMgr.h>
#include <messaging/ReliableMessageProtocolConfig.h>
#include <platform/PlatformManager.h>
#include <cstdlib>
using namespace chip;
using namespace chip::Controller;
using namespace chip::Tracing::DarwinFramework;
static bool sExitHandlerRegistered = false;
static void ShutdownOnExit()
{
MTR_LOG_INFO("ShutdownOnExit invoked on exit");
[[MTRDeviceControllerFactory sharedInstance] stopControllerFactory];
}
@interface MTRDeviceControllerFactoryParams ()
// Flag to keep track of whether our .storage is real consumer-provided storage
// or just the fake thing we made up.
@property (nonatomic, assign) BOOL hasStorage;
@end
MTR_DIRECT_MEMBERS
@interface MTRDeviceControllerFactory ()
- (void)preWarmCommissioningSessionDone;
@end
MTR_DIRECT_MEMBERS
@implementation MTRDeviceControllerFactory {
dispatch_queue_t _chipWorkQueue;
DeviceControllerFactory * _controllerFactory;
Credentials::IgnoreCertificateValidityPeriodPolicy _certificateValidityPolicy;
Crypto::RawKeySessionKeystore _sessionKeystore;
// We use TestPersistentStorageDelegate just to get an in-memory store to back
// our group data provider impl. We initialize this store correctly on every
// controller startup, so don't need to actually persist it.
TestPersistentStorageDelegate _groupStorageDelegate;
Credentials::GroupDataProviderImpl _groupDataProvider;
// _usingPerControllerStorage is only written once, during controller
// factory start. After that it is only read, and can be read from
// arbitrary threads.
BOOL _usingPerControllerStorage;
PersistentStorageDelegate * _persistentStorageDelegate;
MTRSessionResumptionStorageBridge * _sessionResumptionStorage;
PersistentStorageOperationalKeystore * _keystore;
Credentials::PersistentStorageOpCertStore * _opCertStore;
MTROperationalBrowser * _operationalBrowser;
// productAttestationAuthorityCertificates and certificationDeclarationCertificates are just copied
// from MTRDeviceControllerFactoryParams.
NSArray<MTRCertificateDERBytes> * _Nullable _productAttestationAuthorityCertificates;
NSArray<MTRCertificateDERBytes> * _Nullable _certificationDeclarationCertificates;
BOOL _advertiseOperational;
// Lock used to serialize access to the "controllers" array and the
// "_controllerBeingStarted" and "_controllerBeingShutDown" ivars, since those
// need to be touched from both whatever queue is starting controllers and from
// the Matter queue. The way this lock is used assumes that:
//
// 1) The only mutating accesses to the controllers array and the ivars happen
// when the current queue is not the Matter queue or in a block that was
// sync-dispatched to the Matter queue. This is a good assumption, because
// the implementations of the functions that mutate these do sync dispatch to
// the Matter queue, which would deadlock if they were called when that queue
// was the current queue.
//
// 2) It's our API consumer's responsibility to serialize access to us from
// outside.
//
// These assumptions mean that if we are in a block that was sync-dispatched to
// the Matter queue, that block cannot race with either the Matter queue nor the
// non-Matter queue. Similarly, if we are in a situation where the Matter queue
// has been shut down, any accesses to the variables cannot race anything else.
//
// This means that:
//
// A. In a sync-dispatched block, or if the Matter queue has been shut down, we
// do not need to lock and can do read or write access.
// B. Apart from item A, mutations of the array and ivars must happen outside the
// Matter queue and must lock.
// C. Apart from item A, accesses on the Matter queue must be reads only and
// must lock.
// D. Locking around reads not from the Matter queue is OK but not required.
os_unfair_lock _controllersLock;
NSMutableArray<MTRDeviceController *> * _controllers;
MTRDeviceController * _controllerBeingStarted;
MTRDeviceController * _controllerBeingShutDown;
// Next available fabric index. Only valid when _controllerBeingStarted is
// non-nil, and then it corresponds to the controller being started. This
// is only accessed on the Matter queue or after the Matter queue has shut
// down.
FabricIndex _nextAvailableFabricIndex;
id<MTROTAProviderDelegate> _Nullable _otaProviderDelegate;
dispatch_queue_t _Nullable _otaProviderDelegateQueue;
MTRServerEndpoint * _otaProviderEndpoint;
std::unique_ptr<MTROTAProviderDelegateBridge> _otaProviderDelegateBridge;
MTRDiagnosticLogsDownloader * _Nullable _diagnosticLogsDownloader;
// Array of all server endpoints across all controllers, used to ensure
// in an atomic way that endpoint IDs are unique.
NSMutableArray<MTRServerEndpoint *> * _serverEndpoints;
os_unfair_lock _serverEndpointsLock; // Protects access to _serverEndpoints.
class final : public DeviceLayer::BleScannerDelegate {
void OnBleScanStopped() override
{
[MTRDeviceControllerFactory.sharedInstance preWarmCommissioningSessionDone];
}
} _preWarmingDelegate;
}
+ (void)initialize
{
MTRFrameworkInit();
}
+ (MTRDeviceControllerFactory *)sharedInstance
{
static MTRDeviceControllerFactory * factory = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// initialize the factory.
factory = [[MTRDeviceControllerFactory alloc] init];
});
return factory;
}
- (instancetype)init
{
if (!(self = [super init])) {
return nil;
}
// Start the work queue and leave it running. There is no performance
// cost to having an idle dispatch queue, and it simplifies our logic.
DeviceLayer::PlatformMgrImpl().StartEventLoopTask();
_chipWorkQueue = DeviceLayer::PlatformMgrImpl().GetWorkQueue();
_controllerFactory = &DeviceControllerFactory::GetInstance();
// Initialize our default-constructed GroupDataProviderImpl.
// For now default args are fine, since we are just using this for the IPK.
_groupDataProvider.SetStorageDelegate(&_groupStorageDelegate);
_groupDataProvider.SetSessionKeystore(&_sessionKeystore);
CHIP_ERROR err = _groupDataProvider.Init();
VerifyOrDieWithMsg(err == CHIP_NO_ERROR, NotSpecified,
"GroupDataProviderImpl::Init() failed: %" CHIP_ERROR_FORMAT, err.Format());
_controllersLock = OS_UNFAIR_LOCK_INIT;
_controllers = [[NSMutableArray alloc] init];
_serverEndpointsLock = OS_UNFAIR_LOCK_INIT;
_serverEndpoints = [[NSMutableArray alloc] init];
return self;
}
- (void)dealloc
{
[self stopControllerFactory];
_groupDataProvider.Finish();
}
- (void)_assertCurrentQueueIsNotMatterQueue
{
VerifyOrDie(!DeviceLayer::PlatformMgrImpl().IsWorkQueueCurrentQueue());
}
- (void)cleanupStartupObjects
{
assertChipStackLockedByCurrentThread();
MTR_LOG_INFO("Cleaning startup objects in controller factory");
// Make sure the deinit order here is the reverse of the init order in
// startControllerFactory:
_certificationDeclarationCertificates = nil;
_productAttestationAuthorityCertificates = nil;
if (_opCertStore) {
_opCertStore->Finish();
delete _opCertStore;
_opCertStore = nullptr;
}
if (_keystore) {
_keystore->Finish();
delete _keystore;
_keystore = nullptr;
}
_otaProviderDelegateQueue = nil;
_otaProviderDelegate = nil;
if (_sessionResumptionStorage) {
delete _sessionResumptionStorage;
_sessionResumptionStorage = nullptr;
}
if (_persistentStorageDelegate) {
delete _persistentStorageDelegate;
_persistentStorageDelegate = nullptr;
}
_diagnosticLogsDownloader = nil;
ShutdownMetricsCollection();
}
- (CHIP_ERROR)_initFabricTable:(FabricTable &)fabricTable
{
return fabricTable.Init(
{ .storage = _persistentStorageDelegate, .operationalKeystore = _keystore, .opCertStore = _opCertStore });
}
- (nullable NSArray<MTRFabricInfo *> *)knownFabrics
{
[self _assertCurrentQueueIsNotMatterQueue];
if (!_running) { // Note: reading _running from outside of the Matter work queue
return nil;
}
__block NSMutableArray<MTRFabricInfo *> * fabricList;
__block BOOL listFilled = NO;
dispatch_sync(_chipWorkQueue, ^{
FabricTable fabricTable;
CHIP_ERROR err = [self _initFabricTable:fabricTable];
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Can't initialize fabric table when getting known fabrics: %s", err.AsString());
return;
}
fabricList = [NSMutableArray<MTRFabricInfo *> arrayWithCapacity:fabricTable.FabricCount()];
for (const auto & fabricInfo : fabricTable) {
auto * info = [[MTRFabricInfo alloc] initWithFabricTable:fabricTable fabricInfo:fabricInfo];
if (info == nil) {
// Failed to read one of our fabrics.
return;
}
[fabricList addObject:info];
}
listFilled = YES;
});
if (listFilled == NO) {
return nil;
}
return fabricList;
}
- (BOOL)startControllerFactory:(MTRDeviceControllerFactoryParams *)startupParams error:(NSError * __autoreleasing *)error
{
return [self _startControllerFactory:startupParams startingController:NO error:error];
}
- (BOOL)_startControllerFactory:(MTRDeviceControllerFactoryParams *)startupParams
startingController:(BOOL)startingController
error:(NSError * __autoreleasing *)error
{
[self _assertCurrentQueueIsNotMatterQueue];
__block CHIP_ERROR err = CHIP_ERROR_INTERNAL;
dispatch_sync(_chipWorkQueue, ^{
if (_running) {
// TODO: When treating a duplicate call as success we should validate parameters match
MTR_LOG_DEBUG("Ignoring duplicate call to startup, Matter controller factory already started...");
ExitNow(err = CHIP_NO_ERROR);
}
StartupMetricsCollection();
InitializeServerAccessControl();
if (startupParams.hasStorage) {
_persistentStorageDelegate = new MTRPersistentStorageDelegateBridge(startupParams.storage);
_sessionResumptionStorage = nullptr;
_usingPerControllerStorage = NO;
} else {
_persistentStorageDelegate = new MTRDemuxingStorage(self);
_sessionResumptionStorage = new MTRSessionResumptionStorageBridge(self);
_usingPerControllerStorage = YES;
}
_otaProviderDelegate = startupParams.otaProviderDelegate;
if (_otaProviderDelegate != nil) {
_otaProviderDelegateQueue = dispatch_queue_create(
"org.csa-iot.matter.framework.otaprovider.workqueue", DISPATCH_QUEUE_SERIAL_WITH_AUTORELEASE_POOL);
}
// TODO: Allow passing a different keystore implementation via startupParams.
_keystore = new PersistentStorageOperationalKeystore();
SuccessOrExit(err = _keystore->Init(_persistentStorageDelegate));
// TODO Allow passing a different opcert store implementation via startupParams.
_opCertStore = new Credentials::PersistentStorageOpCertStore();
SuccessOrExit(err = _opCertStore->Init(_persistentStorageDelegate));
_productAttestationAuthorityCertificates = [startupParams.productAttestationAuthorityCertificates copy];
_certificationDeclarationCertificates = [startupParams.certificationDeclarationCertificates copy];
{
chip::Controller::FactoryInitParams params;
if (startupParams.port != nil) {
params.listenPort = [startupParams.port unsignedShortValue];
}
params.enableServerInteractions = startupParams.shouldStartServer;
params.groupDataProvider = &_groupDataProvider;
params.sessionKeystore = &_sessionKeystore;
params.fabricIndependentStorage = _persistentStorageDelegate;
params.operationalKeystore = _keystore;
params.opCertStore = _opCertStore;
params.certificateValidityPolicy = &_certificateValidityPolicy;
params.sessionResumptionStorage = _sessionResumptionStorage;
SuccessOrExit(err = _controllerFactory->Init(params));
}
// This needs to happen after DeviceControllerFactory::Init,
// because that creates (lazily, by calling functions with
// static variables in them) some static-lifetime objects.
if (!sExitHandlerRegistered) {
if (atexit(ShutdownOnExit) != 0) {
char error[128];
strerror_r(errno, error, sizeof(error));
MTR_LOG_ERROR("Warning: Failed to register atexit handler: %s", error);
}
sExitHandlerRegistered = true;
}
HeapObjectPoolExitHandling::IgnoreLeaksOnExit();
// Make sure we don't leave a system state running while we have no
// controllers started. This is working around the fact that a system
// state is brought up live on factory init, and not when it comes time
// to actually start a controller, and does not actually clean itself up
// until its refcount (which starts as 0) goes to 0.
// TODO: Don't cause a stack shutdown and restart if startingController
_controllerFactory->RetainSystemState();
_controllerFactory->ReleaseSystemState();
_advertiseOperational = startupParams.shouldStartServer;
_running = YES;
err = CHIP_NO_ERROR;
exit:
if (err != CHIP_NO_ERROR) {
// Note: Since we have failed no later than _controllerFactory->Init(),
// there is no need to call _controllerFactory->Shutdown() here.
[self cleanupStartupObjects];
}
});
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Failed to start Matter controller factory: %" CHIP_ERROR_FORMAT, err.Format());
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:err];
}
return NO;
}
return YES;
}
- (void)stopControllerFactory
{
[self _assertCurrentQueueIsNotMatterQueue];
while ([_controllers count] != 0) {
[_controllers[0] shutdown];
}
dispatch_sync(_chipWorkQueue, ^{
VerifyOrReturn(_running);
MTR_LOG_INFO("Shutting down the Matter controller factory");
_controllerFactory->Shutdown();
[self cleanupStartupObjects];
_running = NO;
_advertiseOperational = NO;
});
}
/**
* Helper function to start a device controller with the given startup params.
* The fabricChecker block will run on the Matter queue, and is expected to
* return nil if pre-startup fabric table checks fail, and set fabricError to
* the right error value in that situation.
*
* The provided controller is expected to have just been allocated and to not be
* initialized yet.
*/
- (MTRDeviceController * _Nullable)_startDeviceController:(MTRDeviceController *)controller
startupParams:(id)startupParams
fabricChecker:(MTRDeviceControllerStartupParamsInternal * (^)(FabricTable * fabricTable,
MTRDeviceController * controller,
CHIP_ERROR & fabricError))fabricChecker
error:(NSError * __autoreleasing *)error
{
[self _assertCurrentQueueIsNotMatterQueue];
id<MTRDeviceControllerStorageDelegate> _Nullable storageDelegate;
dispatch_queue_t _Nullable storageDelegateQueue;
NSUUID * uniqueIdentifier;
id<MTROTAProviderDelegate> _Nullable otaProviderDelegate;
dispatch_queue_t _Nullable otaProviderDelegateQueue;
if ([startupParams isKindOfClass:[MTRDeviceControllerParameters class]]) {
MTRDeviceControllerParameters * params = startupParams;
storageDelegate = params.storageDelegate;
storageDelegateQueue = params.storageDelegateQueue;
uniqueIdentifier = params.uniqueIdentifier;
otaProviderDelegate = params.otaProviderDelegate;
otaProviderDelegateQueue = params.otaProviderDelegateQueue;
} else if ([startupParams isKindOfClass:[MTRDeviceControllerStartupParams class]]) {
MTRDeviceControllerStartupParams * params = startupParams;
storageDelegate = nil;
storageDelegateQueue = nil;
uniqueIdentifier = params.uniqueIdentifier;
otaProviderDelegate = nil;
otaProviderDelegateQueue = nil;
} else {
MTR_LOG_ERROR("Unknown kind of startup params: %@", startupParams);
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT];
}
return nil;
}
if (!_running) { // Note: reading _running from outside of the Matter work queue
if (storageDelegate != nil) {
MTR_LOG_DEFAULT("Auto-starting Matter controller factory in per-controller storage mode");
auto * params = [[MTRDeviceControllerFactoryParams alloc] initWithoutStorage];
if (![self _startControllerFactory:params startingController:YES error:error]) {
return nil;
}
} else {
MTR_LOG_ERROR("Trying to start controller while Matter controller factory is not running");
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE];
}
return nil;
}
}
if (_usingPerControllerStorage && storageDelegate == nil) {
MTR_LOG_ERROR("Must have a controller storage delegate when we do not have storage for the controller factory");
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT];
}
return nil;
}
if (!_usingPerControllerStorage && storageDelegate != nil) {
MTR_LOG_ERROR("Must not have a controller storage delegate when we have storage for the controller factory");
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT];
}
return nil;
}
// Fall back to the factory-wide OTA provider delegate if one is not
// provided in the startup params.
if (otaProviderDelegate == nil) {
otaProviderDelegate = _otaProviderDelegate;
otaProviderDelegateQueue = _otaProviderDelegateQueue;
}
controller = [controller initWithFactory:self
queue:_chipWorkQueue
storageDelegate:storageDelegate
storageDelegateQueue:storageDelegateQueue
otaProviderDelegate:otaProviderDelegate
otaProviderDelegateQueue:otaProviderDelegateQueue
uniqueIdentifier:uniqueIdentifier];
if (controller == nil) {
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT];
}
return nil;
}
if ([_controllers count] == 0) {
dispatch_sync(_chipWorkQueue, ^{
self->_operationalBrowser = new MTROperationalBrowser(self, self->_chipWorkQueue);
});
}
// Add the controller to _controllers now, so if we fail partway through its
// startup we will still do the right cleanups.
os_unfair_lock_lock(&_controllersLock);
[_controllers addObject:controller];
os_unfair_lock_unlock(&_controllersLock);
__block MTRDeviceControllerStartupParamsInternal * params = nil;
__block CHIP_ERROR fabricError = CHIP_ERROR_INTERNAL;
// Create a temporary FabricTable instance for the fabricChecker logic.
// We want the block to end up with just a pointer to the fabric table,
// since we know our on-stack instance will outlive the block.
FabricTable fabricTableInstance;
FabricTable * fabricTable = &fabricTableInstance;
dispatch_sync(_chipWorkQueue, ^{
fabricError = [self _initFabricTable:*fabricTable];
if (fabricError != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Can't initialize fabric table: %s", fabricError.AsString());
return;
}
params = fabricChecker(fabricTable, controller, fabricError);
if (params == nil) {
return;
}
// Check that we are not trying to start a controller with a uniqueIdentifier that
// matches a running controller.
auto * controllersCopy = [self getRunningControllers];
for (MTRDeviceController * existing in controllersCopy) {
if (existing != controller && [existing.uniqueIdentifier isEqual:params.uniqueIdentifier]) {
MTR_LOG_ERROR("Already have running controller with uniqueIdentifier %@", existing.uniqueIdentifier);
fabricError = CHIP_ERROR_INVALID_ARGUMENT;
params = nil;
return;
}
}
// Save off the next available fabric index, in case we are starting a
// controller with a new fabric index. This just needs to happen before
// we set _controllerBeingStarted below.
fabricError = fabricTable->PeekFabricIndexForNextAddition(self->_nextAvailableFabricIndex);
if (fabricError != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Out of space in the fabric table");
params = nil;
return;
}
});
if (params == nil) {
[self controllerShuttingDown:controller];
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:fabricError];
}
return nil;
}
os_unfair_lock_lock(&_controllersLock);
_controllerBeingStarted = controller;
os_unfair_lock_unlock(&_controllersLock);
BOOL ok = [controller startup:params];
os_unfair_lock_lock(&_controllersLock);
_controllerBeingStarted = nil;
os_unfair_lock_unlock(&_controllersLock);
if (ok == NO) {
// TODO: get error from controller's startup.
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INTERNAL];
}
return nil;
}
controller = [self maybeInitializeOTAProvider:controller];
if (controller == nil) {
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INTERNAL];
}
}
return controller;
}
- (MTRDeviceController * _Nullable)createControllerOnExistingFabric:(MTRDeviceControllerStartupParams *)startupParams
error:(NSError * __autoreleasing *)error
{
[self _assertCurrentQueueIsNotMatterQueue];
if (_usingPerControllerStorage) {
// We can never have an "existing fabric" for a new controller to be
// created on, in the sense of createControllerOnExistingFabric.
MTR_LOG_ERROR("Can't createControllerOnExistingFabric when using per-controller data store");
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INCORRECT_STATE];
}
return nil;
}
return [self _startDeviceController:[MTRDeviceController alloc]
startupParams:startupParams
fabricChecker:^MTRDeviceControllerStartupParamsInternal *(
FabricTable * fabricTable, MTRDeviceController * controller, CHIP_ERROR & fabricError) {
const FabricInfo * fabric = nullptr;
BOOL ok = [self findMatchingFabric:*fabricTable params:startupParams fabric:&fabric];
if (!ok) {
MTR_LOG_ERROR("Can't start on existing fabric: fabric matching failed");
fabricError = CHIP_ERROR_INTERNAL;
return nil;
}
if (fabric == nullptr) {
MTR_LOG_ERROR("Can't start on existing fabric: fabric not found");
fabricError = CHIP_ERROR_NOT_FOUND;
return nil;
}
auto * controllersCopy = [self getRunningControllers];
for (MTRDeviceController * existing in controllersCopy) {
BOOL isRunning = YES; // assume the worst
if ([existing isRunningOnFabric:fabricTable
fabricIndex:fabric->GetFabricIndex()
isRunning:&isRunning]
!= CHIP_NO_ERROR) {
MTR_LOG_ERROR("Can't tell what fabric a controller is running on. Not safe to start.");
fabricError = CHIP_ERROR_INTERNAL;
return nil;
}
if (isRunning) {
MTR_LOG_ERROR("Can't start on existing fabric: another controller is running on it");
fabricError = CHIP_ERROR_INCORRECT_STATE;
return nil;
}
}
auto * params =
[[MTRDeviceControllerStartupParamsInternal alloc] initForExistingFabric:fabricTable
fabricIndex:fabric->GetFabricIndex()
keystore:self->_keystore
advertiseOperational:self->_advertiseOperational
params:startupParams];
params.productAttestationAuthorityCertificates = self->_productAttestationAuthorityCertificates;
params.certificationDeclarationCertificates = self->_certificationDeclarationCertificates;
return params;
}
error:error];
}
- (MTRDeviceController * _Nullable)createControllerOnNewFabric:(MTRDeviceControllerStartupParams *)startupParams
error:(NSError * __autoreleasing *)error
{
[self _assertCurrentQueueIsNotMatterQueue];
if (startupParams.vendorID == nil) {
MTR_LOG_ERROR("Must provide vendor id when starting controller on new fabric");
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT];
}
return nil;
}
if (startupParams.intermediateCertificate != nil && startupParams.rootCertificate == nil) {
MTR_LOG_ERROR("Must provide a root certificate when using an intermediate certificate");
if (error != nil) {
*error = [MTRError errorForCHIPErrorCode:CHIP_ERROR_INVALID_ARGUMENT];
}
return nil;
}
return [self _startDeviceController:[MTRDeviceController alloc]
startupParams:startupParams
fabricChecker:^MTRDeviceControllerStartupParamsInternal *(
FabricTable * fabricTable, MTRDeviceController * controller, CHIP_ERROR & fabricError) {
const FabricInfo * fabric = nullptr;
BOOL ok = [self findMatchingFabric:*fabricTable params:startupParams fabric:&fabric];
if (!ok) {
MTR_LOG_ERROR("Can't start on new fabric: fabric matching failed");
fabricError = CHIP_ERROR_INTERNAL;
return nil;
}
if (fabric != nullptr) {
MTR_LOG_ERROR("Can't start on new fabric that matches existing fabric");
fabricError = CHIP_ERROR_INCORRECT_STATE;
return nil;
}
auto * params =
[[MTRDeviceControllerStartupParamsInternal alloc] initForNewFabric:fabricTable
keystore:self->_keystore
advertiseOperational:self->_advertiseOperational
params:startupParams];
params.productAttestationAuthorityCertificates = self->_productAttestationAuthorityCertificates;
params.certificationDeclarationCertificates = self->_certificationDeclarationCertificates;
return params;
}
error:error];
}
- (void)preWarmCommissioningSession
{
dispatch_async(_chipWorkQueue, ^{
CHIP_ERROR err = CHIP_ERROR_INCORRECT_STATE;
if (!self->_running) {
MTR_LOG_ERROR("Can't pre-warm, Matter controller factory is not running");
} else {
MTR_LOG_DEFAULT("Pre-warming commissioning session");
self->_controllerFactory->EnsureAndRetainSystemState();
err = DeviceLayer::PlatformMgrImpl().StartBleScan(&self->_preWarmingDelegate, DeviceLayer::BleScanMode::kPreWarm);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Pre-warming failed: %" CHIP_ERROR_FORMAT, err.Format());
self->_controllerFactory->ReleaseSystemState();
}
}
MATTER_LOG_METRIC(kMetricPreWarmCommissioning, err);
});
}
- (void)preWarmCommissioningSessionDone
{
assertChipStackLockedByCurrentThread();
MTR_LOG_DEFAULT("Pre-warming done");
self->_controllerFactory->ReleaseSystemState();
}
// Finds a fabric that matches the given params, if one exists.
//
// Returns NO on failure, YES on success. If YES is returned, the
// outparam will be written to, but possibly with a null value.
//
// fabricTable should be an initialized fabric table. It needs to
// outlive the consumer's use of the FabricInfo we return, which is
// why it's provided by the caller.
- (BOOL)findMatchingFabric:(FabricTable &)fabricTable
params:(MTRDeviceControllerStartupParams *)params
fabric:(const FabricInfo * _Nullable * _Nonnull)fabric
{
assertChipStackLockedByCurrentThread();
Crypto::P256PublicKey pubKey;
if (params.rootCertificate != nil) {
CHIP_ERROR err = ExtractPubkeyFromX509Cert(AsByteSpan(params.rootCertificate), pubKey);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Can't extract public key from root certificate: %s", ErrorStr(err));
return NO;
}
} else {
// No root certificate means the nocSigner is using the root keys, because
// consumers must provide a root certificate whenever an ICA is used.
CHIP_ERROR err = MTRP256KeypairBridge::MatterPubKeyFromSecKeyRef(params.nocSigner.publicKey, &pubKey);
if (err != CHIP_NO_ERROR) {
MTR_LOG_ERROR("Can't extract public key from MTRKeypair: %s", ErrorStr(err));
return NO;
}
}
*fabric = fabricTable.FindFabric(pubKey, params.fabricID.unsignedLongLongValue);
return YES;
}
// Initialize the MTROTAProviderDelegateBridge if it has not been initialized already
//
// Returns nil on failure, the input controller on success.
// If the provider has been initialized already, it is not considered as a failure.
//
- (MTRDeviceController * _Nullable)maybeInitializeOTAProvider:(MTRDeviceController * _Nonnull)controller
{
[self _assertCurrentQueueIsNotMatterQueue];
VerifyOrReturnValue([_controllers count] == 1, controller);
_otaProviderEndpoint = [MTRServerEndpoint rootNodeEndpoint];
// TODO: Have the OTA Provider cluster revision accessible somewhere?
auto * otaProviderCluster = [[MTRServerCluster alloc] initWithClusterID:@(MTRClusterIDTypeOTASoftwareUpdateProviderID) revision:@(1)];
otaProviderCluster.acceptedCommands = @[
@(MTRCommandIDTypeClusterOTASoftwareUpdateProviderCommandQueryImageID),
@(MTRCommandIDTypeClusterOTASoftwareUpdateProviderCommandApplyUpdateRequestID),
@(MTRCommandIDTypeClusterOTASoftwareUpdateProviderCommandNotifyUpdateAppliedID),
];
otaProviderCluster.generatedCommands = @[
@(MTRCommandIDTypeClusterOTASoftwareUpdateProviderCommandQueryImageResponseID),
@(MTRCommandIDTypeClusterOTASoftwareUpdateProviderCommandApplyUpdateResponseID),
];
[otaProviderCluster addAccessGrant:[MTRAccessGrant accessGrantForAllNodesWithPrivilege:MTRAccessControlEntryPrivilegeOperate]];
// Not expected to fail, since we are following the rules for clusters here.
[_otaProviderEndpoint addServerCluster:otaProviderCluster];
if (![self addServerEndpoint:_otaProviderEndpoint]) {
MTR_LOG_ERROR("Failed to add OTA endpoint on factory. Why?");
[controller shutdown];
return nil;
}
// This endpoint is not actually associated with a specific controller; we
// just need to have a working Matter event loop to bring it up.
[_otaProviderEndpoint associateWithController:nil];
__block CHIP_ERROR err;
dispatch_sync(_chipWorkQueue, ^{
[self->_otaProviderEndpoint registerMatterEndpoint];
// Now that our endpoint exists, go ahead and create the OTA delegate
// bridge. Its constructor relies on the endpoint existing.
_otaProviderDelegateBridge = std::make_unique<MTROTAProviderDelegateBridge>();
auto systemState = _controllerFactory->GetSystemState();
err = _otaProviderDelegateBridge->Init(systemState->SystemLayer(), systemState->ExchangeMgr());
});
if (CHIP_NO_ERROR != err) {
MTR_LOG_ERROR("Failed to init provider delegate bridge: %" CHIP_ERROR_FORMAT, err.Format());
[controller shutdown];
return nil;
}
return controller;
}
- (void)resetOperationalAdvertising
{
if (!_advertiseOperational) {
// No need to reset anything; we are not advertising the things that
// would need to get reset.
return;
}
std::lock_guard lock(_controllersLock);
if (_controllers.count != 0) {
// We have a running controller. That means we likely need to reset
// operational advertising for that controller.
dispatch_async(_chipWorkQueue, ^{
// StartServer() is the only API we have for resetting DNS-SD
// advertising. It sure would be nice if there were a "restart"
// that was a no-op if the DNS-SD server was not already
// running.
app::DnssdServer::Instance().StartServer();
});
}
}
- (void)controllerShuttingDown:(MTRDeviceController *)controller
{
[self _assertCurrentQueueIsNotMatterQueue];
if (![_controllers containsObject:controller]) {
MTR_LOG_ERROR("Controller we don't know about shutting down");
return;
}
os_unfair_lock_lock(&_controllersLock);
// Make sure to set _controllerBeingShutDown and do the remove in the same
// locked section, so there is never a time when the controller is gone from
// both places as viewed from the Matter thread, as long as it's locking
// around its reads.
_controllerBeingShutDown = controller;
[_controllers removeObject:controller];
os_unfair_lock_unlock(&_controllersLock);
// Do the controller shutdown on the Matter work queue.
dispatch_sync(_chipWorkQueue, ^{
FabricIndex fabricIndex = controller.fabricIndex;
if (fabricIndex != kUndefinedFabricIndex) {
// Clear out out group keys for this fabric index, in case fabric
// indices get reused later. If a new controller is started on the
// same fabric it will be handed the IPK at that point.
self->_groupDataProvider.RemoveGroupKeys(fabricIndex);
}
// If there are no other controllers left, we can shut down some things.
// Do this before we shut down the controller itself, because the
// OtaProviderDelegateBridge uses some services provided by the system
// state without retaining it.
if (_controllers.count == 0) {
delete self->_operationalBrowser;
self->_operationalBrowser = nullptr;
if (_otaProviderDelegateBridge) {
_otaProviderDelegateBridge->Shutdown();
_otaProviderDelegateBridge.reset();
}
if (_otaProviderEndpoint != nil) {
[_otaProviderEndpoint unregisterMatterEndpoint];
[_otaProviderEndpoint invalidate];
[self removeServerEndpoint:_otaProviderEndpoint];
_otaProviderEndpoint = nil;
}
} else if (_otaProviderDelegateBridge) {
_otaProviderDelegateBridge->ControllerShuttingDown(controller);
}
[controller shutDownCppController];
self->_controllerBeingShutDown = nil;
if (self->_controllerBeingStarted == controller) {
self->_controllerBeingStarted = nil;
}
});
[controller deinitFromFactory];
}
- (NSArray<MTRDeviceController *> *)getRunningControllers
{
std::lock_guard lock(_controllersLock);
return [_controllers copy];
}
- (nullable MTRDeviceController *)runningControllerForFabricIndex:(FabricIndex)fabricIndex
includeControllerStartingUp:(BOOL)includeControllerStartingUp
includeControllerShuttingDown:(BOOL)includeControllerShuttingDown
{
assertChipStackLockedByCurrentThread();
auto * controllersCopy = [self getRunningControllers];
os_unfair_lock_lock(&_controllersLock);
MTRDeviceController * controllerBeingStarted = _controllerBeingStarted;
MTRDeviceController * controllerBeingShutDown = _controllerBeingShutDown;
os_unfair_lock_unlock(&_controllersLock);
for (MTRDeviceController * existing in controllersCopy) {
if (existing.fabricIndex == fabricIndex) {
return existing;
}
}
if (includeControllerStartingUp == YES && controllerBeingStarted != nil && fabricIndex == _nextAvailableFabricIndex) {
return controllerBeingStarted;
}
if (includeControllerShuttingDown == YES && controllerBeingShutDown != nil
&& controllerBeingShutDown.fabricIndex == fabricIndex) {
return controllerBeingShutDown;
}
return nil;
}
- (nullable MTRDeviceController *)runningControllerForFabricIndex:(chip::FabricIndex)fabricIndex