Coverage Report

Created: 2026-12-01 07:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/PcapPlusPlus/Packet++/header/BgpLayer.h
Line
Count
Source
1
#pragma once
2
3
#include <vector>
4
#include "Layer.h"
5
#include "IpAddress.h"
6
7
/// @file
8
/// This file contains classes for parsing, creating and editing Border Gateway Protocol (BGP) version 4 packets.
9
/// It contains an abstract class named BgpLayer which has common functionality and 5 inherited classes that
10
/// represent the different BGP message types: OPEN, UPDATE, NOTIFICATION, KEEPALIVE and ROUTE-REFRESH.
11
/// Each of these classes contains unique functionality for parsing. creating and editing of these message.
12
13
/// @namespace pcpp
14
/// @brief The main namespace for the PcapPlusPlus lib
15
namespace pcpp
16
{
17
18
  /// @class BgpLayer
19
  /// Represents Border Gateway Protocol (BGP) v4 protocol layer. This is an abstract class that cannot be
20
  /// instantiated, and contains functionality which is common to all BGP message types.
21
  class BgpLayer : public Layer
22
  {
23
  public:
24
    /// An enum representing BGP message types
25
    enum BgpMessageType
26
    {
27
      /// BGP OPEN message
28
      Open = 1,
29
      /// BGP UPDATE message
30
      Update = 2,
31
      /// BGP NOTIFICATION message
32
      Notification = 3,
33
      /// BGP KEEPALIVE message
34
      Keepalive = 4,
35
      /// BGP ROUTE-REFRESH message
36
      RouteRefresh = 5,
37
    };
38
39
#pragma pack(push, 1)
40
    /// @struct bgp_common_header
41
    /// Represents the common fields of a BGP 4 message
42
    struct bgp_common_header
43
    {
44
      /// 16-octet marker
45
      uint8_t marker[16];
46
      /// Total length of the message, including the header
47
      uint16_t length;
48
      /// BGP message type
49
      uint8_t messageType;
50
    };
51
#pragma pack(pop)
52
    static_assert(sizeof(bgp_common_header) == 19, "bgp_common_header size is not 19 bytes");
53
54
    /// @return BGP message type
55
    virtual BgpMessageType getBgpMessageType() const = 0;
56
57
    /// @return BGP message type as string. Return value can be one of the following:
58
    /// "OPEN", "UPDATE", "NOTIFICATION", "KEEPALIVE", "ROUTE-REFRESH", "Unknown"
59
    std::string getMessageTypeAsString() const;
60
61
    /// A static method that checks whether a source or dest port match those associated with the BGP protocol
62
    /// @param[in] portSrc Source port number to check
63
    /// @param[in] portDst Dest port number to check
64
    /// @return True if the source or dest port match those associated with the BGP protocol
65
    static bool isBgpPort(uint16_t portSrc, uint16_t portDst)
66
0
    {
67
0
      return portSrc == 179 || portDst == 179;
68
0
    }
69
70
    /// A method that creates a BGP layer from packet raw data
71
    /// @param[in] data A pointer to the raw data
72
    /// @param[in] dataLen Size of the data in bytes
73
    /// @param[in] prevLayer A pointer to the previous layer
74
    /// @param[in] packet A pointer to the Packet instance where layer will be stored
75
    /// @return A newly allocated BGP layer of one of the following types (according to the message type):
76
    /// BgpOpenMessageLayer, BgpUpdateMessageLayer, BgpNotificationMessageLayer, BgpKeepaliveMessageLayer,
77
    /// BgpRouteRefreshMessageLayer
78
    static BgpLayer* parseBgpLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet);
79
80
    // implement abstract methods
81
82
    /// @return The size of the BGP message
83
    size_t getHeaderLen() const override;
84
85
    /// Multiple BGP messages can reside in a single packet, and the only layer that can come after a BGP message
86
    /// is another BGP message. This method checks for remaining data and parses it as another BGP layer
87
    void parseNextLayer() override;
88
89
    std::string toString() const override;
90
91
    OsiModelLayer getOsiModelLayer() const override
92
0
    {
93
0
      return OsiModelApplicationLayer;
94
0
    }
95
96
    /// @struct SerializedFields
97
    /// Fields written by BgpLayer's serializeLayer(), in addition to
98
    /// Layer::SerializedFields.
99
    struct SerializedFields : Layer::SerializedFields
100
    {
101
      /// @return All field descriptors for BgpLayer
102
      static std::vector<FieldDescriptor> all()
103
0
      {
104
0
        auto result = Layer::SerializedFields::all();
105
0
        std::initializer_list<FieldDescriptor> extra{ MessageType };
106
0
        std::copy(extra.begin(), extra.end(), std::back_inserter(result));
107
0
        return result;
108
0
      }
109
110
      /// @brief BGP message type, one of: "OPEN", "UPDATE", "NOTIFICATION", "KEEPALIVE", "ROUTE-REFRESH"
111
      static const FieldDescriptor MessageType;
112
113
      // cppcheck-suppress duplInheritedMember
114
      /// Maximum field ID used by the layer.
115
      static constexpr uint16_t MaxID = Layer::SerializedFields::MaxID + 1;
116
    };
117
118
    /// Calculates the basic BGP fields:
119
    /// - Set marker to all ones
120
    /// - Set message type value
121
    /// - Set message length
122
    void computeCalculateFields() override;
123
124
  protected:
125
    void serializeLayer(ObjectScope& serializer) const override;
126
127
    // protected c'tors, this class cannot be instantiated by users
128
    BgpLayer()
129
0
    {}
130
    BgpLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet)
