forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCHIPTLVReader.cpp
1008 lines (847 loc) · 27.8 KB
/
CHIPTLVReader.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
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) 2020-2021 Project CHIP Authors
* Copyright (c) 2013-2017 Nest Labs, Inc.
*
* 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.
*/
/**
* @file
* This file implements a parser for the CHIP TLV (Tag-Length-Value) encoding format.
*
*/
#include <stdlib.h>
#include <lib/core/CHIPCore.h>
#include <lib/core/CHIPEncoding.h>
#include <lib/core/CHIPSafeCasts.h>
#include <lib/core/CHIPTLV.h>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/SafeInt.h>
namespace chip {
namespace TLV {
using namespace chip::Encoding;
static const uint8_t sTagSizes[] = { 0, 1, 2, 4, 2, 4, 6, 8 };
void TLVReader::Init(const uint8_t * data, size_t dataLen)
{
// TODO: Maybe we can just make mMaxLen and mLenRead size_t instead?
uint32_t actualDataLen = dataLen > UINT32_MAX ? UINT32_MAX : static_cast<uint32_t>(dataLen);
mBackingStore = nullptr;
mReadPoint = data;
mBufEnd = data + actualDataLen;
mLenRead = 0;
mMaxLen = actualDataLen;
ClearElementState();
mContainerType = kTLVType_NotSpecified;
SetContainerOpen(false);
ImplicitProfileId = kProfileIdNotSpecified;
}
CHIP_ERROR TLVReader::Init(TLVBackingStore & backingStore, uint32_t maxLen)
{
mBackingStore = &backingStore;
mReadPoint = nullptr;
uint32_t bufLen = 0;
CHIP_ERROR err = mBackingStore->OnInit(*this, mReadPoint, bufLen);
if (err != CHIP_NO_ERROR)
return err;
mBufEnd = mReadPoint + bufLen;
mLenRead = 0;
mMaxLen = maxLen;
ClearElementState();
mContainerType = kTLVType_NotSpecified;
SetContainerOpen(false);
ImplicitProfileId = kProfileIdNotSpecified;
AppData = nullptr;
return CHIP_NO_ERROR;
}
void TLVReader::Init(const TLVReader & aReader)
{
// Initialize private data members
mElemTag = aReader.mElemTag;
mElemLenOrVal = aReader.mElemLenOrVal;
mBackingStore = aReader.mBackingStore;
mReadPoint = aReader.mReadPoint;
mBufEnd = aReader.mBufEnd;
mLenRead = aReader.mLenRead;
mMaxLen = aReader.mMaxLen;
mControlByte = aReader.mControlByte;
mContainerType = aReader.mContainerType;
SetContainerOpen(aReader.IsContainerOpen());
// Initialize public data members
ImplicitProfileId = aReader.ImplicitProfileId;
AppData = aReader.AppData;
}
TLVType TLVReader::GetType() const
{
TLVElementType elemType = ElementType();
if (elemType == TLVElementType::EndOfContainer)
return kTLVType_NotSpecified;
if (elemType == TLVElementType::FloatingPointNumber32 || elemType == TLVElementType::FloatingPointNumber64)
return kTLVType_FloatingPointNumber;
if (elemType == TLVElementType::NotSpecified || elemType >= TLVElementType::Null)
return static_cast<TLVType>(elemType);
return static_cast<TLVType>(static_cast<uint8_t>(elemType) & ~kTLVTypeSizeMask);
}
uint32_t TLVReader::GetLength() const
{
if (TLVTypeHasLength(ElementType()))
return static_cast<uint32_t>(mElemLenOrVal);
return 0;
}
CHIP_ERROR TLVReader::Get(bool & v)
{
TLVElementType elemType = ElementType();
if (elemType == TLVElementType::BooleanFalse)
v = false;
else if (elemType == TLVElementType::BooleanTrue)
v = true;
else
return CHIP_ERROR_WRONG_TLV_TYPE;
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::Get(int8_t & v)
{
int64_t v64 = 0;
CHIP_ERROR err = Get(v64);
if (!CanCastTo<int8_t>(v64))
{
return CHIP_ERROR_INVALID_INTEGER_VALUE;
}
v = static_cast<int8_t>(v64);
return err;
}
CHIP_ERROR TLVReader::Get(int16_t & v)
{
int64_t v64 = 0;
CHIP_ERROR err = Get(v64);
if (!CanCastTo<int16_t>(v64))
{
return CHIP_ERROR_INVALID_INTEGER_VALUE;
}
v = static_cast<int16_t>(v64);
return err;
}
CHIP_ERROR TLVReader::Get(int32_t & v)
{
int64_t v64 = 0;
CHIP_ERROR err = Get(v64);
if (!CanCastTo<int32_t>(v64))
{
return CHIP_ERROR_INVALID_INTEGER_VALUE;
}
v = static_cast<int32_t>(v64);
return err;
}
CHIP_ERROR TLVReader::Get(int64_t & v)
{
// Internal callers of this method depend on it not modifying "v" on failure.
switch (ElementType())
{
case TLVElementType::Int8:
v = CastToSigned(static_cast<uint8_t>(mElemLenOrVal));
break;
case TLVElementType::Int16:
v = CastToSigned(static_cast<uint16_t>(mElemLenOrVal));
break;
case TLVElementType::Int32:
v = CastToSigned(static_cast<uint32_t>(mElemLenOrVal));
break;
case TLVElementType::Int64:
v = CastToSigned(mElemLenOrVal);
break;
default:
return CHIP_ERROR_WRONG_TLV_TYPE;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::Get(uint8_t & v)
{
uint64_t v64 = 0;
CHIP_ERROR err = Get(v64);
if (!CanCastTo<uint8_t>(v64))
{
return CHIP_ERROR_INVALID_INTEGER_VALUE;
}
v = static_cast<uint8_t>(v64);
return err;
}
CHIP_ERROR TLVReader::Get(uint16_t & v)
{
uint64_t v64 = 0;
CHIP_ERROR err = Get(v64);
if (!CanCastTo<uint16_t>(v64))
{
return CHIP_ERROR_INVALID_INTEGER_VALUE;
}
v = static_cast<uint16_t>(v64);
return err;
}
CHIP_ERROR TLVReader::Get(uint32_t & v)
{
uint64_t v64 = 0;
CHIP_ERROR err = Get(v64);
if (!CanCastTo<uint32_t>(v64))
{
return CHIP_ERROR_INVALID_INTEGER_VALUE;
}
v = static_cast<uint32_t>(v64);
return err;
}
CHIP_ERROR TLVReader::Get(uint64_t & v)
{
// Internal callers of this method depend on it not modifying "v" on failure.
switch (ElementType())
{
case TLVElementType::UInt8:
case TLVElementType::UInt16:
case TLVElementType::UInt32:
case TLVElementType::UInt64:
v = mElemLenOrVal;
break;
default:
return CHIP_ERROR_WRONG_TLV_TYPE;
}
return CHIP_NO_ERROR;
}
namespace {
float BitCastToFloat(const uint64_t elemLenOrVal)
{
float f;
auto unsigned32 = static_cast<uint32_t>(elemLenOrVal);
memcpy(&f, &unsigned32, sizeof(f));
return f;
}
} // namespace
// Note: Unlike the integer Get functions, this code avoids doing conversions
// between float and double wherever possible, because these conversions are
// relatively expensive on platforms that use soft-float instruction sets.
CHIP_ERROR TLVReader::Get(float & v)
{
switch (ElementType())
{
case TLVElementType::FloatingPointNumber32: {
v = BitCastToFloat(mElemLenOrVal);
break;
}
default:
return CHIP_ERROR_WRONG_TLV_TYPE;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::Get(double & v)
{
switch (ElementType())
{
case TLVElementType::FloatingPointNumber32: {
v = BitCastToFloat(mElemLenOrVal);
break;
}
case TLVElementType::FloatingPointNumber64: {
double d;
memcpy(&d, &mElemLenOrVal, sizeof(d));
v = d;
break;
}
default:
return CHIP_ERROR_WRONG_TLV_TYPE;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::Get(ByteSpan & v)
{
const uint8_t * val;
ReturnErrorOnFailure(GetDataPtr(val));
v = ByteSpan(val, GetLength());
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::Get(CharSpan & v)
{
if (!TLVTypeIsUTF8String(ElementType()))
{
return CHIP_ERROR_WRONG_TLV_TYPE;
}
const uint8_t * bytes;
ReturnErrorOnFailure(GetDataPtr(bytes)); // Does length sanity checks
v = CharSpan(Uint8::to_const_char(bytes), GetLength());
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::GetBytes(uint8_t * buf, size_t bufSize)
{
if (!TLVTypeIsString(ElementType()))
return CHIP_ERROR_WRONG_TLV_TYPE;
if (mElemLenOrVal > bufSize)
return CHIP_ERROR_BUFFER_TOO_SMALL;
CHIP_ERROR err = ReadData(buf, static_cast<uint32_t>(mElemLenOrVal));
if (err != CHIP_NO_ERROR)
return err;
mElemLenOrVal = 0;
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::GetString(char * buf, size_t bufSize)
{
if (!TLVTypeIsString(ElementType()))
return CHIP_ERROR_WRONG_TLV_TYPE;
if ((mElemLenOrVal + 1) > bufSize)
return CHIP_ERROR_BUFFER_TOO_SMALL;
buf[mElemLenOrVal] = 0;
return GetBytes(reinterpret_cast<uint8_t *>(buf), bufSize - 1);
}
CHIP_ERROR TLVReader::DupBytes(uint8_t *& buf, uint32_t & dataLen)
{
if (!TLVTypeIsString(ElementType()))
return CHIP_ERROR_WRONG_TLV_TYPE;
buf = static_cast<uint8_t *>(chip::Platform::MemoryAlloc(static_cast<uint32_t>(mElemLenOrVal)));
if (buf == nullptr)
return CHIP_ERROR_NO_MEMORY;
CHIP_ERROR err = ReadData(buf, static_cast<uint32_t>(mElemLenOrVal));
if (err != CHIP_NO_ERROR)
{
chip::Platform::MemoryFree(buf);
buf = nullptr;
return err;
}
dataLen = static_cast<uint32_t>(mElemLenOrVal);
mElemLenOrVal = 0;
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::DupString(char *& buf)
{
if (!TLVTypeIsString(ElementType()))
return CHIP_ERROR_WRONG_TLV_TYPE;
if (mElemLenOrVal > UINT32_MAX - 1)
return CHIP_ERROR_NO_MEMORY;
buf = static_cast<char *>(chip::Platform::MemoryAlloc(static_cast<uint32_t>(mElemLenOrVal + 1)));
if (buf == nullptr)
return CHIP_ERROR_NO_MEMORY;
CHIP_ERROR err = ReadData(reinterpret_cast<uint8_t *>(buf), static_cast<uint32_t>(mElemLenOrVal));
if (err != CHIP_NO_ERROR)
{
chip::Platform::MemoryFree(buf);
buf = nullptr;
return err;
}
buf[mElemLenOrVal] = 0;
mElemLenOrVal = 0;
return err;
}
CHIP_ERROR TLVReader::GetDataPtr(const uint8_t *& data)
{
CHIP_ERROR err;
if (!TLVTypeIsString(ElementType()))
return CHIP_ERROR_WRONG_TLV_TYPE;
if (GetLength() == 0)
{
data = nullptr;
return CHIP_NO_ERROR;
}
err = EnsureData(CHIP_ERROR_TLV_UNDERRUN);
if (err != CHIP_NO_ERROR)
return err;
uint32_t remainingLen = static_cast<decltype(mMaxLen)>(mBufEnd - mReadPoint);
// Verify that the entirety of the data is available in the buffer.
// Note that this may not be possible if the reader is reading from a chain of buffers.
if (remainingLen < static_cast<uint32_t>(mElemLenOrVal))
return CHIP_ERROR_TLV_UNDERRUN;
data = mReadPoint;
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::OpenContainer(TLVReader & containerReader)
{
TLVElementType elemType = ElementType();
if (!TLVTypeIsContainer(elemType))
return CHIP_ERROR_INCORRECT_STATE;
containerReader.mBackingStore = mBackingStore;
containerReader.mReadPoint = mReadPoint;
containerReader.mBufEnd = mBufEnd;
containerReader.mLenRead = mLenRead;
containerReader.mMaxLen = mMaxLen;
containerReader.ClearElementState();
containerReader.mContainerType = static_cast<TLVType>(elemType);
containerReader.SetContainerOpen(false);
containerReader.ImplicitProfileId = ImplicitProfileId;
containerReader.AppData = AppData;
SetContainerOpen(true);
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::CloseContainer(TLVReader & containerReader)
{
CHIP_ERROR err;
if (!IsContainerOpen())
return CHIP_ERROR_INCORRECT_STATE;
if (static_cast<TLVElementType>(containerReader.mContainerType) != ElementType())
return CHIP_ERROR_INCORRECT_STATE;
err = containerReader.SkipToEndOfContainer();
if (err != CHIP_NO_ERROR)
return err;
mBackingStore = containerReader.mBackingStore;
mReadPoint = containerReader.mReadPoint;
mBufEnd = containerReader.mBufEnd;
mLenRead = containerReader.mLenRead;
mMaxLen = containerReader.mMaxLen;
ClearElementState();
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::EnterContainer(TLVType & outerContainerType)
{
TLVElementType elemType = ElementType();
if (!TLVTypeIsContainer(elemType))
return CHIP_ERROR_INCORRECT_STATE;
outerContainerType = mContainerType;
mContainerType = static_cast<TLVType>(elemType);
ClearElementState();
SetContainerOpen(false);
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::ExitContainer(TLVType outerContainerType)
{
CHIP_ERROR err;
err = SkipToEndOfContainer();
if (err != CHIP_NO_ERROR)
return err;
mContainerType = outerContainerType;
ClearElementState();
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::VerifyEndOfContainer()
{
CHIP_ERROR err = Next();
if (err == CHIP_END_OF_TLV)
return CHIP_NO_ERROR;
if (err == CHIP_NO_ERROR)
return CHIP_ERROR_UNEXPECTED_TLV_ELEMENT;
return err;
}
CHIP_ERROR TLVReader::Next()
{
CHIP_ERROR err;
TLVElementType elemType = ElementType();
err = Skip();
if (err != CHIP_NO_ERROR)
return err;
err = ReadElement();
if (err != CHIP_NO_ERROR)
return err;
elemType = ElementType();
if (elemType == TLVElementType::EndOfContainer)
return CHIP_END_OF_TLV;
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::Next(Tag expectedTag)
{
CHIP_ERROR err = Next();
if (err != CHIP_NO_ERROR)
return err;
if (mElemTag != expectedTag)
return CHIP_ERROR_UNEXPECTED_TLV_ELEMENT;
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::Next(TLVType expectedType, Tag expectedTag)
{
CHIP_ERROR err = Next(expectedTag);
if (err != CHIP_NO_ERROR)
return err;
if (GetType() != expectedType)
return CHIP_ERROR_WRONG_TLV_TYPE;
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::Skip()
{
CHIP_ERROR err;
TLVElementType elemType = ElementType();
if (elemType == TLVElementType::EndOfContainer)
return CHIP_END_OF_TLV;
if (TLVTypeIsContainer(elemType))
{
TLVType outerContainerType;
err = EnterContainer(outerContainerType);
if (err != CHIP_NO_ERROR)
return err;
err = ExitContainer(outerContainerType);
if (err != CHIP_NO_ERROR)
return err;
}
else
{
err = SkipData();
if (err != CHIP_NO_ERROR)
return err;
ClearElementState();
}
return CHIP_NO_ERROR;
}
/**
* Clear the state of the TLVReader.
* This method is used to position the reader before the first TLV,
* between TLVs or after the last TLV.
*/
void TLVReader::ClearElementState()
{
mElemTag = AnonymousTag();
mControlByte = kTLVControlByte_NotSpecified;
mElemLenOrVal = 0;
}
/**
* Skip any data contained in the current TLV by reading over it without
* a destination buffer.
*
* @retval #CHIP_NO_ERROR If the reader was successfully positioned at the end of the
* data.
* @retval other Other CHIP or platform error codes returned by the configured
* TLVBackingStore.
*/
CHIP_ERROR TLVReader::SkipData()
{
CHIP_ERROR err = CHIP_NO_ERROR;
TLVElementType elemType = ElementType();
if (TLVTypeHasLength(elemType))
{
err = ReadData(nullptr, static_cast<uint32_t>(mElemLenOrVal));
if (err != CHIP_NO_ERROR)
return err;
}
return err;
}
CHIP_ERROR TLVReader::SkipToEndOfContainer()
{
CHIP_ERROR err;
TLVType outerContainerType = mContainerType;
uint32_t nestLevel = 0;
// If the user calls Next() after having called OpenContainer() but before calling
// CloseContainer() they're effectively doing a close container by skipping over
// the container element. So reset the 'container open' flag here to prevent them
// from calling CloseContainer() with the now orphaned container reader.
SetContainerOpen(false);
while (true)
{
TLVElementType elemType = ElementType();
if (elemType == TLVElementType::EndOfContainer)
{
if (nestLevel == 0)
return CHIP_NO_ERROR;
nestLevel--;
mContainerType = (nestLevel == 0) ? outerContainerType : kTLVType_UnknownContainer;
}
else if (TLVTypeIsContainer(elemType))
{
nestLevel++;
mContainerType = static_cast<TLVType>(elemType);
}
err = SkipData();
if (err != CHIP_NO_ERROR)
return err;
err = ReadElement();
if (err != CHIP_NO_ERROR)
return err;
}
}
CHIP_ERROR TLVReader::ReadElement()
{
CHIP_ERROR err;
uint8_t stagingBuf[17]; // 17 = 1 control byte + 8 tag bytes + 8 length/value bytes
const uint8_t * p;
TLVElementType elemType;
// Make sure we have input data. Return CHIP_END_OF_TLV if no more data is available.
err = EnsureData(CHIP_END_OF_TLV);
if (err != CHIP_NO_ERROR)
return err;
if (mReadPoint == nullptr)
{
return CHIP_ERROR_INVALID_TLV_ELEMENT;
}
// Get the element's control byte.
mControlByte = *mReadPoint;
// Extract the element type from the control byte. Fail if it's invalid.
elemType = ElementType();
if (!IsValidTLVType(elemType))
return CHIP_ERROR_INVALID_TLV_ELEMENT;
// Extract the tag control from the control byte.
TLVTagControl tagControl = static_cast<TLVTagControl>(mControlByte & kTLVTagControlMask);
// Determine the number of bytes in the element's tag, if any.
uint8_t tagBytes = sTagSizes[tagControl >> kTLVTagControlShift];
// Extract the size of length/value field from the control byte.
TLVFieldSize lenOrValFieldSize = GetTLVFieldSize(elemType);
// Determine the number of bytes in the length/value field.
uint8_t valOrLenBytes = TLVFieldSizeToBytes(lenOrValFieldSize);
// Determine the number of bytes in the element's 'head'. This includes: the control byte, the tag bytes (if present), the
// length bytes (if present), and for elements that don't have a length (e.g. integers), the value bytes.
uint8_t elemHeadBytes = static_cast<uint8_t>(1 + tagBytes + valOrLenBytes);
// If the head of the element overlaps the end of the input buffer, read the bytes into the staging buffer
// and arrange to parse them from there. Otherwise read them directly from the input buffer.
if (elemHeadBytes > (mBufEnd - mReadPoint))
{
err = ReadData(stagingBuf, elemHeadBytes);
if (err != CHIP_NO_ERROR)
return err;
p = stagingBuf;
}
else
{
p = mReadPoint;
mReadPoint += elemHeadBytes;
mLenRead += elemHeadBytes;
}
// Skip over the control byte.
p++;
// Read the tag field, if present.
mElemTag = ReadTag(tagControl, p);
// Read the length/value field, if present.
switch (lenOrValFieldSize)
{
case kTLVFieldSize_0Byte:
mElemLenOrVal = 0;
break;
case kTLVFieldSize_1Byte:
mElemLenOrVal = Read8(p);
break;
case kTLVFieldSize_2Byte:
mElemLenOrVal = LittleEndian::Read16(p);
break;
case kTLVFieldSize_4Byte:
mElemLenOrVal = LittleEndian::Read32(p);
break;
case kTLVFieldSize_8Byte:
mElemLenOrVal = LittleEndian::Read64(p);
VerifyOrReturnError(!TLVTypeHasLength(elemType) || (mElemLenOrVal <= UINT32_MAX), CHIP_ERROR_NOT_IMPLEMENTED);
break;
}
return VerifyElement();
}
CHIP_ERROR TLVReader::VerifyElement()
{
if (ElementType() == TLVElementType::EndOfContainer)
{
if (mContainerType == kTLVType_NotSpecified)
return CHIP_ERROR_INVALID_TLV_ELEMENT;
if (mElemTag != AnonymousTag())
return CHIP_ERROR_INVALID_TLV_TAG;
}
else
{
if (mElemTag == UnknownImplicitTag())
return CHIP_ERROR_UNKNOWN_IMPLICIT_TLV_TAG;
switch (mContainerType)
{
case kTLVType_NotSpecified:
if (IsContextTag(mElemTag))
return CHIP_ERROR_INVALID_TLV_TAG;
break;
case kTLVType_Structure:
if (mElemTag == AnonymousTag())
return CHIP_ERROR_INVALID_TLV_TAG;
break;
case kTLVType_Array:
if (mElemTag != AnonymousTag())
return CHIP_ERROR_INVALID_TLV_TAG;
break;
case kTLVType_UnknownContainer:
case kTLVType_List:
break;
default:
return CHIP_ERROR_INCORRECT_STATE;
}
}
// If the current element encodes a specific length (e.g. a UTF8 string or a byte string), verify
// that the purported length fits within the remaining bytes of the encoding (as delineated by mMaxLen).
//
// Note that this check is not strictly necessary to prevent runtime errors, as any attempt to access
// the data of an element with an invalid length will result in an error. However checking the length
// here catches the error earlier, and ensures that the application will never see the erroneous length
// value.
//
if (TLVTypeHasLength(ElementType()))
{
uint32_t overallLenRemaining = mMaxLen - mLenRead;
if (overallLenRemaining < static_cast<uint32_t>(mElemLenOrVal))
return CHIP_ERROR_TLV_UNDERRUN;
}
return CHIP_NO_ERROR;
}
Tag TLVReader::ReadTag(TLVTagControl tagControl, const uint8_t *& p) const
{
uint16_t vendorId;
uint16_t profileNum;
switch (tagControl)
{
case TLVTagControl::ContextSpecific:
return ContextTag(Read8(p));
case TLVTagControl::CommonProfile_2Bytes:
return CommonTag(LittleEndian::Read16(p));
case TLVTagControl::CommonProfile_4Bytes:
return CommonTag(LittleEndian::Read32(p));
case TLVTagControl::ImplicitProfile_2Bytes:
if (ImplicitProfileId == kProfileIdNotSpecified)
return UnknownImplicitTag();
return ProfileTag(ImplicitProfileId, LittleEndian::Read16(p));
case TLVTagControl::ImplicitProfile_4Bytes:
if (ImplicitProfileId == kProfileIdNotSpecified)
return UnknownImplicitTag();
return ProfileTag(ImplicitProfileId, LittleEndian::Read32(p));
case TLVTagControl::FullyQualified_6Bytes:
vendorId = LittleEndian::Read16(p);
profileNum = LittleEndian::Read16(p);
return ProfileTag(vendorId, profileNum, LittleEndian::Read16(p));
case TLVTagControl::FullyQualified_8Bytes:
vendorId = LittleEndian::Read16(p);
profileNum = LittleEndian::Read16(p);
return ProfileTag(vendorId, profileNum, LittleEndian::Read32(p));
case TLVTagControl::Anonymous:
default:
return AnonymousTag();
}
}
CHIP_ERROR TLVReader::ReadData(uint8_t * buf, uint32_t len)
{
CHIP_ERROR err;
while (len > 0)
{
err = EnsureData(CHIP_ERROR_TLV_UNDERRUN);
if (err != CHIP_NO_ERROR)
return err;
uint32_t remainingLen = static_cast<decltype(mMaxLen)>(mBufEnd - mReadPoint);
uint32_t readLen = len;
if (readLen > remainingLen)
readLen = remainingLen;
if (buf != nullptr)
{
memcpy(buf, mReadPoint, readLen);
buf += readLen;
}
mReadPoint += readLen;
mLenRead += readLen;
len -= readLen;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR TLVReader::EnsureData(CHIP_ERROR noDataErr)
{
CHIP_ERROR err;
if (mReadPoint == mBufEnd)
{
if (mLenRead == mMaxLen)
return noDataErr;
if (mBackingStore == nullptr)
return noDataErr;
uint32_t bufLen;
err = mBackingStore->GetNextBuffer(*this, mReadPoint, bufLen);
if (err != CHIP_NO_ERROR)
return err;
if (bufLen == 0)
return noDataErr;
// Cap mBufEnd so that we don't read beyond the user's specified maximum length, even
// if the underlying buffer is larger.
uint32_t overallLenRemaining = mMaxLen - mLenRead;
if (overallLenRemaining < bufLen)
bufLen = overallLenRemaining;
mBufEnd = mReadPoint + bufLen;
}
return CHIP_NO_ERROR;
}
/**
* This is a private method used to compute the length of a TLV element head.
*/
CHIP_ERROR TLVReader::GetElementHeadLength(uint8_t & elemHeadBytes) const
{
uint8_t tagBytes;
uint8_t valOrLenBytes;
TLVTagControl tagControl;
TLVFieldSize lenOrValFieldSize;
TLVElementType elemType = ElementType();
// Verify element is of valid TLVType.
VerifyOrReturnError(IsValidTLVType(elemType), CHIP_ERROR_INVALID_TLV_ELEMENT);
// Extract the tag control from the control byte.
tagControl = static_cast<TLVTagControl>(mControlByte & kTLVTagControlMask);
// Determine the number of bytes in the element's tag, if any.
tagBytes = sTagSizes[tagControl >> kTLVTagControlShift];
// Extract the size of length/value field from the control byte.
lenOrValFieldSize = GetTLVFieldSize(elemType);
// Determine the number of bytes in the length/value field.
valOrLenBytes = TLVFieldSizeToBytes(lenOrValFieldSize);
// Determine the number of bytes in the element's 'head'. This includes: the
// control byte, the tag bytes (if present), the length bytes (if present),
// and for elements that don't have a length (e.g. integers), the value
// bytes.
VerifyOrReturnError(CanCastTo<uint8_t>(1 + tagBytes + valOrLenBytes), CHIP_ERROR_INTERNAL);
elemHeadBytes = static_cast<uint8_t>(1 + tagBytes + valOrLenBytes);
return CHIP_NO_ERROR;
}
/**
* This is a private method that returns the TLVElementType from mControlByte
*/
TLVElementType TLVReader::ElementType() const
{
if (mControlByte == static_cast<uint16_t>(kTLVControlByte_NotSpecified))
return TLVElementType::NotSpecified;
return static_cast<TLVElementType>(mControlByte & kTLVTypeMask);
}
CHIP_ERROR TLVReader::FindElementWithTag(Tag tag, TLVReader & destReader) const
{
CHIP_ERROR err = CHIP_NO_ERROR;
chip::TLV::TLVReader reader;
reader.Init(*this);
while (CHIP_NO_ERROR == (err = reader.Next()))
{
VerifyOrExit(chip::TLV::kTLVType_NotSpecified != reader.GetType(), err = CHIP_ERROR_INVALID_TLV_ELEMENT);
if (tag == reader.GetTag())
{
destReader.Init(reader);
break;
}
}
exit:
ChipLogIfFalse((CHIP_NO_ERROR == err) || (CHIP_END_OF_TLV == err));
return err;
}
CHIP_ERROR TLVReader::CountRemainingInContainer(size_t * size) const
{
if (mContainerType == kTLVType_NotSpecified)
{
return CHIP_ERROR_INCORRECT_STATE;
}
TLVReader tempReader(*this);
size_t count = 0;
CHIP_ERROR err;
while ((err = tempReader.Next()) == CHIP_NO_ERROR)
{
++count;
};
if (err == CHIP_END_OF_TLV)
{
*size = count;
return CHIP_NO_ERROR;
}
return err;
}
CHIP_ERROR ContiguousBufferTLVReader::OpenContainer(ContiguousBufferTLVReader & containerReader)
{
// We are going to initialize containerReader by calling our superclass
// OpenContainer method. The superclass only knows how to initialize
// members the superclass knows about, so we assert that we don't have any
// extra members that need initializing. If such members ever get added,
// they would need to be initialized in this method.
static_assert(sizeof(ContiguousBufferTLVReader) == sizeof(TLVReader), "We have state the superclass is not initializing?");
return TLVReader::OpenContainer(containerReader);
}
CHIP_ERROR ContiguousBufferTLVReader::GetStringView(Span<const char> & data)
{
return Get(data);
}
CHIP_ERROR ContiguousBufferTLVReader::GetByteView(ByteSpan & data)
{
if (!TLVTypeIsByteString(ElementType()))
{