forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMTRDemuxingStorage.mm
429 lines (340 loc) · 13.8 KB
/
MTRDemuxingStorage.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
/**
* 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.
*/
#import "MTRDemuxingStorage.h"
#import "MTRDeviceControllerFactory_Internal.h"
#import "MTRDeviceController_Internal.h"
#import "MTRLogging_Internal.h"
#include <lib/support/CodeUtils.h>
#include <lib/support/SafeInt.h>
#include <platform/LockTracker.h>
using namespace chip;
static bool IsGlobalKey(NSString * key) { return [key hasPrefix:@"g/"]; }
/**
* Checks for a key that is scoped to a specific fabric index.
*/
static bool IsIndexSpecificKey(NSString * key) { return [key hasPrefix:@"f/"]; }
/**
* Extracts the fabric index from an index-specific key. Fails if the key
* is not index-specific or if a numeric FabricIndex could not be extracted
* from it.
*/
static CHIP_ERROR ExtractIndexFromKey(NSString * key, FabricIndex * index)
{
if (!IsIndexSpecificKey(key)) {
return CHIP_ERROR_INVALID_ARGUMENT;
}
auto * components = [key componentsSeparatedByString:@"/"];
if (components.count < 3) {
// Unexpected "f/something" without any actual data.
return CHIP_ERROR_INVALID_ARGUMENT;
}
auto * indexString = components[1];
auto * scanner = [NSScanner scannerWithString:indexString];
auto * charset = [NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefABCDEF"];
charset = [charset invertedSet];
if ([scanner scanCharactersFromSet:charset intoString:nil] == YES) {
// Leading non-hex chars.
return CHIP_ERROR_INVALID_ARGUMENT;
}
unsigned int value;
if ([scanner scanHexInt:&value] == NO) {
return CHIP_ERROR_INVALID_ARGUMENT;
}
if (scanner.atEnd == NO) {
// Trailing garbage chars.
return CHIP_ERROR_INVALID_ARGUMENT;
}
if (!CanCastTo<FabricIndex>(value)) {
return CHIP_ERROR_INVALID_ARGUMENT;
}
*index = static_cast<FabricIndex>(value);
return CHIP_NO_ERROR;
}
/**
* Extracts the "index-specific" part of an index-specific key (i.e. the
* part after "f/index/").
*/
static CHIP_ERROR ExtractIndexSpecificKey(NSString * key, NSString * __autoreleasing * extractedKey)
{
if (!IsIndexSpecificKey(key)) {
return CHIP_ERROR_INVALID_ARGUMENT;
}
auto * components = [key componentsSeparatedByString:@"/"];
if (components.count < 3) {
// Unexpected "f/something" without any actual data.
return CHIP_ERROR_INVALID_ARGUMENT;
}
components = [components subarrayWithRange:NSMakeRange(2, components.count - 2)];
*extractedKey = [components componentsJoinedByString:@"/"];
return CHIP_NO_ERROR;
}
/**
* Method to test whether a global key should be stored in memory only, as
* opposed to being passed on to the actual storage related to controllers.
*/
static bool IsMemoryOnlyGlobalKey(NSString * key)
{
if ([key isEqualToString:@"g/fidx"]) {
// Fabric index list only needs to be stored in-memory, not persisted,
// because we do not tie controllers to specific fabric indices.
return true;
}
if ([key isEqualToString:@"g/fs/c"] || [key isEqualToString:@"g/fs/n"]) {
// Just store the fail-safe markers in memory as well. We could
// plausibly not store them at all, since we never actually need to
// clean up anything by fabric index, but this is safer in case
// consumers try to read back right after writing.
return true;
}
if ([key isEqualToString:@"g/lkgt"]) {
// Store Last Known Good Time in memory only. We never need this in
// general, because we can always provide the wall-clock time.
return true;
}
// We do not expect to see the "g/sri" or "g/s/*" keys for session
// resumption, because we implement SessionResumptionStorage ourselves.
// For now, put group global counters in memory.
// TODO: we should inject a group counter manager that makes these counters
// per-controller, not globally handled via storage.
// See https://github.com/project-chip/connectedhomeip/issues/28510
if ([key isEqualToString:@"g/gdc"] || [key isEqualToString:@"g/gcc"]) {
return true;
}
// We do not expect to see "g/userlbl/*" User Label keys.
// We do not expect to see the "g/gfl" key for endpoint-to-group
// associations.
// We do not expect to see the "g/a/*" keys for attribute values.
// We do not expect to see the "g/sa/*" keys for attribute values.
// We do not expect to see the "g/bt" and "g/bt/*" keys for the binding
// table.
// We do not expect to see the "g/o/*" OTA Requestor keys.
// We do not expect to see the "g/im/ec" event number counter key.
// We do not expect to see the "g/su/*" and "g/sum" keys for server-side
// subscription resumption storage.
// We do not expect to see the "g/scc/*" scenes keys.
// We do not expect to see the "g/ts/tts", "g/ts/dntp", "g/ts/tz",
// "g/ts/dsto" Time Synchronization keys.
// We do not expect to see the "g/icd/cic" key; that's only used for an ICD
// that sends check-in messages.
// We do not expect to see the "g/icdfl" key; that's only used by
// DefaultICDClientStorage, which Matter.framework does not use.
// We do not expect to see the "g/tnd/*" Thread Network Directory keys.
return false;
}
/**
* Method to test whether an index-specific key should be stored in memory only, as
* opposed to being passed on to the actual storage related to controllers.
* The key string will have the "f/index/" bit already stripped off the
* front of the key.
*/
static bool IsMemoryOnlyIndexSpecificKey(NSString * key)
{
// Store all the fabric table bits in memory only. This is done because the
// fabric table expects none of these things to be stored in the case of a
// "new fabric addition", which is what we always do when using
// per-controller storage.
//
// TODO: Figure out which, if any, of these things we should also store for
// later recall when starting a controller with storage we have used before.
//
// For future reference:
//
// n == NOC
// i == ICAC
// r == RCAC
// m == Fabric metadata (TLV containing the vendor ID)
// o == operational key, only written if internally generated.
if ([key isEqualToString:@"n"] || [key isEqualToString:@"i"] || [key isEqualToString:@"r"] || [key isEqualToString:@"m"] ||
[key isEqualToString:@"o"]) {
return true;
}
// We do not expect to see the "s/*" keys for session resumption, because we
// implement SessionResumptionStorage ourselves.
// We do not expect to see the "ac/*" keys for ACL entries.
// We do not expect to see the "g" or "g/*" keys for which endpoints are in which
// group.
// For now, just store group keysets and group keys in memory.
// TODO: We want to start persisting these, per-controller, if we're going
// to support group keys. Or inject a GroupDataProvider of our own instead
// of using Credentials::GroupDataProviderImp and then
// not be tied to whatever storage format that uses.
// https://github.com/project-chip/connectedhomeip/issues/28511
if ([key hasPrefix:@"gk/"] || [key hasPrefix:@"k/"]) {
return true;
}
// We do not expect to see the "icd/*" keys for the ICD Management table.
// We do not expect to see the "e/*" scenes keys.
// We do not epect to see the "icdc" or "icdk" keys, since those are only
// used by DefaultICDClientStorage, which Matter.framework does not use.
return false;
}
/**
* Method to convert an index-specific key into a fully qualified key.
*/
static NSString * FullyQualifiedKey(FabricIndex index, NSString * key)
{
return [NSString stringWithFormat:@"f/%x/%s", index, key.UTF8String];
}
MTRDemuxingStorage::MTRDemuxingStorage(MTRDeviceControllerFactory * factory)
: mFactory(factory)
{
mInMemoryStore = [[NSMutableDictionary alloc] init];
}
CHIP_ERROR MTRDemuxingStorage::SyncGetKeyValue(const char * key, void * buffer, uint16_t & size)
{
assertChipStackLockedByCurrentThread();
if (buffer == nullptr && size != 0) {
return CHIP_ERROR_INVALID_ARGUMENT;
}
NSString * keyString = [NSString stringWithUTF8String:key];
#if LOG_DEBUG_PERSISTENT_STORAGE_DELEGATE
MTR_LOG_DEBUG("MTRDemuxingStorage Sync Get Value for Key: %@", keyString);
#endif
NSData * value;
if (IsGlobalKey(keyString)) {
value = GetGlobalValue(keyString);
} else if (IsIndexSpecificKey(keyString)) {
FabricIndex index;
ReturnErrorOnFailure(ExtractIndexFromKey(keyString, &index));
ReturnErrorOnFailure(ExtractIndexSpecificKey(keyString, &keyString));
value = GetIndexSpecificValue(index, keyString);
} else {
return CHIP_ERROR_INVALID_ARGUMENT;
}
if (value == nil) {
return CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND;
}
if (value.length > UINT16_MAX) {
return CHIP_ERROR_PERSISTED_STORAGE_FAILED;
}
uint16_t valueSize = static_cast<uint16_t>(value.length);
if (valueSize > size) {
return CHIP_ERROR_BUFFER_TOO_SMALL;
}
size = valueSize;
if (size != 0) {
// buffer is known to be non-null here.
memcpy(buffer, value.bytes, size);
}
return CHIP_NO_ERROR;
}
CHIP_ERROR MTRDemuxingStorage::SyncSetKeyValue(const char * key, const void * value, uint16_t size)
{
if (value == nullptr && size != 0) {
return CHIP_ERROR_INVALID_ARGUMENT;
}
NSString * keyString = [NSString stringWithUTF8String:key];
NSData * valueData = (value == nullptr) ? [NSData data] : [NSData dataWithBytes:value length:size];
#if LOG_DEBUG_PERSISTENT_STORAGE_DELEGATE
MTR_LOG_DEBUG("MTRDemuxingStorage Set Key %@", keyString);
#endif
if (IsGlobalKey(keyString)) {
return SetGlobalValue(keyString, valueData);
}
if (IsIndexSpecificKey(keyString)) {
FabricIndex index;
ReturnErrorOnFailure(ExtractIndexFromKey(keyString, &index));
ReturnErrorOnFailure(ExtractIndexSpecificKey(keyString, &keyString));
return SetIndexSpecificValue(index, keyString, valueData);
}
return CHIP_ERROR_INVALID_ARGUMENT;
}
CHIP_ERROR MTRDemuxingStorage::SyncDeleteKeyValue(const char * key)
{
NSString * keyString = [NSString stringWithUTF8String:key];
#if LOG_DEBUG_PERSISTENT_STORAGE_DELEGATE
MTR_LOG_DEBUG("MTRDemuxingStorage Delete Key: %@", keyString);
#endif
if (IsGlobalKey(keyString)) {
return DeleteGlobalValue(keyString);
}
if (IsIndexSpecificKey(keyString)) {
FabricIndex index;
ReturnErrorOnFailure(ExtractIndexFromKey(keyString, &index));
ReturnErrorOnFailure(ExtractIndexSpecificKey(keyString, &keyString));
return DeleteIndexSpecificValue(index, keyString);
}
return CHIP_ERROR_INVALID_ARGUMENT;
}
NSData * _Nullable MTRDemuxingStorage::GetGlobalValue(NSString * key)
{
if (IsMemoryOnlyGlobalKey(key)) {
return GetInMemoryValue(key);
}
MTR_LOG_ERROR("MTRDemuxingStorage reading unknown global key: %@", key);
return nil;
}
NSData * _Nullable MTRDemuxingStorage::GetIndexSpecificValue(FabricIndex index, NSString * key)
{
if (IsMemoryOnlyIndexSpecificKey(key)) {
return GetInMemoryValue(FullyQualifiedKey(index, key));
}
return nil;
}
CHIP_ERROR MTRDemuxingStorage::SetGlobalValue(NSString * key, NSData * data)
{
if (IsMemoryOnlyGlobalKey(key)) {
// Fabric index list only needs to be stored in-memory, not persisted,
// because we do not tie controllers to specific fabric indices.
return SetInMemoryValue(key, data);
}
MTR_LOG_ERROR("MTRDemuxingStorage setting unknown global key: %@", key);
return CHIP_ERROR_PERSISTED_STORAGE_FAILED;
}
CHIP_ERROR MTRDemuxingStorage::SetIndexSpecificValue(FabricIndex index, NSString * key, NSData * data)
{
if ([key isEqualToString:@"n"]) {
// Index-scoped "n" is NOC.
auto * controller = [mFactory runningControllerForFabricIndex:index];
if (controller == nil) {
return CHIP_ERROR_PERSISTED_STORAGE_FAILED;
}
ReturnErrorOnFailure([controller.controllerDataStore storeLastLocallyUsedNOC:data]);
}
if (IsMemoryOnlyIndexSpecificKey(key)) {
return SetInMemoryValue(FullyQualifiedKey(index, key), data);
}
return CHIP_ERROR_PERSISTED_STORAGE_FAILED;
}
CHIP_ERROR MTRDemuxingStorage::DeleteGlobalValue(NSString * key)
{
if (IsMemoryOnlyGlobalKey(key)) {
return DeleteInMemoryValue(key);
}
MTR_LOG_ERROR("MTRDemuxingStorage deleting unknown global key: %@", key);
return CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND;
}
CHIP_ERROR MTRDemuxingStorage::DeleteIndexSpecificValue(FabricIndex index, NSString * key)
{
if (IsMemoryOnlyIndexSpecificKey(key)) {
return DeleteInMemoryValue(FullyQualifiedKey(index, key));
}
return CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND;
}
NSData * _Nullable MTRDemuxingStorage::GetInMemoryValue(NSString * key) { return mInMemoryStore[key]; }
CHIP_ERROR MTRDemuxingStorage::SetInMemoryValue(NSString * key, NSData * data)
{
mInMemoryStore[key] = data;
return CHIP_NO_ERROR;
}
CHIP_ERROR MTRDemuxingStorage::DeleteInMemoryValue(NSString * key)
{
BOOL present = (mInMemoryStore[key] != nil);
if (present) {
[mInMemoryStore removeObjectForKey:key];
}
return present ? CHIP_NO_ERROR : CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND;
}