131
0
        : Layer(data, dataLen, prevLayer, packet, BGP)
132
0
    {}
133
134
    bgp_common_header* getBasicHeader() const
135
0
    {
136
0
      return reinterpret_cast<bgp_common_header*>(m_Data);
137
0
    }
138
139
    void setBgpFields(size_t messageLen = 0);
140
141
    bool extendLayer(int offsetInLayer, size_t numOfBytesToExtend) override;
142
143
    bool shortenLayer(int offsetInLayer, size_t numOfBytesToShorten) override;
144
  };
145
146
  /// @class BgpOpenMessageLayer
147
  /// Represents a BGP v4 OPEN message
148
  class BgpOpenMessageLayer : public BgpLayer
149
  {
150
  public:
151
#pragma pack(push, 1)
152
    /// @struct bgp_open_message
153
    /// BGP OPEN message structure
154
    typedef struct bgp_open_message : bgp_common_header
155
    {
156
      /// BGP version number
157
      uint8_t version;
158
      /// Autonomous System number of the sender
159
      uint16_t myAutonomousSystem;
160
      /// The number of seconds the sender proposes for the value of the Hold Timer
161
      uint16_t holdTime;
162
      /// BGP Identifier of the sender
163
      uint32_t bgpId;
164
      /// The total length of the Optional Parameters field
165
      uint8_t optionalParameterLength;
166
    } bgp_open_message;
167
#pragma pack(pop)
168
169
    /// @struct optional_parameter
170
    /// A structure that represents BGP OPEN message optional parameters
171
    struct optional_parameter
172
    {
173
      /// Parameter type
174
      uint8_t type = 0;
175
      /// Parameter length
176
      uint8_t length = 0;
177
      /// Parameter data
178
      uint8_t value[32] = {};
179
180
      /// A default c'tor that zeroes all data
181
0
      optional_parameter() = default;
182
183
      /// A c'tor that initializes the values of the struct
184
      /// @param[in] typeVal Parameter type value
185
      /// @param[in] valueAsHexString Parameter data as hex string. The length field will be set accordingly.
186
      /// If this parameter is not a valid hex string the data will remain zeroed and length will be also zero
187
      optional_parameter(uint8_t typeVal, const std::string& valueAsHexString);
188
    };
189
190
    /// A constructor that creates the layer from an existing packet raw data
191
    /// @param[in] data A pointer to the raw data
192
    /// @param[in] dataLen Size of the data in bytes
193
    /// @param[in] prevLayer A pointer to the previous layer
194
    /// @param[in] packet A pointer to the Packet instance where layer will be stored in
195
    BgpOpenMessageLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet)
196
0
        : BgpLayer(data, dataLen, prevLayer, packet)
197
0
    {}
198
199
    /// A static method that takes a byte array and detects whether it is a BgpOpenMessage
200
    /// @param[in] data A byte array
201
    /// @param[in] dataSize The byte array size (in bytes)
202
    /// @return True if the data looks like a valid BgpOpenMessage layer
203
    static bool isDataValid(const uint8_t* data, size_t dataSize);
204
205
    /// A c'tor that creates a new BGP OPEN message
206
    /// @param[in] myAutonomousSystem The Autonomous System number of the sender
207
    /// @param[in] holdTime The number of seconds the sender proposes for the value of the Hold Timer
208
    /// @param[in] bgpId The BGP Identifier of the sender
209
    /// @param[in] optionalParams A vector of optional parameters. This parameter is optional and if not provided no
210
    /// parameters will be set on the message
211
    /// @throws std::invalid_argument if an optional parameter is invalid or the serialized data exceeds 255 bytes
212
    BgpOpenMessageLayer(uint16_t myAutonomousSystem, uint16_t holdTime, const IPv4Address& bgpId,
213
                        const std::vector<optional_parameter>& optionalParams = std::vector<optional_parameter>());
214
215
    /// Get a pointer to the open message data. Notice this points directly to the data, so any change will modify
216
    /// the actual packet data
217
    /// @return A pointer to a bgp_open_message structure containing the data
