-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathJsonToTlv.cpp
443 lines (390 loc) · 14.4 KB
/
JsonToTlv.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
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
/*
*
* 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 <stdint.h>
#include <algorithm>
#include <charconv>
#include <sstream>
#include <string>
#include <vector>
#include <json/json.h>
#include <lib/support/Base64.h>
#include <lib/support/SafeInt.h>
#include <lib/support/jsontlv/ElementTypes.h>
#include <lib/support/jsontlv/JsonToTlv.h>
namespace chip {
namespace {
// Not directly used: TLV encoding will not encode this number and
// will just encode "Implicit profile tag"
// This profile, but will be used for deciding what binary values to encode.
constexpr uint32_t kTemporaryImplicitProfileId = 0xFF01;
std::vector<std::string> SplitIntoFieldsBySeparator(const std::string & input, char separator)
{
std::vector<std::string> substrings;
std::stringstream ss(input);
std::string substring;
while (std::getline(ss, substring, separator))
{
substrings.push_back(std::move(substring));
}
return substrings;
}
CHIP_ERROR JsonTypeStrToTlvType(const char * elementType, ElementTypeContext & type)
{
if (strcmp(elementType, kElementTypeInt) == 0)
{
type.tlvType = TLV::kTLVType_SignedInteger;
}
else if (strcmp(elementType, kElementTypeUInt) == 0)
{
type.tlvType = TLV::kTLVType_UnsignedInteger;
}
else if (strcmp(elementType, kElementTypeBool) == 0)
{
type.tlvType = TLV::kTLVType_Boolean;
}
else if (strcmp(elementType, kElementTypeFloat) == 0)
{
type.tlvType = TLV::kTLVType_FloatingPointNumber;
type.isDouble = false;
}
else if (strcmp(elementType, kElementTypeDouble) == 0)
{
type.tlvType = TLV::kTLVType_FloatingPointNumber;
type.isDouble = true;
}
else if (strcmp(elementType, kElementTypeBytes) == 0)
{
type.tlvType = TLV::kTLVType_ByteString;
}
else if (strcmp(elementType, kElementTypeString) == 0)
{
type.tlvType = TLV::kTLVType_UTF8String;
}
else if (strcmp(elementType, kElementTypeNull) == 0)
{
type.tlvType = TLV::kTLVType_Null;
}
else if (strcmp(elementType, kElementTypeStruct) == 0)
{
type.tlvType = TLV::kTLVType_Structure;
}
else if (strncmp(elementType, kElementTypeArray, strlen(kElementTypeArray)) == 0)
{
type.tlvType = TLV::kTLVType_Array;
}
else
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
return CHIP_NO_ERROR;
}
struct ElementContext
{
std::string jsonName;
TLV::Tag tag = TLV::AnonymousTag();
ElementTypeContext type;
ElementTypeContext subType;
};
bool CompareByTag(const ElementContext & a, const ElementContext & b)
{
// If tags are of the same type compare by tag number
if (IsContextTag(a.tag) == IsContextTag(b.tag))
{
return TLV::TagNumFromTag(a.tag) < TLV::TagNumFromTag(b.tag);
}
// Otherwise, compare by tag type: context tags first followed by common profile tags
return IsContextTag(a.tag);
}
// The profileId parameter is used when encoding a tag for a TLV element to specify the profile that the tag belongs to.
// If the vendor ID is zero but the tag ID does not fit within an 8-bit value, the function uses Implicit Profile Tag.
// Here, the kTemporaryImplicitProfileId serves as a default value for cases where no explicit profile ID is provided by
// the caller. This allows for the encoding of tags that are not vendor-specific or context-specific but are instead
// associated with a temporary implicit profile ID (0xFF01).
CHIP_ERROR InternalConvertTlvTag(uint32_t tagNumber, TLV::Tag & tag, const uint32_t profileId = kTemporaryImplicitProfileId)
{
uint16_t vendor_id = static_cast<uint16_t>(tagNumber >> 16);
uint16_t tag_id = static_cast<uint16_t>(tagNumber & 0xFFFF);
if (vendor_id != 0)
{
tag = TLV::ProfileTag(vendor_id, /*profileNum=*/0, tag_id);
}
else if (tag_id <= UINT8_MAX)
{
tag = TLV::ContextTag(static_cast<uint8_t>(tagNumber));
}
else
{
tag = TLV::ProfileTag(profileId, tagNumber);
}
return CHIP_NO_ERROR;
}
template <typename T>
CHIP_ERROR ParseNumericalField(const std::string & decimalString, T & outValue)
{
const char * start_ptr = decimalString.data();
const char * end_ptr = decimalString.data() + decimalString.size();
auto [last_converted_ptr, _] = std::from_chars(start_ptr, end_ptr, outValue, 10);
VerifyOrReturnError(last_converted_ptr == end_ptr, CHIP_ERROR_INVALID_ARGUMENT);
return CHIP_NO_ERROR;
}
CHIP_ERROR ParseJsonName(const std::string & name, ElementContext & elementCtx, uint32_t implicitProfileId)
{
uint32_t tagNumber = 0;
const char * elementType = nullptr;
std::vector<std::string> nameFields = SplitIntoFieldsBySeparator(name, ':');
TLV::Tag tag = TLV::AnonymousTag();
ElementTypeContext type;
ElementTypeContext subType;
if (nameFields.size() == 2)
{
ReturnErrorOnFailure(ParseNumericalField(nameFields[0], tagNumber));
elementType = nameFields[1].c_str();
}
else if (nameFields.size() == 3)
{
ReturnErrorOnFailure(ParseNumericalField(nameFields[1], tagNumber));
elementType = nameFields[2].c_str();
}
else
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
ReturnErrorOnFailure(InternalConvertTlvTag(tagNumber, tag, implicitProfileId));
ReturnErrorOnFailure(JsonTypeStrToTlvType(elementType, type));
if (type.tlvType == TLV::kTLVType_Array)
{
std::vector<std::string> arrayFields = SplitIntoFieldsBySeparator(elementType, '-');
VerifyOrReturnError(arrayFields.size() == 2, CHIP_ERROR_INVALID_ARGUMENT);
if (strcmp(arrayFields[1].c_str(), kElementTypeEmpty) == 0)
{
subType.tlvType = TLV::kTLVType_NotSpecified;
}
else
{
ReturnErrorOnFailure(JsonTypeStrToTlvType(arrayFields[1].c_str(), subType));
}
}
elementCtx.jsonName = name;
elementCtx.tag = tag;
elementCtx.type = type;
elementCtx.subType = subType;
return CHIP_NO_ERROR;
}
CHIP_ERROR EncodeTlvElement(const Json::Value & val, TLV::TLVWriter & writer, const ElementContext & elementCtx)
{
TLV::Tag tag = elementCtx.tag;
switch (elementCtx.type.tlvType)
{
case TLV::kTLVType_UnsignedInteger: {
uint64_t v = 0;
if (val.isUInt64())
{
v = val.asUInt64();
}
else if (val.isString())
{
ReturnErrorOnFailure(ParseNumericalField(val.asString(), v));
}
else
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
ReturnErrorOnFailure(writer.Put(tag, v));
break;
}
case TLV::kTLVType_SignedInteger: {
int64_t v = 0;
if (val.isInt64())
{
v = val.asInt64();
}
else if (val.isString())
{
ReturnErrorOnFailure(ParseNumericalField(val.asString(), v));
}
else
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
ReturnErrorOnFailure(writer.Put(tag, v));
break;
}
case TLV::kTLVType_Boolean: {
VerifyOrReturnError(val.isBool(), CHIP_ERROR_INVALID_ARGUMENT);
ReturnErrorOnFailure(writer.Put(tag, val.asBool()));
break;
}
case TLV::kTLVType_FloatingPointNumber: {
if (val.isNumeric())
{
if (elementCtx.type.isDouble)
{
ReturnErrorOnFailure(writer.Put(tag, val.asDouble()));
}
else
{
ReturnErrorOnFailure(writer.Put(tag, val.asFloat()));
}
}
else if (val.isString())
{
const std::string valAsString = val.asString();
bool isPositiveInfinity = (valAsString == kFloatingPointPositiveInfinity);
bool isNegativeInfinity = (valAsString == kFloatingPointNegativeInfinity);
VerifyOrReturnError(isPositiveInfinity || isNegativeInfinity, CHIP_ERROR_INVALID_ARGUMENT);
if (elementCtx.type.isDouble)
{
if (isPositiveInfinity)
{
ReturnErrorOnFailure(writer.Put(tag, std::numeric_limits<double>::infinity()));
}
else
{
ReturnErrorOnFailure(writer.Put(tag, -std::numeric_limits<double>::infinity()));
}
}
else
{
if (isPositiveInfinity)
{
ReturnErrorOnFailure(writer.Put(tag, std::numeric_limits<float>::infinity()));
}
else
{
ReturnErrorOnFailure(writer.Put(tag, -std::numeric_limits<float>::infinity()));
}
}
}
else
{
return CHIP_ERROR_INVALID_ARGUMENT;
}
break;
}
case TLV::kTLVType_ByteString: {
VerifyOrReturnError(val.isString(), CHIP_ERROR_INVALID_ARGUMENT);
const std::string valAsString = val.asString();
size_t encodedLen = valAsString.length();
VerifyOrReturnError(CanCastTo<uint16_t>(encodedLen), CHIP_ERROR_INVALID_ARGUMENT);
// Check if the length is a multiple of 4 as strict padding is required.
VerifyOrReturnError(encodedLen % 4 == 0, CHIP_ERROR_INVALID_ARGUMENT);
Platform::ScopedMemoryBuffer<uint8_t> byteString;
byteString.Alloc(BASE64_MAX_DECODED_LEN(static_cast<uint16_t>(encodedLen)));
// On a platform where malloc(0) is null (which could be misinterpreted as "out of memory")
// we should skip this check if it's a zero-length string.
#ifdef CONFIG_MALLOC_0_IS_NULL
if (encodedLen > 0)
#endif
VerifyOrReturnError(byteString.Get() != nullptr, CHIP_ERROR_NO_MEMORY);
auto decodedLen = Base64Decode(valAsString.c_str(), static_cast<uint16_t>(encodedLen), byteString.Get());
VerifyOrReturnError(decodedLen < UINT16_MAX, CHIP_ERROR_INVALID_ARGUMENT);
ReturnErrorOnFailure(writer.PutBytes(tag, byteString.Get(), decodedLen));
break;
}
case TLV::kTLVType_UTF8String: {
VerifyOrReturnError(val.isString(), CHIP_ERROR_INVALID_ARGUMENT);
const std::string valAsString = val.asString();
ReturnErrorOnFailure(writer.PutString(tag, valAsString.data(), static_cast<uint32_t>(valAsString.size())));
break;
}
case TLV::kTLVType_Null: {
VerifyOrReturnError(val.isNull(), CHIP_ERROR_INVALID_ARGUMENT);
ReturnErrorOnFailure(writer.PutNull(tag));
break;
}
case TLV::kTLVType_Structure: {
TLV::TLVType containerType;
VerifyOrReturnError(val.isObject(), CHIP_ERROR_INVALID_ARGUMENT);
ReturnErrorOnFailure(writer.StartContainer(tag, TLV::kTLVType_Structure, containerType));
std::vector<std::string> jsonNames = val.getMemberNames();
std::vector<ElementContext> nestedElementsCtx;
for (size_t i = 0; i < jsonNames.size(); i++)
{
ElementContext ctx;
ReturnErrorOnFailure(ParseJsonName(jsonNames[i], ctx, writer.ImplicitProfileId));
nestedElementsCtx.push_back(ctx);
}
// Sort Json object elements by Tag number (low to high).
// Note that all sorted Context Tags will appear first followed by all sorted Common Tags.
std::sort(nestedElementsCtx.begin(), nestedElementsCtx.end(), CompareByTag);
for (auto & ctx : nestedElementsCtx)
{
ReturnErrorOnFailure(EncodeTlvElement(val[ctx.jsonName], writer, ctx));
}
ReturnErrorOnFailure(writer.EndContainer(containerType));
break;
}
case TLV::kTLVType_Array: {
TLV::TLVType containerType;
VerifyOrReturnError(val.isArray(), CHIP_ERROR_INVALID_ARGUMENT);
ReturnErrorOnFailure(writer.StartContainer(tag, TLV::kTLVType_Array, containerType));
if (elementCtx.subType.tlvType == TLV::kTLVType_NotSpecified)
{
VerifyOrReturnError(val.size() == 0, CHIP_ERROR_INVALID_ARGUMENT);
}
else
{
ElementContext nestedElementCtx;
nestedElementCtx.tag = TLV::AnonymousTag();
nestedElementCtx.type = elementCtx.subType;
for (Json::ArrayIndex i = 0; i < val.size(); i++)
{
ReturnErrorOnFailure(EncodeTlvElement(val[i], writer, nestedElementCtx));
}
}
ReturnErrorOnFailure(writer.EndContainer(containerType));
break;
}
default:
return CHIP_ERROR_INVALID_TLV_ELEMENT;
break;
}
return CHIP_NO_ERROR;
}
} // namespace
CHIP_ERROR JsonToTlv(const std::string & jsonString, MutableByteSpan & tlv)
{
TLV::TLVWriter writer;
writer.Init(tlv);
writer.ImplicitProfileId = kTemporaryImplicitProfileId;
ReturnErrorOnFailure(JsonToTlv(jsonString, writer));
ReturnErrorOnFailure(writer.Finalize());
tlv.reduce_size(writer.GetLengthWritten());
return CHIP_NO_ERROR;
}
CHIP_ERROR JsonToTlv(const std::string & jsonString, TLV::TLVWriter & writer)
{
Json::Reader reader;
Json::Value json;
bool result = reader.parse(jsonString, json);
VerifyOrReturnError(result, CHIP_ERROR_INTERNAL);
ElementContext elementCtx;
elementCtx.type = { TLV::kTLVType_Structure, false };
// Use kTemporaryImplicitProfileId as the default value for cases where no explicit implicit profile ID is provided by
// the caller. This allows for the encoding of tags that are not vendor-specific or context-specific but are instead
// associated with a temporary implicit profile ID (0xFF01).
if (writer.ImplicitProfileId == TLV::kProfileIdNotSpecified)
{
writer.ImplicitProfileId = kTemporaryImplicitProfileId;
}
return EncodeTlvElement(json, writer, elementCtx);
}
CHIP_ERROR ConvertTlvTag(uint32_t tagNumber, TLV::Tag & tag)
{
return InternalConvertTlvTag(tagNumber, tag);
}
} // namespace chip