Coverage Report

Created: 2026-09-28 06:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/PcapPlusPlus/Packet++/header/TLVData.h
Line
Count
Source
1
#pragma once
2
3
#include "Layer.h"
4
#include "IpAddress.h"
5
#include <string.h>
6
#include <type_traits>
7
8
/// @file
9
10
/// @namespace pcpp
11
/// @brief The main namespace for the PcapPlusPlus lib
12
namespace pcpp
13
{
14
  /// @class TLVRecord
15
  /// A wrapper class for a Type-Length-Value (TLV) record. This class does not create or modify TLV records, but
16
  /// rather serves as a wrapper and provides useful methods for retrieving data from them. This class has several
17
  /// abstract methods that should be implemented in derived classes. These methods are for record length value
18
  /// calculation (the 'L' in TLV) which is implemented differently in different protocols
19
  template <typename TRecType, typename TRecLen> class TLVRecord
20
  {
21
  protected:
22
    /// A struct representing the TLV construct
23
#pragma pack(push, 1)
24
    struct TLVRawData
25
    {
26
      /// Record type
27
      TRecType recordType;
28
      /// Record length in bytes
29
      TRecLen recordLen;
30
      /// Record value (variable size)
31
      uint8_t recordValue[];
32
    };
33
#pragma pack(pop)
34
35
    TLVRawData* m_Data;
36
37
  public:
38
    /// A c'tor for this class that gets a pointer to the TLV record raw data (byte array)
39
    /// @param[in] recordRawData A pointer to the TLV record raw data
40
    TLVRecord(uint8_t* recordRawData)
41
    {
42
      assign(recordRawData);
43
    }
44
45
    /// A copy c'tor for this class. This copy c'tor doesn't copy the TLV data, but only the pointer to it,
46
    /// which means that after calling it both the old and the new instance will point to the same TLV raw data
47
    /// @param[in] other The TLVRecord instance to copy from
48
    TLVRecord(const TLVRecord& other)
49
    {
50
      m_Data = other.m_Data;
51
    }
52
53
    /// A d'tor for this class, currently does nothing
54
    virtual ~TLVRecord() = default;
55
56
    /// Assign a pointer to the TLV record raw data (byte array)
57
    /// @param[in] recordRawData A pointer to the TLV record raw data
58
    void assign(uint8_t* recordRawData)
59
0
    {
60
0
      m_Data = reinterpret_cast<TLVRawData*>(recordRawData);
61
0
    }
62
63
    /// Check if a pointer can be assigned to the TLV record data
64
    /// @param[in] recordRawData A pointer to the TLV record raw data
65
    /// @param[in] tlvDataLen The size of the TLV record raw data
66
    /// @return True if data is valid and can be assigned
67
    static bool canAssign(const uint8_t* recordRawData, size_t tlvDataLen)
68
0
    {
69
0
      return recordRawData != nullptr &&
70
0
             tlvDataLen >= (sizeof(TLVRawData::recordType) + sizeof(TLVRawData::recordLen));
71
0
    }
72
73
    /// Overload of the assignment operator. This operator doesn't copy the TLV data, but rather copies the pointer
74
    /// to it, which means that after calling it both the old and the new instance will point to the same TLV raw
75
    /// data
76
    /// @param[in] other The TLVRecord instance to assign
77
    TLVRecord& operator=(const TLVRecord& other)
78
    {
79
      m_Data = other.m_Data;
80
      return *this;
81
    }
82
83
    /// Overload of the equality operator. Two record are equal if both of them point to the same data, or if they
84
    /// point to different data but their total size is equal and the raw data they both contain is similar.
85
    /// @param[in] rhs The object to compare to
86
    /// @return True if both objects are equal, false otherwise
87
    bool operator==(const TLVRecord& rhs) const
88
    {
89
      if (m_Data == rhs.m_Data)
90
        return true;
91
92
      if (getTotalSize() != rhs.getTotalSize())
93
        return false;
94
95
      if (isNull() || ((TLVRecord&)rhs).isNull())
96
        return false;
97
98
      return (memcmp(m_Data, rhs.m_Data, getTotalSize()) == 0);
99
    }
100
101
    /// Overload of the not equal operator.
102
    /// @param[in] rhs The object to compare to
103
    /// @return True if objects are not equal, false otherwise
104
    bool operator!=(const TLVRecord& rhs) const
105
    {
106
      return !operator==(rhs);
107
    }
108
109
    /// @return The type field of the record (the 'T' in __Type__-Length-Value)
110
    TRecType getType() const
111
    {
112
      if (m_Data == nullptr)
113
        return 0;
114
115
      return m_Data->recordType;
116
    }
117
118
    /// @return A pointer to the value of the record as byte array (the 'V' in Type-Length- __Value__)
119
    uint8_t* getValue() const
120
    {
121
      if (m_Data == nullptr)
122
        return nullptr;
123
124
      return m_Data->recordValue;
125
    }
126
127
    /// @return True if the TLV record raw data is nullptr, false otherwise
128
    bool isNull() const
129
    {
130
      return (m_Data == nullptr);
131
    }
132
133
    /// @return True if the TLV record raw data is not nullptr, false otherwise
134
    bool isNotNull() const
135
    {
136
      return (m_Data != nullptr);
137
    }
138
139
    /// @return A pointer to the TLV record raw data byte stream
140
    uint8_t* getRecordBasePtr() const
141
    {
142
      return reinterpret_cast<uint8_t*>(m_Data);
143
    }
144
145
    /// Free the memory of the TLV record raw data
146
    void purgeRecordData()
147
    {
148
      if (!isNull())
149
      {
150
        delete[] m_Data;
151
        m_Data = nullptr;
152
      }
153
    }
154
155
    /// A templated method to retrieve the record data as a certain type T. For example, if record data is 4B long
156
    /// (integer) then this method should be used as getValueAs<int>() and it will return the record data as an
157
    /// integer.<BR> Notice this return value is a copy of the data, not a pointer to the actual data
158
    /// @tparam T A non-pointer, default-constructible, trivially copyable type
159
    /// @param[in] offset The offset in the record data to start reading the value from. Useful for cases when you
160
    /// want to read some of the data that doesn't start at offset 0. This is an optional parameter and the default
161
    /// value is 0, meaning start reading the value at the beginning of the record data
162
    /// @return The record data as type T
163
    template <typename T> T getValueAs(size_t offset = 0) const
164
    {
165
      static_assert(std::is_trivially_copyable<T>::value && std::is_default_constructible<T>::value &&
166
                        !std::is_pointer<T>::value,
167
                    "TLVRecord::getValueAs<T>() requires T to be a non-pointer, "
168
                    "default-constructible, trivially copyable type");
169
170
      if (getDataSize() < sizeof(T) + offset)
171
      {
172
        return T{};
173
      }
174
175
      T result;
176
      memcpy(&result, m_Data->recordValue + getValueOffset() + offset, sizeof(T));
177
      return result;
178
    }
179
180
    /// A templated method to copy data of type T into the TLV record data. For example: if record data is 4[Bytes]
181
    /// long use this method with \<int\> to set an integer value into the record data: setValue<int>(num)
182
    /// @tparam T A non-pointer, trivially copyable type
183
    /// @param[in] newValue The value of type T to copy to the record data
184
    /// @param[in] valueOffset An optional parameter that specifies where to start setting the record data (default
185
    /// set to 0). For example: if record data is 20 bytes long and you only need to set the 4 last bytes as integer
186
    /// then use this method like this: setValue<int>(num, 16)
187
    /// @return True if value was set successfully or false if the size of T is larger than the record data size
188
    template <typename T> bool setValue(T newValue, int valueOffset = 0)
189
    {
190
      static_assert(std::is_trivially_copyable<T>::value && !std::is_pointer<T>::value,
191
                    "TLVRecord::setValue<T>() requires T to be a non-pointer, trivially copyable type");
192
193
      if (getDataSize() < sizeof(T))
194
      {
195
        return false;
196
      }
197
198
      memcpy(m_Data->recordValue + getValueOffset() + valueOffset, &newValue, sizeof(T));
199
      return true;
200
    }
201
202
    /// @return The total size of the TLV record (in bytes)
203
    virtual size_t getTotalSize() const = 0;
204
205
    /// @return The size of the record value (meaning the size of the 'V' part in TLV)
206
    virtual size_t getDataSize() const = 0;
207
208
  protected:
209
    virtual size_t getValueOffset() const
210
0
    {
211
0
      return 0;
212
0
    }
213
  };
214
215
  /// @class TLVRecordReader
216
  /// A class for reading TLV records data out of a byte stream. This class contains helper methods for retrieving and
217
  /// counting TLV records. This is a template class that expects template argument class derived from TLVRecord.
218
  template <typename TLVRecordType> class TLVRecordReader
219
  {
220
  private:
221
    mutable size_t m_RecordCount;
222
223
  public:
224
    /// A default c'tor for this class
225
    TLVRecordReader()
226
    {
227
      m_RecordCount = static_cast<size_t>(-1);
228
    }
229
230
    /// A default copy c'tor for this class
231
    TLVRecordReader(const TLVRecordReader& other)
232
    {
233
      m_RecordCount = other.m_RecordCount;
234
    }
235
236
    /// A d'tor for this class which currently does nothing
237
    virtual ~TLVRecordReader() = default;
238
239
    /// Overload of the assignment operator for this class
240
    /// @param[in] other The TLVRecordReader instance to assign
241
    TLVRecordReader& operator=(const TLVRecordReader& other)
242
    {
243
      m_RecordCount = other.m_RecordCount;
244
      return *this;
245
    }
246
247
    // cppcheck-suppress functionStatic
248
    /// Get the first TLV record out of a byte stream
249
    /// @param[in] tlvDataBasePtr A pointer to the TLV data byte stream
250
    /// @param[in] tlvDataLen The TLV data byte stream length
251
    /// @return An instance of type TLVRecordType that contains the first TLV record. If tlvDataBasePtr is nullptr
252
    /// or tlvDataLen is zero the returned TLVRecordType instance will be logically null, meaning
253
    /// TLVRecordType.isNull() will return true
254
    TLVRecordType getFirstTLVRecord(uint8_t* tlvDataBasePtr, size_t tlvDataLen) const
255
    {
256
      TLVRecordType resRec(nullptr);  // for NRVO optimization
257
      if (!TLVRecordType::canAssign(tlvDataBasePtr, tlvDataLen))
258
        return resRec;
259
260
      resRec.assign(tlvDataBasePtr);
261
      // resRec pointer is out-bounds of the TLV records memory
262
      if (resRec.getRecordBasePtr() + resRec.getTotalSize() > tlvDataBasePtr + tlvDataLen)
263
        resRec.assign(nullptr);
264
265
      // check if there are records at all and the total size is not zero
266
      if (!resRec.isNull() && (tlvDataLen == 0 || resRec.getTotalSize() == 0))
267
        resRec.assign(nullptr);
268
269
      return resRec;
270
    }
271
272
    // cppcheck-suppress [constParameterReference, functionStatic]
273
    /// Get a TLV record that follows a given TLV record in a byte stream
274
    /// @param[in] record A given TLV record
275
    /// @param[in] tlvDataBasePtr A pointer to the TLV data byte stream
276
    /// @param[in] tlvDataLen The TLV data byte stream length
277
    /// @return An instance of type TLVRecordType that wraps the record following the record given as input. If the
278
    /// input record.isNull() is true or if the next record is out of bounds of the byte stream, a logical null
279
    /// instance of TLVRecordType will be returned, meaning TLVRecordType.isNull() will return true
280
    TLVRecordType getNextTLVRecord(TLVRecordType& record, const uint8_t* tlvDataBasePtr, size_t tlvDataLen) const
281
    {
282
      TLVRecordType resRec(nullptr);  // for NRVO optimization
283
284
      if (record.isNull())
285
        return resRec;
286
287
      if (!TLVRecordType::canAssign(record.getRecordBasePtr() + record.getTotalSize(),
288
                                    tlvDataBasePtr - record.getRecordBasePtr() + tlvDataLen -
289
                                        record.getTotalSize()))
290
        return resRec;
291
292
      resRec.assign(record.getRecordBasePtr() + record.getTotalSize());
293
294
      if (resRec.getTotalSize() == 0)
295
        resRec.assign(nullptr);
296
297
      // resRec pointer is out-bounds of the TLV records memory
298
      if ((resRec.getRecordBasePtr() - tlvDataBasePtr) < 0)
299
        resRec.assign(nullptr);
300
301
      // resRec pointer is out-bounds of the TLV records memory
302
      if (!resRec.isNull() && resRec.getRecordBasePtr() + resRec.getTotalSize() > tlvDataBasePtr + tlvDataLen)
303
        resRec.assign(nullptr);
304
305
      return resRec;
306
    }
307
308
    /// Search for the first TLV record that corresponds to a given record type (the 'T' in __Type__-Length-Value)
309
    /// @param[in] recordType The record type to search for
310
    /// @param[in] tlvDataBasePtr A pointer to the TLV data byte stream
311
    /// @param[in] tlvDataLen The TLV data byte stream length
312
    /// @return An instance of type TLVRecordType that contains the result record. If record was not found a logical
313
    /// null instance of TLVRecordType will be returned, meaning TLVRecordType.isNull() will return true
314
    TLVRecordType getTLVRecord(uint32_t recordType, uint8_t* tlvDataBasePtr, size_t tlvDataLen) const
315
    {
316
      TLVRecordType curRec = getFirstTLVRecord(tlvDataBasePtr, tlvDataLen);
317
      while (!curRec.isNull())
318
      {
319
        if (curRec.getType() == recordType)
320
        {
321
          return curRec;
322
        }
323
324
        curRec = getNextTLVRecord(curRec, tlvDataBasePtr, tlvDataLen);
325
      }
326
327
      curRec.assign(nullptr);
328
      return curRec;  // for NRVO optimization
329
    }
330
331
    /// Get the TLV record count in a given TLV data byte stream. For efficiency purposes the count is being cached
332
    /// so only the first call to this method will go over all the TLV records, while all consequent calls will
333
    /// return the cached number. This implies that if there is a change in the number of records, it's the user's
334
    /// responsibility to call changeTLVRecordCount() with the record count change
335
    /// @param[in] tlvDataBasePtr A pointer to the TLV data byte stream
336
    /// @param[in] tlvDataLen The TLV data byte stream length
337
    /// @return The TLV record count
338
    size_t getTLVRecordCount(uint8_t* tlvDataBasePtr, size_t tlvDataLen) const
339
    {
340
      if (m_RecordCount != static_cast<size_t>(-1))
341
        return m_RecordCount;
342
343
      m_RecordCount = 0;
344
      TLVRecordType curRec = getFirstTLVRecord(tlvDataBasePtr, tlvDataLen);
345
      while (!curRec.isNull())
346
      {
347
        m_RecordCount++;
348
        curRec = getNextTLVRecord(curRec, tlvDataBasePtr, tlvDataLen);
349
      }
350
351
      return m_RecordCount;
352
    }
353
354
    /// As described in getTLVRecordCount(), the TLV record count is being cached for efficiency purposes. So if the
355
    /// number of TLV records change, it's the user's responsibility to call this method with the number of TLV
356
    /// records being added or removed. If records were added the change should be a positive number, or a negative
357
    /// number if records were removed
358
    /// @param[in] changedBy Number of records that were added or removed
359
    void changeTLVRecordCount(int changedBy)
360
    {
361
      if (m_RecordCount != static_cast<size_t>(-1))
362
        m_RecordCount += changedBy;
363
    }
364
  };
365
366
  /// @class TLVRecordBuilder
367
  /// A base class for building Type-Length-Value (TLV) records. This builder receives the record parameters in its
368
  /// c'tor, builds the record raw buffer and provides a method to build a TLVRecord object out of it. Please notice
369
  /// this is a base class that lacks the capability of actually building TLVRecord objects and also cannot be
370
  /// instantiated. The reason for that is that different protocols build TLV records in different ways, so these
371
  /// missing capabilities will be implemented by the derived classes which are specific to each protocol. This class
372
  /// only provides the common infrastructure that will be used by them
373
  class TLVRecordBuilder
374
  {
375
  protected:
376
    TLVRecordBuilder();
377
378
    TLVRecordBuilder(uint32_t recType, const uint8_t* recValue, uint8_t recValueLen);
379
380
    TLVRecordBuilder(uint32_t recType, uint8_t recValue);
381
382
    TLVRecordBuilder(uint32_t recType, uint16_t recValue);
383
384
    TLVRecordBuilder(uint32_t recType, uint32_t recValue);
385
386
    TLVRecordBuilder(uint32_t recType, const IPv4Address& recValue);
387
388
    TLVRecordBuilder(uint32_t recType, const std::string& recValue, bool valueIsHexString = false);
389
390
    TLVRecordBuilder(const TLVRecordBuilder& other);
391
392
    TLVRecordBuilder& operator=(const TLVRecordBuilder& other);
393
394
    virtual ~TLVRecordBuilder();
395
396
    void init(uint32_t recType, const uint8_t* recValue, size_t recValueLen);
397
398
    uint8_t* m_RecValue;
399
    size_t m_RecValueLen;
400
    uint32_t m_RecType;
401
402
  private:
403
    void copyData(const TLVRecordBuilder& other);
404
  };
405
}  // namespace pcpp