218
    bgp_open_message* getOpenMsgHeader() const
219
0
    {
220
0
      return reinterpret_cast<bgp_open_message*>(m_Data);
221
0
    }
222
223
    /// @return The BGP identifier as IPv4Address object
224
    IPv4Address getBgpId() const
225
0
    {
226
0
      return IPv4Address(getOpenMsgHeader()->bgpId);
227
0
    }
228
229
    /// Set the BGP identifier
230
    /// @param[in] newBgpId BGP identifier to set. If value is not a valid IPv4 address it won't be set
231
    void setBgpId(const IPv4Address& newBgpId);
232
233
    /// Get a vector of the optional parameters in the message
234
    /// @param[out] optionalParameters The vector where the optional parameters will be written to. This method
235
    /// doesn't remove any existing data on this vector before pushing data to it
236
    void getOptionalParameters(std::vector<optional_parameter>& optionalParameters) const;
237
238
    /// @return The length in [bytes] of the optional parameters data in the message
239
    size_t getOptionalParametersLength();
240
241
    /// Set optional parameters in the message. This method will override all existing optional parameters currently
242
    /// in the message. If the input is an empty vector all optional parameters will be cleared. This method
243
    /// automatically sets the bgp_common_header#length and the bgp_open_message#optionalParameterLength fields on
244
    /// the message
245
    /// @param[in] optionalParameters A vector of new optional parameters to set in the message
246
    /// @return True if all optional parameters were set successfully or false otherwise. In case of an error an
247
    /// appropriate message will be printed to log
248
    bool setOptionalParameters(const std::vector<optional_parameter>& optionalParameters);
249
250
    /// Clear all optional parameters currently in the message. This is equivalent to calling
251
    /// setOptionalParameters() with an empty vector as a parameter
252
    /// @return True if all optional parameters were successfully cleared or false otherwise. In case of an error an
253
    /// appropriate message will be printed to log
254
    bool clearOptionalParameters();
255
256
    // implement abstract methods
257
258
    BgpMessageType getBgpMessageType() const override
259
0
    {
260
0
      return BgpLayer::Open;
261
0
    }
262
263
    /// @struct SerializedFields
264
    /// Fields written by BgpOpenMessageLayer's serializeLayer(), in addition to
265
    /// BgpLayer::SerializedFields.
266
    struct SerializedFields : BgpLayer::SerializedFields
267
    {
268
      /// @return All field descriptors for BgpOpenMessageLayer
269
      static std::vector<FieldDescriptor> all()
270
0
      {
271
0
        auto result = BgpLayer::SerializedFields::all();
272
0
        std::initializer_list<FieldDescriptor> extra{ Version, MyAutonomousSystem, HoldTime, BgpId,
273
0
                                                    OptionalParameters };
274
0
        std::copy(extra.begin(), extra.end(), std::back_inserter(result));
275
0
        return result;
276
0
      }
277
278
      /// @brief BGP version number
279
      static const FieldDescriptor Version;
280
281
      /// @brief Autonomous System number of the sender, in host byte order
282
      static const FieldDescriptor MyAutonomousSystem;
283
284
      /// @brief Hold Timer value proposed by the sender, in host byte order
285
      static const FieldDescriptor HoldTime;
286
287
      /// @brief BGP identifier of the sender, as an IPv4 address string
288
      static const FieldDescriptor BgpId;
289
290
      /// @brief Optional parameters as an array of {type, length} objects
291
      static const FieldDescriptor OptionalParameters;
292
293
      // cppcheck-suppress duplInheritedMember
294
      /// Maximum field ID used by the layer.
295
      static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 5;
296
297
      /// @struct OptionalParameterObject
298
      /// Fields of a single BGP OPEN optional parameter.
299
      struct OptionalParameterObject : ObjectFieldDescriptor<OptionalParameterObject>
300
      {
301
        using ObjectFieldDescriptor::ObjectFieldDescriptor;
302
303
        /// @return All field descriptors for an optional parameter
304
        static std::vector<FieldDescriptor> all()
305
0
        {
306
0
          return { Type, Length };
307
0
        }
308
309
        /// @brief Parameter type
310
        static const FieldDescriptor Type;
311
312
        /// @brief Parameter length, in bytes
313
        static const FieldDescriptor Length;
314
      };
315
316
      /// @brief Single optional parameter element (used as the array item type)
317
      static const OptionalParameterObject OptionalParameter;
318
    };
319
320
  protected:
321
    void serializeLayer(ObjectScope& serializer) const override;
322
323
  private:
324
    /// Serializes the optional parameters to a byte array
325
    /// @throws std::invalid_argument if an optional parameter is invalid or the serialized data doesn't fit in
326
    /// maxByteArrSize bytes
327
    size_t optionalParamsToByteArray(const std::vector<optional_parameter>& optionalParams, uint8_t* resultByteArr,
328
                                     size_t maxByteArrSize);
