forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExamplePersistentStorage.cpp
323 lines (265 loc) · 9.12 KB
/
ExamplePersistentStorage.cpp
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
/*
* Copyright (c) 2020-2022 Project CHIP Authors
* All rights reserved.
*
* 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 "ExamplePersistentStorage.h"
#include <lib/core/CHIPEncoding.h>
#include <lib/support/IniEscaping.h>
#include <fstream>
#include <map>
#include <memory>
#include <string>
using String = std::basic_string<char>;
using Section = std::map<String, String>;
using Sections = std::map<String, Section>;
using namespace ::chip;
using namespace ::chip::Controller;
using namespace ::chip::IniEscaping;
using namespace ::chip::Logging;
constexpr char kDefaultSectionName[] = "Default";
constexpr char kPortKey[] = "ListenPort";
constexpr char kLoggingKey[] = "LoggingLevel";
constexpr char kLocalNodeIdKey[] = "LocalNodeId";
constexpr char kCommissionerCATsKey[] = "CommissionerCATs";
constexpr LogCategory kDefaultLoggingLevel = kLogCategory_Automation;
const char * GetUsedDirectory(const char * directory)
{
const char * dir = directory;
if (dir == nullptr)
{
dir = getenv("TMPDIR");
}
if (dir == nullptr)
{
dir = "/tmp";
}
return dir;
}
std::string GetFilename(const char * directory, const char * name)
{
const char * dir = GetUsedDirectory(directory);
if (name == nullptr)
{
return std::string(dir) + "/chip_tool_config.ini";
}
return std::string(dir) + "/chip_tool_config." + std::string(name) + ".ini";
}
CHIP_ERROR PersistentStorage::Init(const char * name, const char * directory)
{
CHIP_ERROR err = CHIP_NO_ERROR;
std::ifstream ifs;
ifs.open(GetFilename(directory, name), std::ifstream::in);
if (!ifs.good())
{
CommitConfig(directory, name);
ifs.open(GetFilename(directory, name), std::ifstream::in);
}
VerifyOrExit(ifs.is_open(), err = CHIP_ERROR_OPEN_FAILED);
mName = name;
mDirectory = directory;
mConfig.clear();
mConfig.parse(ifs);
ifs.close();
// To audit the contents at init, uncomment the following:
#if 0
DumpKeys();
#endif
exit:
return err;
}
CHIP_ERROR PersistentStorage::SyncGetKeyValue(const char * key, void * value, uint16_t & size)
{
std::string iniValue;
ReturnErrorCodeIf(((value == nullptr) && (size != 0)), CHIP_ERROR_INVALID_ARGUMENT);
auto section = mConfig.sections[kDefaultSectionName];
ReturnErrorCodeIf(!SyncDoesKeyExist(key), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
std::string escapedKey = EscapeKey(key);
ReturnErrorCodeIf(!inipp::extract(section[escapedKey], iniValue), CHIP_ERROR_INVALID_ARGUMENT);
iniValue = Base64ToString(iniValue);
uint16_t dataSize = static_cast<uint16_t>(iniValue.size());
ReturnErrorCodeIf(size == 0 && dataSize == 0, CHIP_NO_ERROR);
ReturnErrorCodeIf(value == nullptr, CHIP_ERROR_BUFFER_TOO_SMALL);
uint16_t sizeToCopy = std::min(size, dataSize);
memcpy(value, iniValue.data(), sizeToCopy);
size = sizeToCopy;
return size < dataSize ? CHIP_ERROR_BUFFER_TOO_SMALL : CHIP_NO_ERROR;
}
CHIP_ERROR PersistentStorage::SyncSetKeyValue(const char * key, const void * value, uint16_t size)
{
ReturnErrorCodeIf((value == nullptr) && (size != 0), CHIP_ERROR_INVALID_ARGUMENT);
auto section = mConfig.sections[kDefaultSectionName];
std::string escapedKey = EscapeKey(key);
if (value == nullptr)
{
section[escapedKey] = "";
}
else
{
section[escapedKey] = StringToBase64(std::string(static_cast<const char *>(value), size));
}
mConfig.sections[kDefaultSectionName] = section;
return CommitConfig(mDirectory, mName);
}
CHIP_ERROR PersistentStorage::SyncDeleteKeyValue(const char * key)
{
auto section = mConfig.sections[kDefaultSectionName];
ReturnErrorCodeIf(!SyncDoesKeyExist(key), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND);
std::string escapedKey = EscapeKey(key);
section.erase(escapedKey);
mConfig.sections[kDefaultSectionName] = section;
return CommitConfig(mDirectory, mName);
}
bool PersistentStorage::SyncDoesKeyExist(const char * key)
{
std::string escapedKey = EscapeKey(key);
auto section = mConfig.sections[kDefaultSectionName];
auto it = section.find(escapedKey);
return (it != section.end());
}
void PersistentStorage::DumpKeys() const
{
#if CHIP_PROGRESS_LOGGING
for (const auto & section : mConfig.sections)
{
const std::string & sectionName = section.first;
const auto & sectionContent = section.second;
ChipLogProgress(chipTool, "[%s]", sectionName.c_str());
for (const auto & entry : sectionContent)
{
const std::string & keyName = entry.first;
ChipLogProgress(chipTool, " => %s", UnescapeKey(keyName).c_str());
}
}
#endif // CHIP_PROGRESS_LOGGING
}
CHIP_ERROR PersistentStorage::SyncClearAll()
{
ChipLogProgress(chipTool, "Clearing %s storage", kDefaultSectionName);
auto section = mConfig.sections[kDefaultSectionName];
section.clear();
mConfig.sections[kDefaultSectionName] = section;
return CommitConfig(mDirectory, mName);
}
const char * PersistentStorage::GetDirectory() const
{
return GetUsedDirectory(mDirectory);
}
CHIP_ERROR PersistentStorage::CommitConfig(const char * directory, const char * name)
{
CHIP_ERROR err = CHIP_NO_ERROR;
std::ofstream ofs;
std::string tmpPath = GetFilename(directory, name) + ".tmp";
ofs.open(tmpPath, std::ofstream::out | std::ofstream::trunc);
VerifyOrExit(ofs.good(), err = CHIP_ERROR_WRITE_FAILED);
mConfig.generate(ofs);
ofs.close();
VerifyOrExit(ofs.good(), err = CHIP_ERROR_WRITE_FAILED);
VerifyOrExit(rename(tmpPath.c_str(), GetFilename(directory, name).c_str()) == 0, err = CHIP_ERROR_WRITE_FAILED);
exit:
return err;
}
uint16_t PersistentStorage::GetListenPort()
{
CHIP_ERROR err = CHIP_NO_ERROR;
// By default chip-tool listens on an ephemeral port.
uint16_t chipListenPort = 0;
char value[6];
uint16_t size = static_cast<uint16_t>(sizeof(value));
err = SyncGetKeyValue(kPortKey, value, size);
if (CHIP_NO_ERROR == err)
{
uint16_t tmpValue;
std::stringstream ss(value);
ss >> tmpValue;
if (!ss.fail() && ss.eof())
{
chipListenPort = tmpValue;
}
}
return chipListenPort;
}
LogCategory PersistentStorage::GetLoggingLevel()
{
CHIP_ERROR err = CHIP_NO_ERROR;
LogCategory chipLogLevel = kDefaultLoggingLevel;
char value[9];
uint16_t size = static_cast<uint16_t>(sizeof(value));
err = SyncGetKeyValue(kLoggingKey, value, size);
if (CHIP_NO_ERROR == err)
{
if (strcasecmp(value, "none") == 0)
{
chipLogLevel = kLogCategory_None;
}
else if (strcasecmp(value, "error") == 0)
{
chipLogLevel = kLogCategory_Error;
}
else if (strcasecmp(value, "progress") == 0)
{
chipLogLevel = kLogCategory_Progress;
}
else if (strcasecmp(value, "detail") == 0)
{
chipLogLevel = kLogCategory_Detail;
}
else if (strcasecmp(value, "automation") == 0)
{
chipLogLevel = kLogCategory_Automation;
}
}
return chipLogLevel;
}
NodeId PersistentStorage::GetLocalNodeId()
{
CHIP_ERROR err = CHIP_NO_ERROR;
uint64_t nodeId;
uint16_t size = static_cast<uint16_t>(sizeof(nodeId));
err = SyncGetKeyValue(kLocalNodeIdKey, &nodeId, size);
if (err == CHIP_NO_ERROR)
{
return static_cast<NodeId>(Encoding::LittleEndian::HostSwap64(nodeId));
}
return kTestControllerNodeId;
}
CHIP_ERROR PersistentStorage::SetLocalNodeId(NodeId value)
{
uint64_t nodeId = Encoding::LittleEndian::HostSwap64(value);
return SyncSetKeyValue(kLocalNodeIdKey, &nodeId, sizeof(nodeId));
}
CATValues PersistentStorage::GetCommissionerCATs()
{
CHIP_ERROR err = CHIP_NO_ERROR;
CATValues cats;
chip::CATValues::Serialized serializedCATs;
uint16_t size = chip::CATValues::kSerializedLength;
err = SyncGetKeyValue(kCommissionerCATsKey, serializedCATs, size);
if (err == CHIP_NO_ERROR && size == chip::CATValues::kSerializedLength)
{
err = cats.Deserialize(serializedCATs);
if (err == CHIP_NO_ERROR)
{
return cats;
}
}
return chip::kUndefinedCATs;
}
CHIP_ERROR PersistentStorage::SetCommissionerCATs(const CATValues & cats)
{
chip::CATValues::Serialized serializedCATs;
ReturnErrorOnFailure(cats.Serialize(serializedCATs));
return SyncSetKeyValue(kCommissionerCATsKey, serializedCATs, sizeof(serializedCATs));
}