Coverage Report

Created: 2026-12-01 07:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/PcapPlusPlus/Packet++/header/BluetoothHciLayer.h
Line
Count
Source
1
#pragma once
2
3
#include "Layer.h"
4
5
#include <iterator>
6
#include <algorithm>
7
#include <vector>
8
9
/// @file
10
/// This file contains classes for parsing Bluetooth Host Controller Interface (HCI) packets.
11
/// It contains an abstract class named BluetoothHciLayer which has common functionality.
12
/// It contains inherited classes that represent the different HCI packet types, identified by the H4 packet indicator
13
/// octet. These types of packets are Command, ACL data, SCO data, Event and ISO data.
14
/// **Currently** only Event packets are implemented, by BluetoothHciEventLayer.
15
/// Instances are created through the BluetoothHciLayer::parseLayer() factory, which identifies the packet type and
16
/// constructs the matching class.
17
18
/// @namespace pcpp
19
/// @brief The main namespace for the PcapPlusPlus lib
20
namespace pcpp
21
{
22
  /// @class BluetoothHciLayer
23
  /// An abstract base class for all Bluetooth HCI packet types. It handles the parts common to every HCI packet:
24
  /// the optional direction pseudo-header and the H4 packet indicator octet. Concrete subclasses parse a specific
25
  /// packet type and are created through BluetoothHciLayer::parseLayer()
26
  class BluetoothHciLayer : public Layer
27
  {
28
  public:
29
    /// @enum BluetoothHciPacketType
30
    /// The HCI packet type, taken from the H4 packet indicator octet
31
    enum class BluetoothHciPacketType : uint8_t
32
    {
33
      /// Not a recognized HCI packet type. 0x00 is not a valid H4 packet indicator value
34
      Unknown = 0x00,
35
      /// A command sent from the host to the controller
36
      Command = 0x01,
37
      /// ACL data
38
      AclData = 0x02,
39
      /// Synchronous (SCO) data
40
      ScoData = 0x03,
41
      /// An event sent from the controller to the host
42
      Event = 0x04,
43
      /// Isochronous (ISO) data
44
      IsoData = 0x05
45
    };
46
47
    /// @enum BluetoothHciDirection
48
    /// The direction of an HCI packet, taken from the pseudo-header present in
49
    /// LINKTYPE_BLUETOOTH_HCI_H4_WITH_PHDR captures
50
    enum class BluetoothHciDirection : uint32_t
51
    {
52
      /// Sent from the host to the controller
53
      HostToController = 0,
54
      /// Received by the host from the controller
55
      ControllerToHost = 1,
56
      /// The capture has no direction pseudo-header (LINKTYPE_BLUETOOTH_HCI_H4)
57
      Unknown = 0xffffffff
58
    };
59
60
    ~BluetoothHciLayer() override = default;
61
62
    /// A static factory that identifies the HCI packet type and creates the matching layer
63
    /// @param[in] data A pointer to the raw data
64
    /// @param[in] dataLen Size of the data in bytes
65
    /// @param[in] packet A pointer to the Packet instance where layer will be stored in
66
    /// @param[in] hasDirectionHeader True if the data starts with a 4-byte direction pseudo-header
67
    /// (LINKTYPE_BLUETOOTH_HCI_H4_WITH_PHDR), false if it starts directly with the H4 packet indicator
68
    /// (LINKTYPE_BLUETOOTH_HCI_H4)
69
    /// @return An instance of a BluetoothHciLayer subclass, or nullptr if the data is invalid or the packet type
70
    /// is not supported yet
71
    static BluetoothHciLayer* parseLayer(uint8_t* data, size_t dataLen, Packet* packet, bool hasDirectionHeader);
72
73
    /// @return True if this packet is preceded by a direction pseudo-header, false otherwise
74
    bool hasDirectionHeader() const
75
0
    {
76
0
      return m_HasDirectionHeader;
77
0
    }
78
79
    /// Get the direction of this packet
80
    /// @return The packet direction, or BluetoothHciDirection::Unknown if the capture has no direction
81
    /// pseudo-header
82
    BluetoothHciDirection getDirection() const;
83
84
    /// @return The HCI packet type this layer represents, or BluetoothHciPacketType::Unknown if the packet
85
    /// indicator octet doesn't match a known packet type
86
    BluetoothHciPacketType getPacketType() const
87
0
    {
88
0
      return packetTypeFromIndicator(m_Data[getDirectionHeaderLen()]);
89
0
    }
90
91
    // implement abstract methods
92
93
    /// HCI packets don't encapsulate another protocol, so no next layer is parsed. Subclasses that do encapsulate
94
    /// another protocol override this method
95
    void parseNextLayer() override
96
0
    {}
97
98
    /// Does nothing for this layer
99
    void computeCalculateFields() override
100
0
    {}
101
102
    OsiModelLayer getOsiModelLayer() const override
103
0
    {
104
0
      return OsiModelDataLinkLayer;
105
0
    }
106
107
    /// A static method that validates the part of the input data common to all HCI packet types
108
    /// @param[in] data The pointer to the beginning of a byte stream of a Bluetooth HCI packet
109
    /// @param[in] dataLen The length of the byte stream
110
    /// @param[in] hasDirectionHeader True if the data is expected to start with a 4-byte direction pseudo-header
111
    /// @return True if the data is long enough to hold the direction pseudo-header, if one is expected, followed
112
    /// by a packet indicator octet
113
    static bool isDataValid(const uint8_t* data, size_t dataLen, bool hasDirectionHeader);
114
115
  protected:
116
    /// Size of the direction pseudo-header on the wire. Exposed to derived classes so their static
117
    /// validators can size-check the raw buffer without needing the struct definition itself
118
    static constexpr size_t directionHeaderSize = 4;
119
120
    /// A constructor that creates the layer from an existing packet raw data
121
    /// @param[in] data A pointer to the raw data
122
    /// @param[in] dataLen Size of the data in bytes
123
    /// @param[in] packet A pointer to the Packet instance where layer will be stored in
124
    /// @param[in] hasDirectionHeader True if the data starts with a 4-byte direction pseudo-header
125
    BluetoothHciLayer(uint8_t* data, size_t dataLen, Packet* packet, bool hasDirectionHeader)
126
0
        : Layer(data, dataLen, nullptr, packet, BluetoothHCI), m_HasDirectionHeader(hasDirectionHeader)
127
0
    {}
128
129
    /// Constructor used by subclasses that will allocate their own buffer via allocData()
130
    /// @param[in] hasDirectionHeader True if the buffer will include a 4-byte direction pseudo-header
131
0
    explicit BluetoothHciLayer(bool hasDirectionHeader) : m_HasDirectionHeader(hasDirectionHeader)
132
0
    {
133
0
      m_Protocol = BluetoothHCI;
134
0
    }
135
136
    /// @return Size of the direction pseudo-header, or 0 if this packet has none
137
    size_t getDirectionHeaderLen() const
138
0
    {
139
0
      return m_HasDirectionHeader ? directionHeaderSize : 0;
140
0
    }
141
142
  private:
143
#pragma pack(push, 1)
144
    struct bluetooth_hci_direction_header
145
    {
146
      uint32_t direction;
147
    };
148
#pragma pack(pop)
149
    static_assert(sizeof(bluetooth_hci_direction_header) == directionHeaderSize,
150
                  "bluetooth_hci_direction_header size does not match directionHeaderSize");
151
152
    static BluetoothHciPacketType packetTypeFromIndicator(uint8_t packetIndicator);
153
154
    bool m_HasDirectionHeader;
155
  };
156
157
  /// @class BluetoothHciEventLayer
158
  /// Represents a Bluetooth HCI Event packet, identified by the H4 packet indicator octet 0x04
159
  class BluetoothHciEventLayer : public BluetoothHciLayer
160
  {
161
    friend BluetoothHciLayer* BluetoothHciLayer::parseLayer(uint8_t* data, size_t dataLen, Packet* packet,
162
                                                            bool hasDirectionHeader);
163
164
  public:
165
    ~BluetoothHciEventLayer() override = default;
166
167
    /// Construct a new Event layer with no direction pseudo-header, suitable for serialization to
168
    /// LINKTYPE_BLUETOOTH_HCI_H4 captures
169
    /// @param[in] eventCode The HCI event code
170
    /// @param[in] parameters The raw parameter bytes. Must contain at most 255 bytes
171
    /// @throw std::invalid_argument if parameters contains more than 255 bytes
172
    explicit BluetoothHciEventLayer(uint8_t eventCode, const std::vector<uint8_t>& parameters = {});
173
174
    /// Construct a new Event layer prefixed with the 4-byte direction pseudo-header, suitable for serialization
175
    /// to LINKTYPE_BLUETOOTH_HCI_H4_WITH_PHDR captures
176
    /// @param[in] direction The packet direction
177
    /// @param[in] eventCode The HCI event code
178
    /// @param[in] parameters The raw parameter bytes. Must contain at most 255 bytes
179
    /// @throw std::invalid_argument if direction is not HostToController or ControllerToHost, or if parameters
180
    /// contains more than 255 bytes
181
    BluetoothHciEventLayer(BluetoothHciDirection direction, uint8_t eventCode,
182
                           const std::vector<uint8_t>& parameters = {});
183
184
    /// Get the event code of this packet
185
    /// @return The event code
186
    uint8_t getEventCode() const
187
0
    {
188
0
      return getEventHeader()->eventCode;
189
0
    }
190
191
    /// Set the event code of this packet
192
    /// @param[in] eventCode The new event code
193
    void setEventCode(uint8_t eventCode)
194
0
    {
195
0
      getEventHeader()->eventCode = eventCode;
196
0
    }
197
198
    /// Get the parameter total length. If the packet is truncated, i.e. the parameterTotalLength field is
199
    /// larger than the number of parameter bytes actually present, the number of bytes present is returned
200
    /// @return The parameter total length, in bytes
201
    uint8_t getParameterTotalLength() const;
202
203
    /// Get a pointer to the raw event parameters
204
    /// @return A pointer to the raw parameter bytes
205
    uint8_t* getParameters() const
206
0
    {
207
0
      return m_Data + getDirectionHeaderLen() + sizeof(uint8_t) + sizeof(bluetooth_hci_event_header);
208
0
    }
209
210
    /// Replace the parameter bytes of this packet. The parameterTotalLength field is updated to match
211
    /// @param[in] parameters The new parameter bytes. Must contain at most 255 bytes
212
    /// @throw std::invalid_argument if parameters contains more than 255 bytes
213
    /// @throw std::runtime_error if the layer could not be extended or shortened to fit the new parameters
214
    void setParameters(const std::vector<uint8_t>& parameters);
215
216
    // implement abstract methods
217
218
    /// @return The entire data length. HCI Event packets don't encapsulate another protocol, so the whole buffer
219
    /// is treated as the header
220
    size_t getHeaderLen() const override
221
0
    {
222
0
      return m_DataLen;
223
0
    }
224
225
    std::string toString() const override;
226
227
    /// A static method that validates the input data
228
    /// @param[in] data The pointer to the beginning of a byte stream of a Bluetooth HCI Event packet
229
    /// @param[in] dataLen The length of the byte stream
230
    /// @param[in] hasDirectionHeader True if the data is expected to start with a 4-byte direction pseudo-header
231
    /// @return True if the data is valid and can represent a Bluetooth HCI Event packet
232
    static bool isDataValid(const uint8_t* data, size_t dataLen, bool hasDirectionHeader);
233
234
    /// @struct SerializedFields
235
    /// Fields written by BluetoothHciEventLayer's serializeLayer(), in addition to Layer::SerializedFields
236
    struct SerializedFields : Layer::SerializedFields
237
    {
238
      /// @return All field descriptors for BluetoothHciEventLayer
239
      static std::vector<FieldDescriptor> all()
240
0
      {
241
0
        auto result = Layer::SerializedFields::all();
242
0
        std::initializer_list<FieldDescriptor> extra{ Direction, EventCode, ParameterTotalLength };
243
0
        std::copy(extra.begin(), extra.end(), std::back_inserter(result));
244
0
        return result;
245
0
      }
246
247
      /// @brief Packet direction, as "HostToController", "ControllerToHost", or "Unknown"
248
      static const FieldDescriptor Direction;
249
250
      /// @brief HCI event code
251
      static const FieldDescriptor EventCode;
252
253
      /// @brief Length of the parameter bytes
254
      static const FieldDescriptor ParameterTotalLength;
255
    };
256
257
  protected:
258
    void serializeLayer(ObjectScope& serializer) const override;
259
260
  private:
261
#pragma pack(push, 1)
262
    struct bluetooth_hci_event_header
263
    {
264
      uint8_t eventCode;
265
      uint8_t parameterTotalLength;
266
    };
267
#pragma pack(pop)
268
    static_assert(sizeof(bluetooth_hci_event_header) == 2, "bluetooth_hci_event_header size is not 2 bytes");
269
270
    /// A constructor that creates the layer from an existing packet raw data. Instances are only created through
271
    /// BluetoothHciLayer::parseLayer()
272
    /// @param[in] data A pointer to the raw data
273
    /// @param[in] dataLen Size of the data in bytes
274
    /// @param[in] packet A pointer to the Packet instance where layer will be stored in
275
    /// @param[in] hasDirectionHeader True if the data starts with a 4-byte direction pseudo-header
276
    BluetoothHciEventLayer(uint8_t* data, size_t dataLen, Packet* packet, bool hasDirectionHeader)
277
0
        : BluetoothHciLayer(data, dataLen, packet, hasDirectionHeader)
278
0
    {}
279
280
    /// Shared construction logic used by both public constructors. Allocates the buffer, writes the packet
281
    /// indicator octet, event header and parameter bytes. The direction pseudo-header, when present, must be
282
    /// written separately by the caller
283
    /// @throw std::invalid_argument if parameters contains more than 255 bytes
284
    void initLayer(uint8_t eventCode, const std::vector<uint8_t>& parameters);
285
286
    bluetooth_hci_event_header* getEventHeader() const
287
0
    {
288
0
      return reinterpret_cast<bluetooth_hci_event_header*>(m_Data + getDirectionHeaderLen() + sizeof(uint8_t));
289
0
    }
290
  };
291
292
}  // namespace pcpp