329
  };
330
331
  /// @class BgpUpdateMessageLayer
332
  /// Represents a BGP v4 UPDATE message
333
  class BgpUpdateMessageLayer : public BgpLayer
334
  {
335
  public:
336
    /// @struct prefix_and_ip
337
    /// A structure that contains IPv4 address and IP address mask (prefix) information.
338
    /// It's used to represent BGP Withdrawn Routes and Network Layer Reachability Information (NLRI)
339
    struct prefix_and_ip
340
    {
341
      /// IPv4 address mask, must contain one of the values: 8, 16, 24, 32
342
      uint8_t prefix;
343
      /// IPv4 address
344
      IPv4Address ipAddr;
345
346
      /// A default c'tor that zeroes all data
347
0
      prefix_and_ip() : prefix(0), ipAddr(IPv4Address::Zero)
348
0
      {}
349
350
      /// A c'tor that initializes the values of the struct
351
      /// @param[in] prefixVal IPv4 address mask value
352
      /// @param[in] ipAddrVal IPv4 address
353
      prefix_and_ip(uint8_t prefixVal, const std::string& ipAddrVal) : prefix(prefixVal), ipAddr(ipAddrVal)
354
0
      {}
355
    };
356
357
    /// @struct path_attribute
358
    /// A structure that represents BGP OPEN message Path Attributes information
359
    struct path_attribute
360
    {
361
      /// Path attribute flags
362
      uint8_t flags;
363
      /// Path attribute type
364
      uint8_t type;
365
      /// Path attribute length
366
      uint8_t length;
367
      /// Path attribute data. Max supported data length is 32 bytes
368
      uint8_t data[32];
369
370
      // FIXME: This does not actually zero the data.
371
      /// A default c'tor that zeroes all data
372
      path_attribute()
373
0
      {}
374
375
      /// A c'tor that initializes the values of the struct
376
      /// @param[in] flagsVal Path attribute flags value
377
      /// @param[in] typeVal Path attribute type value
378
      /// @param[in] dataAsHexString Path attribute data as hex string. The path_attribute#length field will be
379
      /// set accordingly. If this parameter is not a valid hex string the data will remain zeroed and length will
380
      /// be also set to zero
381
      path_attribute(uint8_t flagsVal, uint8_t typeVal, const std::string& dataAsHexString);
382
    };
383
384
    /// A constructor that creates the layer from an existing packet raw data
385
    /// @param[in] data A pointer to the raw data
386
    /// @param[in] dataLen Size of the data in bytes
387
    /// @param[in] prevLayer A pointer to the previous layer
388
    /// @param[in] packet A pointer to the Packet instance where layer will be stored in
389
    BgpUpdateMessageLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet)
390
0
        : BgpLayer(data, dataLen, prevLayer, packet)
391
0
    {}
392
393
    /// A static method that takes a byte array and detects whether it is a BgpUpdateMessage
394
    /// @param[in] data A byte array
395
    /// @param[in] dataSize The byte array size (in bytes)
396
    /// @return True if the data looks like a valid BgpUpdateMessage layer
397
    static bool isDataValid(const uint8_t* data, size_t dataSize);
398
399
    /// A c'tor that creates a new BGP UPDATE message
400
    /// @param[in] withdrawnRoutes A vector of withdrawn routes data. If left empty (which is the default value) no
401
    /// withdrawn route information will be written to the message
402
    /// @param[in] pathAttributes A vector of path attributes data. If left empty (which is the default value) no
403
    /// path attribute information will be written to the message
404
    /// @param[in] nlri A vector of network layer reachability data. If left empty (which is the default value) no
405
    /// reachability information will be written to the message
406
    explicit BgpUpdateMessageLayer(
407
        const std::vector<prefix_and_ip>& withdrawnRoutes = std::vector<prefix_and_ip>(),
408
        const std::vector<path_attribute>& pathAttributes = std::vector<path_attribute>(),
409
        const std::vector<prefix_and_ip>& nlri = std::vector<prefix_and_ip>());
410
411
    /// Get a pointer to the basic BGP message data. Notice this points directly to the data, so any change will
412
    /// modify the actual packet data
413
    /// @return A pointer to a bgp_common_header structure containing the data
414
    bgp_common_header* getBasicMsgHeader() const
415
0
    {
416
0
      return reinterpret_cast<bgp_common_header*>(m_Data);
417
0
    }
418
419
    /// @return The size in [bytes] of the Withdrawn Routes data
420
    size_t getWithdrawnRoutesLength() const;
421
422
    /// Get a vector of the Withdrawn Routes currently in the message
423
    /// @param[out] withdrawnRoutes A reference to a vector the Withdrawn Routes data will be written to
424
    void getWithdrawnRoutes(std::vector<prefix_and_ip>& withdrawnRoutes) const;
