forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMTRDeviceControllerDataStore.mm
1258 lines (1049 loc) · 49.3 KB
/
MTRDeviceControllerDataStore.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) 2023 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.
*/
#include "MTRDeviceControllerDataStore.h"
// Importing MTRBaseDevice.h for the MTRAttributePath class. Needs to change when https://github.com/project-chip/connectedhomeip/issues/31247 is fixed.
#import "MTRBaseDevice.h"
#import "MTRLogging_Internal.h"
#include <lib/core/CASEAuthTag.h>
#include <lib/core/NodeId.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/SafeInt.h>
// FIXME: Are these good key strings? https://github.com/project-chip/connectedhomeip/issues/28973
static NSString * sResumptionNodeListKey = @"caseResumptionNodeList";
static NSString * sLastLocallyUsedNOCKey = @"lastLocallyUsedControllerNOC";
static NSString * ResumptionByNodeIDKey(NSNumber * nodeID)
{
return [NSString stringWithFormat:@"caseResumptionByNodeID/%llx", nodeID.unsignedLongLongValue];
}
static NSString * ResumptionByResumptionIDKey(NSData * resumptionID)
{
return
[NSString stringWithFormat:@"caseResumptionByResumptionID/%s", [resumptionID base64EncodedStringWithOptions:0].UTF8String];
}
static bool IsUnsignedIntegerNumber(id _Nullable value)
{
if (value == nil) {
return false;
}
if (![value isKindOfClass:[NSNumber class]]) {
return false;
}
NSNumber * number = value;
// Not sure how to check for the number being an integer.
if ([number compare:@(0)] == NSOrderedAscending) {
return false;
}
return true;
}
static bool IsValidNodeIDNumber(id _Nullable value)
{
// Node IDs cannot be negative.
if (!IsUnsignedIntegerNumber(value)) {
return false;
}
NSNumber * number = value;
// Validate that this is a valid operational ID, not some garbage unsigned
// int value that can't be a node id.
uint64_t unsignedValue = number.unsignedLongLongValue;
if (!chip::IsOperationalNodeId(unsignedValue)) {
return false;
}
return true;
}
static bool IsValidCATNumber(id _Nullable value)
{
// CATs cannot be negative.
if (!IsUnsignedIntegerNumber(value)) {
return false;
}
NSNumber * number = value;
// Validate that this is a valid CAT value and, not some garbage unsigned int
// value that can't be a CAT.
uint64_t unsignedValue = number.unsignedLongLongValue;
if (!chip::CanCastTo<chip::CASEAuthTag>(unsignedValue)) {
return false;
}
auto tag = static_cast<chip::CASEAuthTag>(unsignedValue);
if (!chip::IsValidCASEAuthTag(tag)) {
return false;
}
return true;
}
@implementation MTRDeviceControllerDataStore {
id<MTRDeviceControllerStorageDelegate> _storageDelegate;
dispatch_queue_t _storageDelegateQueue;
// Controller owns us, so we have to make sure to not keep it alive.
__weak MTRDeviceController * _controller;
// Array of nodes with resumption info, oldest-stored first.
NSMutableArray<NSNumber *> * _nodesWithResumptionInfo;
}
- (nullable instancetype)initWithController:(MTRDeviceController *)controller
storageDelegate:(id<MTRDeviceControllerStorageDelegate>)storageDelegate
storageDelegateQueue:(dispatch_queue_t)storageDelegateQueue
{
if (!(self = [super init])) {
return nil;
}
_controller = controller;
_storageDelegate = storageDelegate;
_storageDelegateQueue = storageDelegateQueue;
__block id resumptionNodeList;
dispatch_sync(_storageDelegateQueue, ^{
@autoreleasepool {
// NOTE: controller, not our weak ref, since we know it's still
// valid under this sync dispatch.
resumptionNodeList = [_storageDelegate controller:controller
valueForKey:sResumptionNodeListKey
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
}
});
if (resumptionNodeList != nil) {
if (![resumptionNodeList isKindOfClass:[NSArray class]]) {
MTR_LOG_ERROR("List of CASE resumption node IDs is not an array");
return nil;
}
for (id value in resumptionNodeList) {
if (!IsValidNodeIDNumber(value)) {
MTR_LOG_ERROR("Resumption node ID contains invalid value: %@", value);
return nil;
}
}
_nodesWithResumptionInfo = [resumptionNodeList mutableCopy];
} else {
_nodesWithResumptionInfo = [[NSMutableArray alloc] init];
}
return self;
}
- (void)fetchAttributeDataForAllDevices:(MTRDeviceControllerDataStoreClusterDataHandler)clusterDataHandler
{
__block NSDictionary<NSString *, id> * dataStoreSecureLocalValues = nil;
MTRDeviceController * controller = _controller;
VerifyOrReturn(controller != nil); // No way to call delegate without controller.
dispatch_sync(_storageDelegateQueue, ^{
if ([self->_storageDelegate respondsToSelector:@selector(valuesForController:securityLevel:sharingType:)]) {
dataStoreSecureLocalValues = [self->_storageDelegate valuesForController:controller securityLevel:MTRStorageSecurityLevelSecure sharingType:MTRStorageSharingTypeNotShared];
}
});
if (dataStoreSecureLocalValues.count) {
clusterDataHandler([self _getClusterDataFromSecureLocalValues:dataStoreSecureLocalValues]);
}
}
- (nullable MTRCASESessionResumptionInfo *)findResumptionInfoByNodeID:(NSNumber *)nodeID
{
return [self _findResumptionInfoWithKey:ResumptionByNodeIDKey(nodeID)];
}
- (nullable MTRCASESessionResumptionInfo *)findResumptionInfoByResumptionID:(NSData *)resumptionID
{
return [self _findResumptionInfoWithKey:ResumptionByResumptionIDKey(resumptionID)];
}
- (void)storeResumptionInfo:(MTRCASESessionResumptionInfo *)resumptionInfo
{
MTRDeviceController * controller = _controller;
VerifyOrReturn(controller != nil); // No way to call delegate without controller.
auto * oldInfo = [self findResumptionInfoByNodeID:resumptionInfo.nodeID];
dispatch_sync(_storageDelegateQueue, ^{
if (oldInfo != nil) {
// Remove old resumption id key. No need to do that for the
// node id, because we are about to overwrite it.
[_storageDelegate controller:controller
removeValueForKey:ResumptionByResumptionIDKey(oldInfo.resumptionID)
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
[_nodesWithResumptionInfo removeObject:resumptionInfo.nodeID];
}
[_storageDelegate controller:controller
storeValue:resumptionInfo
forKey:ResumptionByNodeIDKey(resumptionInfo.nodeID)
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
[_storageDelegate controller:controller
storeValue:resumptionInfo
forKey:ResumptionByResumptionIDKey(resumptionInfo.resumptionID)
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
// Update our resumption info node list.
[_nodesWithResumptionInfo addObject:resumptionInfo.nodeID];
[_storageDelegate controller:controller
storeValue:[_nodesWithResumptionInfo copy]
forKey:sResumptionNodeListKey
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
});
}
- (void)clearAllResumptionInfo
{
MTRDeviceController * controller = _controller;
VerifyOrReturn(controller != nil); // No way to call delegate without controller.
// Can we do less dispatch? We would need to have a version of
// _findResumptionInfoWithKey that assumes we are already on the right queue.
for (NSNumber * nodeID in _nodesWithResumptionInfo) {
auto * oldInfo = [self findResumptionInfoByNodeID:nodeID];
if (oldInfo != nil) {
dispatch_sync(_storageDelegateQueue, ^{
[_storageDelegate controller:controller
removeValueForKey:ResumptionByResumptionIDKey(oldInfo.resumptionID)
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
[_storageDelegate controller:controller
removeValueForKey:ResumptionByNodeIDKey(oldInfo.nodeID)
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
});
}
}
[_nodesWithResumptionInfo removeAllObjects];
}
- (CHIP_ERROR)storeLastLocallyUsedNOC:(MTRCertificateTLVBytes)noc
{
MTRDeviceController * controller = _controller;
VerifyOrReturnError(controller != nil, CHIP_ERROR_PERSISTED_STORAGE_FAILED); // No way to call delegate without controller.
__block BOOL ok;
dispatch_sync(_storageDelegateQueue, ^{
ok = [_storageDelegate controller:controller
storeValue:noc
forKey:sLastLocallyUsedNOCKey
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
});
return ok ? CHIP_NO_ERROR : CHIP_ERROR_PERSISTED_STORAGE_FAILED;
}
- (MTRCertificateTLVBytes _Nullable)fetchLastLocallyUsedNOC
{
MTRDeviceController * controller = _controller;
VerifyOrReturnValue(controller != nil, nil); // No way to call delegate without controller.
__block id data;
dispatch_sync(_storageDelegateQueue, ^{
@autoreleasepool {
data = [_storageDelegate controller:controller
valueForKey:sLastLocallyUsedNOCKey
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
}
});
if (data == nil) {
return nil;
}
if (![data isKindOfClass:[NSData class]]) {
return nil;
}
return data;
}
- (nullable MTRCASESessionResumptionInfo *)_findResumptionInfoWithKey:(nullable NSString *)key
{
MTRDeviceController * controller = _controller;
VerifyOrReturnValue(controller != nil, nil); // No way to call delegate without controller.
// key could be nil if [NSString stringWithFormat] returns nil for some reason.
if (key == nil) {
return nil;
}
__block id resumptionInfo;
dispatch_sync(_storageDelegateQueue, ^{
@autoreleasepool {
resumptionInfo = [_storageDelegate controller:controller
valueForKey:key
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
}
});
if (resumptionInfo == nil) {
return nil;
}
if (![resumptionInfo isKindOfClass:[MTRCASESessionResumptionInfo class]]) {
return nil;
}
return resumptionInfo;
}
#pragma - Attribute Cache utility
/** MTRDevice cache storage
*
* Per controller:
* NodeID index
* key: "attrCacheNodeIndex"
* value: list of nodeIDs
* EndpointID index
* key: "attrCacheEndpointIndex:<nodeID>"
* value: list of endpoint IDs
* ClusterID index
* key: "attrCacheClusterIndex:<nodeID>:<endpointID>"
* value: list of cluster IDs
* Cluster data entry:
* key: "attrCacheClusterData:<nodeID>:<endpointID>:<clusterID>"
* value: MTRDeviceClusterData
*/
- (id)_fetchAttributeCacheValueForKey:(NSString *)key expectedClass:(Class)expectedClass;
{
MTRDeviceController * controller = _controller;
VerifyOrReturnValue(controller != nil, nil); // No way to call delegate without controller.
id data;
@autoreleasepool {
data = [_storageDelegate controller:controller
valueForKey:key
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
}
if (data == nil) {
return nil;
}
if (![data isKindOfClass:expectedClass]) {
return nil;
}
return data;
}
- (BOOL)_storeAttributeCacheValue:(id)value forKey:(NSString *)key
{
MTRDeviceController * controller = _controller;
VerifyOrReturnValue(controller != nil, NO); // No way to call delegate without controller.
return [_storageDelegate controller:controller
storeValue:value
forKey:key
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
}
- (BOOL)_bulkStoreAttributeCacheValues:(NSDictionary<NSString *, id<NSSecureCoding>> *)values
{
MTRDeviceController * controller = _controller;
VerifyOrReturnValue(controller != nil, NO); // No way to call delegate without controller.
return [_storageDelegate controller:controller
storeValues:values
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
}
- (BOOL)_removeAttributeCacheValueForKey:(NSString *)key
{
MTRDeviceController * controller = _controller;
VerifyOrReturnValue(controller != nil, NO); // No way to call delegate without controller.
return [_storageDelegate controller:controller
removeValueForKey:key
securityLevel:MTRStorageSecurityLevelSecure
sharingType:MTRStorageSharingTypeNotShared];
}
static NSString * sAttributeCacheNodeIndexKey = @"attrCacheNodeIndex";
- (nullable NSArray<NSNumber *> *)_fetchNodeIndex
{
dispatch_assert_queue(_storageDelegateQueue);
return [self _fetchAttributeCacheValueForKey:sAttributeCacheNodeIndexKey expectedClass:[NSArray class]];
}
- (BOOL)_storeNodeIndex:(NSArray<NSNumber *> *)nodeIndex
{
dispatch_assert_queue(_storageDelegateQueue);
return [self _storeAttributeCacheValue:nodeIndex forKey:sAttributeCacheNodeIndexKey];
}
- (BOOL)_deleteNodeIndex
{
dispatch_assert_queue(_storageDelegateQueue);
return [self _removeAttributeCacheValueForKey:sAttributeCacheNodeIndexKey];
}
static NSString * sAttributeCacheEndpointIndexKeyPrefix = @"attrCacheEndpointIndex";
- (NSString *)_endpointIndexKeyForNodeID:(NSNumber *)nodeID
{
return [sAttributeCacheEndpointIndexKeyPrefix stringByAppendingFormat:@":0x%016llX", nodeID.unsignedLongLongValue];
}
- (nullable NSArray<NSNumber *> *)_fetchEndpointIndexForNodeID:(NSNumber *)nodeID
{
dispatch_assert_queue(_storageDelegateQueue);
if (!nodeID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return nil;
}
return [self _fetchAttributeCacheValueForKey:[self _endpointIndexKeyForNodeID:nodeID] expectedClass:[NSArray class]];
}
- (BOOL)_storeEndpointIndex:(NSArray<NSNumber *> *)endpointIndex forNodeID:(NSNumber *)nodeID
{
dispatch_assert_queue(_storageDelegateQueue);
if (!nodeID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return NO;
}
return [self _storeAttributeCacheValue:endpointIndex forKey:[self _endpointIndexKeyForNodeID:nodeID]];
}
- (BOOL)_removeEndpointFromEndpointIndex:(NSNumber *)endpointID forNodeID:(NSNumber *)nodeID
{
dispatch_assert_queue(_storageDelegateQueue);
if (!endpointID || !nodeID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return NO;
}
NSMutableArray<NSNumber *> * endpointIndex = [[self _fetchEndpointIndexForNodeID:nodeID] mutableCopy];
if (endpointIndex == nil) {
return NO;
}
[endpointIndex removeObject:endpointID];
return [self _storeEndpointIndex:endpointIndex forNodeID:nodeID];
}
- (BOOL)_deleteEndpointIndexForNodeID:(NSNumber *)nodeID
{
dispatch_assert_queue(_storageDelegateQueue);
if (!nodeID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return NO;
}
return [self _removeAttributeCacheValueForKey:[self _endpointIndexKeyForNodeID:nodeID]];
}
static NSString * sAttributeCacheClusterIndexKeyPrefix = @"attrCacheClusterIndex";
- (NSString *)_clusterIndexKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID
{
return [sAttributeCacheClusterIndexKeyPrefix stringByAppendingFormat:@":0x%016llX:%0x04X", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue];
}
- (nullable NSArray<NSNumber *> *)_fetchClusterIndexForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID
{
dispatch_assert_queue(_storageDelegateQueue);
if (!nodeID || !endpointID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return nil;
}
return [self _fetchAttributeCacheValueForKey:[self _clusterIndexKeyForNodeID:nodeID endpointID:endpointID] expectedClass:[NSArray class]];
}
- (BOOL)_storeClusterIndex:(NSArray<NSNumber *> *)clusterIndex forNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID
{
dispatch_assert_queue(_storageDelegateQueue);
if (!nodeID || !endpointID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return NO;
}
return [self _storeAttributeCacheValue:clusterIndex forKey:[self _clusterIndexKeyForNodeID:nodeID endpointID:endpointID]];
}
- (BOOL)_deleteClusterIndexForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID
{
dispatch_assert_queue(_storageDelegateQueue);
if (!nodeID || !endpointID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return NO;
}
return [self _removeAttributeCacheValueForKey:[self _clusterIndexKeyForNodeID:nodeID endpointID:endpointID]];
}
static NSString * sAttributeCacheClusterDataKeyPrefix = @"attrCacheClusterData";
- (NSString *)_clusterDataKeyForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID
{
return [sAttributeCacheClusterDataKeyPrefix stringByAppendingFormat:@":0x%016llX:0x%04X:0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue];
}
- (nullable MTRDeviceClusterData *)_fetchClusterDataForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID
{
dispatch_assert_queue(_storageDelegateQueue);
if (!nodeID || !endpointID || !clusterID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return nil;
}
return [self _fetchAttributeCacheValueForKey:[self _clusterDataKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID] expectedClass:[MTRDeviceClusterData class]];
}
- (BOOL)_storeClusterData:(MTRDeviceClusterData *)clusterData forNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID
{
dispatch_assert_queue(_storageDelegateQueue);
if (!nodeID || !endpointID || !clusterID || !clusterData) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return NO;
}
return [self _storeAttributeCacheValue:clusterData forKey:[self _clusterDataKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID]];
}
- (BOOL)_deleteClusterDataForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID
{
dispatch_assert_queue(_storageDelegateQueue);
if (!nodeID || !endpointID || !clusterID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return NO;
}
return [self _removeAttributeCacheValueForKey:[self _clusterDataKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID]];
}
#pragma - Attribute Cache management
#ifndef ATTRIBUTE_CACHE_VERBOSE_LOGGING
#define ATTRIBUTE_CACHE_VERBOSE_LOGGING 0
#endif
#ifdef DEBUG
- (void)unitTestPruneEmptyStoredClusterDataBranches
{
dispatch_sync(_storageDelegateQueue, ^{
[self _pruneEmptyStoredClusterDataBranches];
});
}
#endif
- (void)_pruneEmptyStoredClusterDataBranches
{
dispatch_assert_queue(_storageDelegateQueue);
NSUInteger storeFailures = 0;
// Fetch node index
NSArray<NSNumber *> * nodeIndex = [self _fetchNodeIndex];
NSMutableArray<NSNumber *> * nodeIndexCopy = [nodeIndex mutableCopy];
for (NSNumber * nodeID in nodeIndex) {
// Fetch endpoint index
NSArray<NSNumber *> * endpointIndex = [self _fetchEndpointIndexForNodeID:nodeID];
NSMutableArray<NSNumber *> * endpointIndexCopy = [endpointIndex mutableCopy];
for (NSNumber * endpointID in endpointIndex) {
// Fetch cluster index
NSArray<NSNumber *> * clusterIndex = [self _fetchClusterIndexForNodeID:nodeID endpointID:endpointID];
NSMutableArray<NSNumber *> * clusterIndexCopy = [clusterIndex mutableCopy];
for (NSNumber * clusterID in clusterIndex) {
// Fetch cluster data, if it exists.
MTRDeviceClusterData * clusterData = [self _fetchClusterDataForNodeID:nodeID endpointID:endpointID clusterID:clusterID];
if (!clusterData) {
[clusterIndexCopy removeObject:clusterID];
}
}
if (clusterIndex.count != clusterIndexCopy.count) {
BOOL success;
if (clusterIndexCopy.count) {
success = [self _storeClusterIndex:clusterIndexCopy forNodeID:nodeID endpointID:endpointID];
} else {
[endpointIndexCopy removeObject:endpointID];
success = [self _deleteClusterIndexForNodeID:nodeID endpointID:endpointID];
}
if (!success) {
storeFailures++;
MTR_LOG_ERROR("Store failed in _pruneEmptyStoredClusterDataBranches for clusterIndex (%lu) @ node 0x%016llX endpoint %u", static_cast<unsigned long>(clusterIndexCopy.count), nodeID.unsignedLongLongValue, endpointID.unsignedShortValue);
}
}
}
if (endpointIndex.count != endpointIndexCopy.count) {
BOOL success;
if (endpointIndexCopy.count) {
success = [self _storeEndpointIndex:endpointIndexCopy forNodeID:nodeID];
} else {
[nodeIndexCopy removeObject:nodeID];
success = [self _deleteEndpointIndexForNodeID:nodeID];
}
if (!success) {
storeFailures++;
MTR_LOG_ERROR("Store failed in _pruneEmptyStoredClusterDataBranches for endpointIndex (%lu) @ node 0x%016llX", static_cast<unsigned long>(endpointIndexCopy.count), nodeID.unsignedLongLongValue);
}
}
}
if (nodeIndex.count != nodeIndexCopy.count) {
BOOL success;
if (nodeIndexCopy.count) {
success = [self _storeNodeIndex:nodeIndexCopy];
} else {
success = [self _deleteNodeIndex];
}
if (!success) {
storeFailures++;
MTR_LOG_ERROR("Store failed in _pruneEmptyStoredClusterDataBranches for nodeIndex (%lu)", static_cast<unsigned long>(nodeIndexCopy.count));
}
}
if (storeFailures) {
MTR_LOG_ERROR("Store failed in _pruneEmptyStoredClusterDataBranches: failure count %lu", static_cast<unsigned long>(storeFailures));
}
}
- (void)_clearStoredClusterDataForNodeID:(NSNumber *)nodeID
{
dispatch_assert_queue(_storageDelegateQueue);
NSUInteger endpointsClearAttempts = 0;
NSUInteger clusterDataClearAttempts = 0;
NSUInteger endpointsCleared = 0;
NSUInteger clusterDataCleared = 0;
// Fetch endpoint index
NSArray<NSNumber *> * endpointIndex = [self _fetchEndpointIndexForNodeID:nodeID];
endpointsClearAttempts += endpointIndex.count;
for (NSNumber * endpointID in endpointIndex) {
// Fetch cluster index
NSArray<NSNumber *> * clusterIndex = [self _fetchClusterIndexForNodeID:nodeID endpointID:endpointID];
clusterDataClearAttempts += clusterIndex.count; // Assuming every cluster has cluster data
for (NSNumber * clusterID in clusterIndex) {
BOOL success = [self _deleteClusterDataForNodeID:nodeID endpointID:endpointID clusterID:clusterID];
if (!success) {
MTR_LOG_ERROR("Delete failed for clusterData @ node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue);
} else {
clusterDataCleared++;
}
}
BOOL success = [self _deleteClusterIndexForNodeID:nodeID endpointID:endpointID];
if (!success) {
MTR_LOG_ERROR("Delete failed for clusterIndex @ node 0x%016llX endpoint %u", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue);
} else {
endpointsCleared++;
}
}
BOOL success = [self _deleteEndpointIndexForNodeID:nodeID];
if (!success) {
MTR_LOG_ERROR("Delete failed for endpointIndex @ node 0x%016llX", nodeID.unsignedLongLongValue);
}
MTR_LOG("clearStoredClusterDataForNodeID: deleted endpoints %lu/%lu clusters %lu/%lu", static_cast<unsigned long>(endpointsCleared), static_cast<unsigned long>(endpointsClearAttempts), static_cast<unsigned long>(clusterDataCleared), static_cast<unsigned long>(clusterDataClearAttempts));
}
- (void)clearStoredClusterDataForNodeID:(NSNumber *)nodeID
{
dispatch_async(_storageDelegateQueue, ^{
[self _clearStoredClusterDataForNodeID:nodeID];
NSArray<NSNumber *> * nodeIndex = [self _fetchNodeIndex];
NSMutableArray<NSNumber *> * nodeIndexCopy = [nodeIndex mutableCopy];
[nodeIndexCopy removeObject:nodeID];
if (nodeIndex.count != nodeIndexCopy.count) {
BOOL success;
if (nodeIndexCopy.count) {
success = [self _storeNodeIndex:nodeIndexCopy];
} else {
success = [self _deleteNodeIndex];
}
if (!success) {
MTR_LOG_ERROR("Store failed in clearStoredAttributesForNodeID for nodeIndex (%lu)", static_cast<unsigned long>(nodeIndexCopy.count));
}
}
});
}
- (void)clearStoredClusterDataForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID
{
dispatch_async(_storageDelegateQueue, ^{
NSArray<NSNumber *> * clusterIndex = [self _fetchClusterIndexForNodeID:nodeID endpointID:endpointID];
NSMutableArray<NSNumber *> * clusterIndexCopy = [clusterIndex mutableCopy];
[clusterIndexCopy removeObject:clusterID];
BOOL success;
if (clusterIndexCopy.count != clusterIndex.count) {
success = [self _storeClusterIndex:clusterIndexCopy forNodeID:nodeID endpointID:endpointID];
if (!success) {
MTR_LOG_ERROR("clearStoredClusterDataForNodeID: _storeClusterIndex failed for node 0x%016llX endpoint %u", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue);
}
}
success = [self _deleteClusterDataForNodeID:nodeID endpointID:endpointID clusterID:clusterID];
if (!success) {
MTR_LOG_ERROR("clearStoredClusterDataForNodeID: _deleteClusterDataForNodeID failed for node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue);
return;
}
MTR_LOG("clearStoredClusterDataForNodeID: Deleted endpoint %u cluster 0x%08lX for node 0x%016llX successfully", endpointID.unsignedShortValue, clusterID.unsignedLongValue, nodeID.unsignedLongLongValue);
});
}
- (void)clearStoredClusterDataForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID
{
dispatch_async(_storageDelegateQueue, ^{
BOOL success = [self _removeEndpointFromEndpointIndex:endpointID forNodeID:nodeID];
if (!success) {
MTR_LOG_ERROR("removeEndpointFromEndpointIndex for endpointID %u failed for node 0x%016llX", endpointID.unsignedShortValue, nodeID.unsignedLongLongValue);
}
NSArray<NSNumber *> * clusterIndex = [self _fetchClusterIndexForNodeID:nodeID endpointID:endpointID];
for (NSNumber * cluster in clusterIndex) {
success = [self _deleteClusterDataForNodeID:nodeID endpointID:endpointID clusterID:cluster];
if (!success) {
MTR_LOG_ERROR("Delete failed for clusterData for node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, cluster.unsignedLongValue);
}
}
success = [self _deleteClusterIndexForNodeID:nodeID endpointID:endpointID];
if (!success) {
MTR_LOG_ERROR("Delete failed for clusterIndex for node 0x%016llX endpoint %u", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue);
}
MTR_LOG("clearStoredClusterDataForNodeID: Deleted endpoint %u for node 0x%016llX successfully", endpointID.unsignedShortValue, nodeID.unsignedLongLongValue);
});
}
- (void)removeAttributes:(NSSet<NSNumber *> *)attributes fromCluster:(MTRClusterPath *)path forNodeID:(NSNumber *)nodeID
{
MTRDeviceClusterData * clusterData = [self getStoredClusterDataForNodeID:nodeID endpointID:path.endpoint clusterID:path.cluster];
if (clusterData == nil) {
return;
}
for (NSNumber * attribute in attributes) {
[clusterData removeValueForAttribute:attribute];
}
dispatch_async(_storageDelegateQueue, ^{
BOOL success = [self _storeClusterData:clusterData forNodeID:nodeID endpointID:path.endpoint clusterID:path.cluster];
if (!success) {
MTR_LOG_ERROR("removeAttributes: _storeClusterData failed for node 0x%016llX endpoint %u", nodeID.unsignedLongLongValue, path.endpoint.unsignedShortValue);
}
MTR_LOG("removeAttributes: Deleted attributes %@ from endpoint %u cluster 0x%08lX for node 0x%016llX successfully", attributes, path.endpoint.unsignedShortValue, path.cluster.unsignedLongValue, nodeID.unsignedLongLongValue);
});
}
- (void)clearAllStoredClusterData
{
dispatch_async(_storageDelegateQueue, ^{
// Fetch node index
NSArray<NSNumber *> * nodeIndex = [self _fetchNodeIndex];
for (NSNumber * nodeID in nodeIndex) {
[self _clearStoredClusterDataForNodeID:nodeID];
}
BOOL success = [self _deleteNodeIndex];
if (!success) {
MTR_LOG_ERROR("Delete failed for nodeIndex");
}
});
}
- (nullable NSDictionary<MTRClusterPath *, MTRDeviceClusterData *> *)getStoredClusterDataForNodeID:(NSNumber *)nodeID
{
if (!nodeID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return nil;
}
__block NSMutableDictionary<MTRClusterPath *, MTRDeviceClusterData *> * clusterDataToReturn = nil;
dispatch_sync(_storageDelegateQueue, ^{
// Fetch node index
NSArray<NSNumber *> * nodeIndex = [self _fetchNodeIndex];
#if ATTRIBUTE_CACHE_VERBOSE_LOGGING
MTR_LOG("Fetch got %lu values for nodeIndex", static_cast<unsigned long>(nodeIndex.count));
#endif
if (![nodeIndex containsObject:nodeID]) {
// Sanity check and delete if nodeID exists in index
NSArray<NSNumber *> * endpointIndex = [self _fetchEndpointIndexForNodeID:nodeID];
if (endpointIndex) {
MTR_LOG_ERROR("Persistent attribute cache contains orphaned entry for nodeID %@ - deleting", nodeID);
// _clearStoredClusterDataForNodeID because we are are already
// on the _storageDelegateQueue and do not need to modify the
// node index in this case.
[self _clearStoredClusterDataForNodeID:nodeID];
}
MTR_LOG("Fetch got no value for endpointIndex @ node 0x%016llX", nodeID.unsignedLongLongValue);
clusterDataToReturn = nil;
return;
}
// Fetch endpoint index
NSArray<NSNumber *> * endpointIndex = [self _fetchEndpointIndexForNodeID:nodeID];
#if ATTRIBUTE_CACHE_VERBOSE_LOGGING
MTR_LOG("Fetch got %lu values for endpointIndex @ node 0x%016llX", static_cast<unsigned long>(endpointIndex.count), nodeID.unsignedLongLongValue);
#endif
for (NSNumber * endpointID in endpointIndex) {
// Fetch cluster index
NSArray<NSNumber *> * clusterIndex = [self _fetchClusterIndexForNodeID:nodeID endpointID:endpointID];
#if ATTRIBUTE_CACHE_VERBOSE_LOGGING
MTR_LOG("Fetch got %lu values for clusterIndex @ node 0x%016llX %u", static_cast<unsigned long>(clusterIndex.count), nodeID.unsignedLongLongValue, endpointID.unsignedShortValue);
#endif
for (NSNumber * clusterID in clusterIndex) {
// Fetch cluster data
MTRDeviceClusterData * clusterData = [self _fetchClusterDataForNodeID:nodeID endpointID:endpointID clusterID:clusterID];
if (!clusterData) {
MTR_LOG("Fetch got no value for clusterData @ node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue);
continue;
}
#if ATTRIBUTE_CACHE_VERBOSE_LOGGING
MTR_LOG("Fetch got clusterData @ node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, endpointID.unsignedShortValue, clusterID.unsignedLongValue);
#endif
MTRClusterPath * path = [MTRClusterPath clusterPathWithEndpointID:endpointID clusterID:clusterID];
if (!clusterDataToReturn) {
clusterDataToReturn = [NSMutableDictionary dictionary];
}
clusterDataToReturn[path] = clusterData;
}
}
});
return clusterDataToReturn;
}
- (nullable MTRDeviceClusterData *)getStoredClusterDataForNodeID:(NSNumber *)nodeID endpointID:(NSNumber *)endpointID clusterID:(NSNumber *)clusterID
{
// Don't bother checking our indices here, since this will only be called
// when the consumer knows that we're supposed to have data for this cluster
// path.
__block MTRDeviceClusterData * clusterDataToReturn = nil;
dispatch_sync(_storageDelegateQueue, ^{
clusterDataToReturn = [self _fetchClusterDataForNodeID:nodeID endpointID:endpointID clusterID:clusterID];
});
return clusterDataToReturn;
}
// Utility for constructing dictionary of nodeID to cluster data from dictionary of storage keys
- (nullable NSDictionary<NSNumber *, NSDictionary<MTRClusterPath *, MTRDeviceClusterData *> *> *)_getClusterDataFromSecureLocalValues:(NSDictionary<NSString *, id> *)secureLocalValues
{
NSMutableDictionary<NSNumber *, NSDictionary<MTRClusterPath *, MTRDeviceClusterData *> *> * clusterDataByNodeToReturn = nil;
if (![secureLocalValues isKindOfClass:[NSDictionary class]]) {
return nil;
}
// Fetch node index
NSArray<NSNumber *> * nodeIndex = secureLocalValues[sAttributeCacheNodeIndexKey];
if (![nodeIndex isKindOfClass:[NSArray class]]) {
return nil;
}
for (NSNumber * nodeID in nodeIndex) {
if (![nodeID isKindOfClass:[NSNumber class]]) {
continue;
}
NSMutableDictionary<MTRClusterPath *, MTRDeviceClusterData *> * clusterDataForNode = nil;
NSArray<NSNumber *> * endpointIndex = secureLocalValues[[self _endpointIndexKeyForNodeID:nodeID]];
if (![endpointIndex isKindOfClass:[NSArray class]]) {
continue;
}
for (NSNumber * endpointID in endpointIndex) {
if (![endpointID isKindOfClass:[NSNumber class]]) {
continue;
}
NSArray<NSNumber *> * clusterIndex = secureLocalValues[[self _clusterIndexKeyForNodeID:nodeID endpointID:endpointID]];
if (![clusterIndex isKindOfClass:[NSArray class]]) {
continue;
}
for (NSNumber * clusterID in clusterIndex) {
if (![clusterID isKindOfClass:[NSNumber class]]) {
continue;
}
MTRDeviceClusterData * clusterData = secureLocalValues[[self _clusterDataKeyForNodeID:nodeID endpointID:endpointID clusterID:clusterID]];
if (!clusterData) {
continue;
}
if (![clusterData isKindOfClass:[MTRDeviceClusterData class]]) {
continue;
}
MTRClusterPath * clusterPath = [MTRClusterPath clusterPathWithEndpointID:endpointID clusterID:clusterID];
if (!clusterDataForNode) {
clusterDataForNode = [NSMutableDictionary dictionary];
}
clusterDataForNode[clusterPath] = clusterData;
}
}
if (clusterDataForNode.count) {
if (!clusterDataByNodeToReturn) {
clusterDataByNodeToReturn = [NSMutableDictionary dictionary];
}
clusterDataByNodeToReturn[nodeID] = clusterDataForNode;
}
}
return clusterDataByNodeToReturn;
}
- (void)storeClusterData:(NSDictionary<MTRClusterPath *, MTRDeviceClusterData *> *)clusterData forNodeID:(NSNumber *)nodeID
{
if (!nodeID) {
MTR_LOG_ERROR("%s: unexpected nil input", __func__);
return;
}
if (!clusterData.count) {
MTR_LOG_ERROR("%s: nothing to store", __func__);
return;
}
dispatch_async(_storageDelegateQueue, ^{
NSUInteger storeFailures = 0;
NSMutableDictionary<NSString *, id<NSSecureCoding>> * bulkValuesToStore = nil;
if ([self->_storageDelegate respondsToSelector:@selector(controller:storeValues:securityLevel:sharingType:)]) {
bulkValuesToStore = [NSMutableDictionary dictionary];
}
// A map of endpoint => list of clusters modified for that endpoint so cluster indexes can be updated later
NSMutableDictionary<NSNumber *, NSMutableSet<NSNumber *> *> * clustersModified = [NSMutableDictionary dictionary];
// Write cluster specific data first
for (MTRClusterPath * path in clusterData) {
MTRDeviceClusterData * data = clusterData[path];
#if ATTRIBUTE_CACHE_VERBOSE_LOGGING
MTR_LOG("Attempt to store clusterData @ node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, path.endpoint.unsignedShortValue, path.cluster.unsignedLongValue);
#endif
if (bulkValuesToStore) {
bulkValuesToStore[[self _clusterDataKeyForNodeID:nodeID endpointID:path.endpoint clusterID:path.cluster]] = data;
} else {
// Store cluster data
BOOL storeFailed = ![self _storeClusterData:data forNodeID:nodeID endpointID:path.endpoint clusterID:path.cluster];
if (storeFailed) {
storeFailures++;
MTR_LOG_ERROR("Store failed for clusterData @ node 0x%016llX endpoint %u cluster 0x%08lX", nodeID.unsignedLongLongValue, path.endpoint.unsignedShortValue, path.cluster.unsignedLongValue);
}
}
// Note the cluster as modified for the endpoint