425
426
    /// Set Withdrawn Routes in this message. This method will override any existing Withdrawn Routes in the
427
    /// message. If the input is an empty vector all Withdrawn Routes will be removed. This method automatically
428
    /// sets the bgp_common_header#length and the Withdrawn Routes length fields in the message
429
    /// @param[in] withdrawnRoutes New Withdrawn Routes to set in the message
430
    /// @return True if all Withdrawn Routes were set successfully or false otherwise. In case of an error an
431
    /// appropriate message will be printed to log
432
    bool setWithdrawnRoutes(const std::vector<prefix_and_ip>& withdrawnRoutes);
433
434
    /// Clear all Withdrawn Routes data currently in the message. This is equivalent to calling setWithdrawnRoutes()
435
    /// with an empty vector as a parameter
436
    /// @return True if all Withdrawn Routes were successfully cleared or false otherwise. In case of an error an
437
    /// appropriate message will be printed to log
438
    bool clearWithdrawnRoutes();
439
440
    /// @return The size in [bytes] of the Path Attributes data
441
    size_t getPathAttributesLength() const;
442
443
    /// Get a vector of the Path Attributes currently in the message
444
    /// @param[out] pathAttributes A reference to a vector the Path Attributes data will be written to
445
    void getPathAttributes(std::vector<path_attribute>& pathAttributes) const;
446
447
    /// Set Path Attributes in this message. This method will override any existing Path Attributes in the message.
448
    /// If the input is an empty vector all Path Attributes will be removed. This method automatically sets the
449
    /// bgp_common_header#length and the Path Attributes length fields in the message
450
    /// @param[in] pathAttributes New Path Attributes to set in the message
451
    /// @return True if all Path Attributes were set successfully or false otherwise. In case of an error an
452
    /// appropriate message will be printed to log
453
    bool setPathAttributes(const std::vector<path_attribute>& pathAttributes);
454
455
    /// Clear all Path Attributes data currently in the message. This is equivalent to calling setPathAttributes()
456
    /// with an empty vector as a parameter
457
    /// @return True if all Path Attributes were successfully cleared or false otherwise. In case of an error an
458
    /// appropriate message will be printed to log
459
    bool clearPathAttributes();
460
461
    /// @return The size in [bytes] of the Network Layer Reachability Info
462
    size_t getNetworkLayerReachabilityInfoLength() const;
463
464
    /// Get a vector of the Network Layer Reachability Info currently in the message
465
    /// @param[out] nlri A reference to a vector the NLRI data will be written to
466
    void getNetworkLayerReachabilityInfo(std::vector<prefix_and_ip>& nlri) const;
467
468
    /// Set NLRI data in this message. This method will override any existing NLRI data in the message.
469
    /// If the input is an empty vector all NLRI data will be removed. This method automatically sets the
470
    /// bgp_common_header#length field in the message
471
    /// @param[in] nlri New NLRI data to set in the message
472
    /// @return True if all NLRI data was set successfully or false otherwise. In case of an error an appropriate
473
    /// message will be printed to log
474
    bool setNetworkLayerReachabilityInfo(const std::vector<prefix_and_ip>& nlri);
475
476
    /// Clear all NLRI data currently in the message. This is equivalent to calling
477
    /// setNetworkLayerReachabilityInfo() with an empty vector as a parameter
478
    /// @return True if all NLRI were successfully cleared or false otherwise. In case of an error an appropriate
479
    /// message will be printed to log
480
    bool clearNetworkLayerReachabilityInfo();
481
482
    // implement abstract methods
483
484
    BgpMessageType getBgpMessageType() const override
485
0
    {
486
0
      return BgpLayer::Update;
487
0
    }
488
489
    /// @struct SerializedFields
490
    /// Fields written by BgpUpdateMessageLayer's serializeLayer(), in addition to
491
    /// BgpLayer::SerializedFields.
492
    struct SerializedFields : BgpLayer::SerializedFields
493
    {
494
      /// @return All field descriptors for BgpUpdateMessageLayer
495
      static std::vector<FieldDescriptor> all()
496
0
      {
497
0
        auto result = BgpLayer::SerializedFields::all();
498
0
        std::initializer_list<FieldDescriptor> extra{ WithdrawnRoutes, PathAttributes,
499
0
                                                    NetworkLayerReachabilityInfo };
500
0
        std::copy(extra.begin(), extra.end(), std::back_inserter(result));
501
0
        return result;
502
0
      }
503
504
      /// @brief Withdrawn routes as an array of {prefix, ipAddr} objects
505
      static const FieldDescriptor WithdrawnRoutes;
506
507
      /// @brief Path attributes as an array of {flags, type, length} objects
508
      static const FieldDescriptor PathAttributes;
509
510
      /// @brief Network Layer Reachability Information as an array of {prefix, ipAddr} objects
511
      static const FieldDescriptor NetworkLayerReachabilityInfo;
512
513
      // cppcheck-suppress duplInheritedMember
514
      /// Maximum field ID used by the layer.
515
      static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 3;
516
517
      /// @struct PrefixAndIpObject
518
      /// Fields of a single IPv4 prefix + address pair.
519
      struct PrefixAndIpObject : ObjectFieldDescriptor<PrefixAndIpObject>
520
      {
521
        using ObjectFieldDescriptor::ObjectFieldDescriptor;
522
523
        /// @return All field descriptors for a prefix + IP pair
524
        static std::vector<FieldDescriptor> all()
525
0
        {
526
0
          return { Prefix, IpAddr };
527
0
        }
528
529
        /// @brief IPv4 address mask (8, 16, 24 or 32)
530
        static const FieldDescriptor Prefix;
531
532
        /// @brief IPv4 address as a string
533
        static const FieldDescriptor IpAddr;
534
      };
535
536
      /// @brief Single withdrawn route element (used as the array item type)
537
      static const PrefixAndIpObject WithdrawnRoute;
538
539
      /// @struct PathAttributeObject
540
      /// Fields of a single BGP path attribute.
541
      struct PathAttributeObject : ObjectFieldDescriptor<PathAttributeObject>
542
      {
543
        using ObjectFieldDescriptor::ObjectFieldDescriptor;
544
545
        /// @return All field descriptors for a path attribute
546
        static std::vector<FieldDescriptor> all()
547
0
        {
548
0
          return { Flags, Type, Length };
549
0
        }
550
551
        /// @brief Path attribute flags
552
        static const FieldDescriptor Flags;
553
554
        /// @brief Path attribute type
555
        static const FieldDescriptor Type;
556
557
        /// @brief Path attribute length, in bytes
558
        static const FieldDescriptor Length;
559
      };
560
561
      /// @brief Single path attribute element (used as the array item type)
562
      static const PathAttributeObject PathAttribute;
563
564
      /// @brief Single NLRI element (used as the array item type)
565
      static const PrefixAndIpObject Nlri;
566
    };
567
568
  protected:
569
    void serializeLayer(ObjectScope& serializer) const override;
570
571
  private:
572
    void parsePrefixAndIPData(uint8_t* dataPtr, size_t dataLen, std::vector<prefix_and_ip>& result) const;
573
574
    size_t prefixAndIPDataToByteArray(const std::vector<prefix_and_ip>& prefixAndIpData, uint8_t* resultByteArr,
575
                                      size_t maxByteArrSize);
576
577
    size_t pathAttributesToByteArray(const std::vector<path_attribute>& pathAttributes, uint8_t* resultByteArr,
578
                                     size_t maxByteArrSize);
579
  };
580
581
  /// @class BgpNotificationMessageLayer
582
  /// Represents a BGP v4 NOTIFICATION message
583
  class BgpNotificationMessageLayer : public BgpLayer
584
  {
585
  public:
586
#pragma pack(push, 1)
587
    /// @struct bgp_notification_message
588
    /// BGP NOTIFICATION message structure
589
    typedef struct bgp_notification_message : bgp_common_header
590
    {
591
      /// BGP notification error code
592
      uint8_t errorCode;
593
      /// BGP notification error sub-code
594
      uint8_t errorSubCode;
595
    } bgp_notification_message;
596
#pragma pack(pop)
597
598
    /// A constructor that creates the layer from an existing packet raw data
599
    /// @param[in] data A pointer to the raw data
600
    /// @param[in] dataLen Size of the data in bytes
601
    /// @param[in] prevLayer A pointer to the previous layer
602
    /// @param[in] packet A pointer to the Packet instance where layer will be stored in
603
    BgpNotificationMessageLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet)
604
0
        : BgpLayer(data, dataLen, prevLayer, packet)
605
0
    {}
606
607
    /// A c'tor that creates a new BGP NOTIFICATION message
608
    /// @param[in] errorCode BGP notification error code
609
    /// @param[in] errorSubCode BGP notification error sub code
610
    BgpNotificationMessageLayer(uint8_t errorCode, uint8_t errorSubCode);
611
612
    /// A c'tor that creates a new BGP Notification message
613
    /// @param[in] errorCode BGP notification error code
614
    /// @param[in] errorSubCode BGP notification error sub code
615
    /// @param[in] notificationData A byte array that contains the notification data
616
    /// @param[in] notificationDataLen The size of the byte array that contains the notification data
617
    BgpNotificationMessageLayer(uint8_t errorCode, uint8_t errorSubCode, const uint8_t* notificationData,
618
                                size_t notificationDataLen);
619
620
    /// A c'tor that creates a new BGP Notification message
621
    /// @param[in] errorCode BGP notification error code
622
    /// @param[in] errorSubCode BGP notification error sub code
623
    /// @param[in] notificationData A hex string that contains the notification data. This string will be converted
624
    /// to a byte array that will be added to the message. If the input isn't a valid hex string notification data
625
    /// will remain empty and an error will be printed to log
626
    BgpNotificationMessageLayer(uint8_t errorCode, uint8_t errorSubCode, const std::string& notificationData);
627
628
    /// Get a pointer to the notification message data. Notice this points directly to the data, so any change will
629
    /// modify the actual packet data
630
    /// @return A pointer to a bgp_notification_message structure containing the data
631
    bgp_notification_message* getNotificationMsgHeader() const
632
0
    {
633
0
      return reinterpret_cast<bgp_notification_message*>(m_Data);
634
0
    }
635
636
    /// @return The size in [bytes] of the notification data. Notification data is a variable-length field used to
637
    /// diagnose the reason for the BGP NOTIFICATION
638
    size_t getNotificationDataLen() const;
639
640
    /// @return A pointer to the notification data. Notification data is a variable-length field used to diagnose
641
    /// the reason for the BGP NOTIFICATION
642
    uint8_t* getNotificationData() const;
643
644
    /// @return A hex string which represents the notification data. Notification data is a variable-length field
645
    /// used to diagnose the reason for the BGP NOTIFICATION
646
    std::string getNotificationDataAsHexString() const;
647
648
    /// Set the notification data. This method will extend or shorten the existing layer to include the new
649
    /// notification data. If newNotificationData is nullptr or newNotificationDataLen is zero then notification
650
    /// data will be set to none.
651
    /// @param[in] newNotificationData A byte array containing the new notification data
652
    /// @param[in] newNotificationDataLen The size of the byte array
653
    /// @return True if notification data was set successfully or false if any error occurred. In case of an error
654
    /// an appropriate error message will be printed to log
655
    bool setNotificationData(const uint8_t* newNotificationData, size_t newNotificationDataLen);
656
657
    /// Set the notification data. This method will extend or shorten the existing layer to include the new
658
    /// notification data. If newNotificationDataAsHexString is an empty string then notification data will be set
659
    /// to none.
660
    /// @param[in] newNotificationDataAsHexString A hex string representing the new notification data. If the string
661
    /// is not a valid hex string no data will be changed and an error will be returned
662
    /// @return True if notification data was set successfully or false if any error occurred or if the string is
663
    /// not a valid hex string. In case of an error an appropriate error message will be printed to log
664
    bool setNotificationData(const std::string& newNotificationDataAsHexString);
665
666
    // implement abstract methods
667
668
    BgpMessageType getBgpMessageType() const override
669
0
    {
670
0
      return BgpLayer::Notification;
671
0
    }
672
673
    /// @struct SerializedFields
674
    /// Fields written by BgpNotificationMessageLayer's serializeLayer(), in addition to
675
    /// BgpLayer::SerializedFields.
676
    struct SerializedFields : BgpLayer::SerializedFields
677
    {
678
      /// @return All field descriptors for BgpNotificationMessageLayer
679
      static std::vector<FieldDescriptor> all()
680
0
      {
681
0
        auto result = BgpLayer::SerializedFields::all();
682
0
        std::initializer_list<FieldDescriptor> extra{ ErrorCode, ErrorSubCode };
683
0
        std::copy(extra.begin(), extra.end(), std::back_inserter(result));
684
0
        return result;
685
0
      }
686
687
      /// @brief BGP notification error code
688
      static const FieldDescriptor ErrorCode;
689
690
      /// @brief BGP notification error sub-code
691
      static const FieldDescriptor ErrorSubCode;
692
693
      // cppcheck-suppress duplInheritedMember
694
      /// Maximum field ID used by the layer.
695
      static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 2;
696
    };
697
698
  protected:
699
    void serializeLayer(ObjectScope& serializer) const override;
700
701
  private:
702
    void initMessageData(uint8_t errorCode, uint8_t errorSubCode, const uint8_t* notificationData,
703
                         size_t notificationDataLen);
704
  };
705
706
  /// @class BgpKeepaliveMessageLayer
707
  /// Represents a BGP v4 KEEPALIVE message
708
  class BgpKeepaliveMessageLayer : public BgpLayer
709
  {
710
  public:
711
    /// @typedef bgp_keepalive_message
712
    /// BGP KEEPALIVE message structure
713
    typedef bgp_common_header bgp_keepalive_message;
714
715
    /// A constructor that creates the layer from an existing packet raw data
716
    /// @param[in] data A pointer to the raw data
717
    /// @param[in] dataLen Size of the data in bytes
718
    /// @param[in] prevLayer A pointer to the previous layer
719
    /// @param[in] packet A pointer to the Packet instance where layer will be stored in
720
    BgpKeepaliveMessageLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet)
721
0
        : BgpLayer(data, dataLen, prevLayer, packet)
722
0
    {}
723
724
    /// A c'tor that creates a new BGP KEEPALIVE message
725
    BgpKeepaliveMessageLayer();
726
727
    /// Get a pointer to the KeepAlive message data. Notice this points directly to the data, so any change will
728
    /// modify the actual packet data
729
    /// @return A pointer to a bgp_keepalive_message structure containing the data
730
    bgp_keepalive_message* getKeepaliveHeader() const
731
0
    {
732
0
      return reinterpret_cast<bgp_keepalive_message*>(getBasicHeader());
733
0
    }
734
735
    // implement abstract methods
736
737
    BgpMessageType getBgpMessageType() const override
738
0
    {
739
0
      return BgpLayer::Keepalive;
740
0
    }
741
742
    /// @struct SerializedFields
743
    /// Fields written by BgpKeepaliveMessageLayer's serializeLayer(), in addition to
744
    /// BgpLayer::SerializedFields. A KEEPALIVE message carries only the common BGP
745
    /// header, so no message-specific fields are added here.
746
    struct SerializedFields : BgpLayer::SerializedFields
747
    {
748
      /// @return All field descriptors for BgpKeepaliveMessageLayer
749
      static std::vector<FieldDescriptor> all()
750
0
      {
751
0
        return BgpLayer::SerializedFields::all();
752
0
      }
753
754
      // cppcheck-suppress duplInheritedMember
755
      /// Maximum field ID used by the layer.
756
      static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID;
757
    };
758
  };
759
760
  /// @class BgpRouteRefreshMessageLayer
761
  /// Represents a BGP v4 ROUTE-REFRESH message
762
  class BgpRouteRefreshMessageLayer : public BgpLayer
763
  {
764
  public:
765
#pragma pack(push, 1)
766
    /// @struct bgp_route_refresh_message
767
    /// BGP ROUTE-REFRESH message structure
768
    typedef struct bgp_route_refresh_message : bgp_common_header
769
    {
770
      /// Address Family Identifier
771
      uint16_t afi;
772
      /// Reserved field
773
      uint8_t reserved;
774
      /// Subsequent Address Family Identifier
775
      uint8_t safi;
776
    } bgp_route_refresh_message;
777
#pragma pack(pop)
778
779
    /// A constructor that creates the layer from an existing packet raw data
780
    /// @param[in] data A pointer to the raw data
781
    /// @param[in] dataLen Size of the data in bytes
782
    /// @param[in] prevLayer A pointer to the previous layer
783
    /// @param[in] packet A pointer to the Packet instance where layer will be stored in
784
    BgpRouteRefreshMessageLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet)
785
0
        : BgpLayer(data, dataLen, prevLayer, packet)
786
0
    {}
787
788
    /// A c'tor that creates a new BGP ROUTE-REFRESH message
789
    /// @param[in] afi The Address Family Identifier (AFI) value to set in the message
790
    /// @param[in] safi The Subsequent Address Family Identifier (SAFI) value to set in the message
791
    BgpRouteRefreshMessageLayer(uint16_t afi, uint8_t safi);
792
793
    /// Get a pointer to the ROUTE-REFRESH message data. Notice this points directly to the data, so any change will
794
    /// modify the actual packet data
795
    /// @return A pointer to a bgp_route_refresh_message structure containing the data
796
    bgp_route_refresh_message* getRouteRefreshHeader() const
797
0
    {
798
0
      return reinterpret_cast<bgp_route_refresh_message*>(getBasicHeader());
799
0
    }
800
801
    // implement abstract methods
802
803
    BgpMessageType getBgpMessageType() const override
804
0
    {
805
0
      return BgpLayer::RouteRefresh;
806
0
    }
807
808
    /// @struct SerializedFields
809
    /// Fields written by BgpRouteRefreshMessageLayer's serializeLayer(), in addition to
810
    /// BgpLayer::SerializedFields.
811
    struct SerializedFields : BgpLayer::SerializedFields
812
    {
813
      /// @return All field descriptors for BgpRouteRefreshMessageLayer
814
      static std::vector<FieldDescriptor> all()
815
0
      {
816
0
        auto result = BgpLayer::SerializedFields::all();
817
0
        std::initializer_list<FieldDescriptor> extra{ Afi, Safi };
818
0
        std::copy(extra.begin(), extra.end(), std::back_inserter(result));
819
0
        return result;
820
0
      }
821
822
      /// @brief Address Family Identifier, in host byte order
823
      static const FieldDescriptor Afi;
824
825
      /// @brief Subsequent Address Family Identifier, in host byte order
826
      static const FieldDescriptor Safi;
827
828
      // cppcheck-suppress duplInheritedMember
829
      /// Maximum field ID used by the layer.
830
      static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 2;
831
    };
832
833
  protected:
834
    void serializeLayer(ObjectScope& serializer) const override;
835
  };
836
837
}  // namespace pcpp