From 420d36959afe87a9b34fa544b1d0c603032934c7 Mon Sep 17 00:00:00 2001 From: Hack15951 Date: Thu, 12 Nov 2026 10:58:30 +0800 Subject: [PATCH 1/2] Add serialization support for BgpLayer (all message types) - part of #2278 --- Packet++/header/BgpLayer.h | 273 +++++++++++++++++++++++++- Packet++/src/BgpLayer.cpp | 188 +++++++++++++++++- Tests/Packet++Test/TestDefinition.h | 1 + Tests/Packet++Test/Tests/BgpTests.cpp | 107 ++++++++++ Tests/Packet++Test/main.cpp | 1 + 5 files changed, 559 insertions(+), 11 deletions(-) diff --git a/Packet++/header/BgpLayer.h b/Packet++/header/BgpLayer.h index 675aaa9707..bb16cb4cff 100644 --- a/Packet++/header/BgpLayer.h +++ b/Packet++/header/BgpLayer.h @@ -93,6 +93,31 @@ namespace pcpp return OsiModelApplicationLayer; } + /// @struct SerializedFields + /// Fields written by BgpLayer's serializeLayer(), in addition to + /// Layer::SerializedFields. + struct SerializedFields : Layer::SerializedFields + { + /// @return All field descriptors for BgpLayer + static std::vector all() + { + auto result = Layer::SerializedFields::all(); + std::initializer_list extra{ Marker, MessageType }; + std::copy(extra.begin(), extra.end(), std::back_inserter(result)); + return result; + } + + /// @brief 16-octet BGP marker, as lowercase hexadecimal without separators + static const FieldDescriptor Marker; + + /// @brief BGP message type, one of: "OPEN", "UPDATE", "NOTIFICATION", "KEEPALIVE", "ROUTE-REFRESH" + static const FieldDescriptor MessageType; + + // cppcheck-suppress duplInheritedMember + /// Maximum field ID used by the layer. + static constexpr uint16_t MaxID = Layer::SerializedFields::MaxID + 2; + }; + /// Calculates the basic BGP fields: /// - Set marker to all ones /// - Set message type value @@ -100,6 +125,8 @@ namespace pcpp void computeCalculateFields() override; protected: + void serializeLayer(ObjectScope& serializer) const override; + // protected c'tors, this class cannot be instantiated by users BgpLayer() {} @@ -209,7 +236,7 @@ namespace pcpp /// Get a vector of the optional parameters in the message /// @param[out] optionalParameters The vector where the optional parameters will be written to. This method /// doesn't remove any existing data on this vector before pushing data to it - void getOptionalParameters(std::vector& optionalParameters); + void getOptionalParameters(std::vector& optionalParameters) const; /// @return The length in [bytes] of the optional parameters data in the message size_t getOptionalParametersLength(); @@ -236,6 +263,73 @@ namespace pcpp return BgpLayer::Open; } + /// @struct SerializedFields + /// Fields written by BgpOpenMessageLayer's serializeLayer(), in addition to + /// BgpLayer::SerializedFields. + struct SerializedFields : BgpLayer::SerializedFields + { + /// @return All field descriptors for BgpOpenMessageLayer + static std::vector all() + { + auto result = BgpLayer::SerializedFields::all(); + std::initializer_list extra{ Version, MyAutonomousSystem, HoldTime, + BgpId, OptionalParameterLength, OptionalParameters }; + std::copy(extra.begin(), extra.end(), std::back_inserter(result)); + return result; + } + + /// @brief BGP version number + static const FieldDescriptor Version; + + /// @brief Autonomous System number of the sender, in host byte order + static const FieldDescriptor MyAutonomousSystem; + + /// @brief Hold Timer value proposed by the sender, in host byte order + static const FieldDescriptor HoldTime; + + /// @brief BGP identifier of the sender, as an IPv4 address string + static const FieldDescriptor BgpId; + + /// @brief Total length of the Optional Parameters field, in bytes + static const FieldDescriptor OptionalParameterLength; + + /// @brief Optional parameters as an array of {type, length, value} objects + static const FieldDescriptor OptionalParameters; + + // cppcheck-suppress duplInheritedMember + /// Maximum field ID used by the layer. + static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 6; + + /// @struct OptionalParameterSerializedFields + /// Fields of a single BGP OPEN optional parameter. + struct OptionalParameterSerializedFields + { + /// @return All field descriptors for an optional parameter + static std::vector all() + { + auto result = std::vector{}; + std::initializer_list extra{ Type, Length, Value }; + std::copy(extra.begin(), extra.end(), std::back_inserter(result)); + return result; + } + + /// @brief Parameter type + static const FieldDescriptor Type; + + /// @brief Parameter length, in bytes + static const FieldDescriptor Length; + + /// @brief Parameter value, as a lowercase hexadecimal string + static const FieldDescriptor Value; + }; + + /// @brief Single optional parameter element (used as the array item type) + static const ObjectFieldDescriptor OptionalParameter; + }; + + protected: + void serializeLayer(ObjectScope& serializer) const override; + private: /// Serializes the optional parameters to a byte array /// @throws std::invalid_argument if an optional parameter is invalid or the serialized data doesn't fit in @@ -337,7 +431,7 @@ namespace pcpp /// Get a vector of the Withdrawn Routes currently in the message /// @param[out] withdrawnRoutes A reference to a vector the Withdrawn Routes data will be written to - void getWithdrawnRoutes(std::vector& withdrawnRoutes); + void getWithdrawnRoutes(std::vector& withdrawnRoutes) const; /// Set Withdrawn Routes in this message. This method will override any existing Withdrawn Routes in the /// message. If the input is an empty vector all Withdrawn Routes will be removed. This method automatically @@ -358,7 +452,7 @@ namespace pcpp /// Get a vector of the Path Attributes currently in the message /// @param[out] pathAttributes A reference to a vector the Path Attributes data will be written to - void getPathAttributes(std::vector& pathAttributes); + void getPathAttributes(std::vector& pathAttributes) const; /// Set Path Attributes in this message. This method will override any existing Path Attributes in the message. /// If the input is an empty vector all Path Attributes will be removed. This method automatically sets the @@ -379,7 +473,7 @@ namespace pcpp /// Get a vector of the Network Layer Reachability Info currently in the message /// @param[out] nlri A reference to a vector the NLRI data will be written to - void getNetworkLayerReachabilityInfo(std::vector& nlri); + void getNetworkLayerReachabilityInfo(std::vector& nlri) const; /// Set NLRI data in this message. This method will override any existing NLRI data in the message. /// If the input is an empty vector all NLRI data will be removed. This method automatically sets the @@ -402,8 +496,95 @@ namespace pcpp return BgpLayer::Update; } + /// @struct SerializedFields + /// Fields written by BgpUpdateMessageLayer's serializeLayer(), in addition to + /// BgpLayer::SerializedFields. + struct SerializedFields : BgpLayer::SerializedFields + { + /// @return All field descriptors for BgpUpdateMessageLayer + static std::vector all() + { + auto result = BgpLayer::SerializedFields::all(); + std::initializer_list extra{ WithdrawnRoutes, PathAttributes, + NetworkLayerReachabilityInfo }; + std::copy(extra.begin(), extra.end(), std::back_inserter(result)); + return result; + } + + /// @brief Withdrawn routes as an array of {prefix, ipAddr} objects + static const FieldDescriptor WithdrawnRoutes; + + /// @brief Path attributes as an array of {flags, type, length, value} objects + static const FieldDescriptor PathAttributes; + + /// @brief Network Layer Reachability Information as an array of {prefix, ipAddr} objects + static const FieldDescriptor NetworkLayerReachabilityInfo; + + // cppcheck-suppress duplInheritedMember + /// Maximum field ID used by the layer. + static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 3; + + /// @struct PrefixAndIpSerializedFields + /// Fields of a single IPv4 prefix + address pair. + struct PrefixAndIpSerializedFields + { + /// @return All field descriptors for a prefix + IP pair + static std::vector all() + { + auto result = std::vector{}; + std::initializer_list extra{ Prefix, IpAddr }; + std::copy(extra.begin(), extra.end(), std::back_inserter(result)); + return result; + } + + /// @brief IPv4 address mask (8, 16, 24 or 32) + static const FieldDescriptor Prefix; + + /// @brief IPv4 address as a string + static const FieldDescriptor IpAddr; + }; + + /// @brief Single withdrawn route element (used as the array item type) + static const ObjectFieldDescriptor WithdrawnRoute; + + /// @struct PathAttributeSerializedFields + /// Fields of a single BGP path attribute. + struct PathAttributeSerializedFields + { + /// @return All field descriptors for a path attribute + static std::vector all() + { + auto result = std::vector{}; + std::initializer_list extra{ Flags, Type, Length, Value }; + std::copy(extra.begin(), extra.end(), std::back_inserter(result)); + return result; + } + + /// @brief Path attribute flags + static const FieldDescriptor Flags; + + /// @brief Path attribute type + static const FieldDescriptor Type; + + /// @brief Path attribute length, in bytes + static const FieldDescriptor Length; + + /// @brief Path attribute value, as a lowercase hexadecimal string + static const FieldDescriptor Value; + }; + + /// @brief Single path attribute element (used as the array item type) + static const ObjectFieldDescriptor PathAttribute; + + /// @brief Single NLRI element (used as the array item type) + static const ObjectFieldDescriptor Nlri; + }; + + protected: + void serializeLayer(ObjectScope& serializer) const override; + private: - void parsePrefixAndIPData(uint8_t* dataPtr, size_t dataLen, std::vector& result); + void parsePrefixAndIPData(uint8_t* dataPtr, size_t dataLen, std::vector& result) const; size_t prefixAndIPDataToByteArray(const std::vector& prefixAndIpData, uint8_t* resultByteArr, size_t maxByteArrSize); @@ -504,6 +685,37 @@ namespace pcpp return BgpLayer::Notification; } + /// @struct SerializedFields + /// Fields written by BgpNotificationMessageLayer's serializeLayer(), in addition to + /// BgpLayer::SerializedFields. + struct SerializedFields : BgpLayer::SerializedFields + { + /// @return All field descriptors for BgpNotificationMessageLayer + static std::vector all() + { + auto result = BgpLayer::SerializedFields::all(); + std::initializer_list extra{ ErrorCode, ErrorSubCode, NotificationData }; + std::copy(extra.begin(), extra.end(), std::back_inserter(result)); + return result; + } + + /// @brief BGP notification error code + static const FieldDescriptor ErrorCode; + + /// @brief BGP notification error sub-code + static const FieldDescriptor ErrorSubCode; + + /// @brief Notification data, as a lowercase hexadecimal string + static const FieldDescriptor NotificationData; + + // cppcheck-suppress duplInheritedMember + /// Maximum field ID used by the layer. + static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 3; + }; + + protected: + void serializeLayer(ObjectScope& serializer) const override; + private: void initMessageData(uint8_t errorCode, uint8_t errorSubCode, const uint8_t* notificationData, size_t notificationDataLen); @@ -544,6 +756,26 @@ namespace pcpp { return BgpLayer::Keepalive; } + + /// @struct SerializedFields + /// Fields written by BgpKeepaliveMessageLayer's serializeLayer(), in addition to + /// BgpLayer::SerializedFields. A KEEPALIVE message carries only the common BGP + /// header, so no message-specific fields are added here. + struct SerializedFields : BgpLayer::SerializedFields + { + /// @return All field descriptors for BgpKeepaliveMessageLayer + static std::vector all() + { + return BgpLayer::SerializedFields::all(); + } + + // cppcheck-suppress duplInheritedMember + /// Maximum field ID used by the layer. + static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID; + }; + + protected: + void serializeLayer(ObjectScope& serializer) const override; }; /// @class BgpRouteRefreshMessageLayer @@ -593,6 +825,37 @@ namespace pcpp { return BgpLayer::RouteRefresh; } + + /// @struct SerializedFields + /// Fields written by BgpRouteRefreshMessageLayer's serializeLayer(), in addition to + /// BgpLayer::SerializedFields. + struct SerializedFields : BgpLayer::SerializedFields + { + /// @return All field descriptors for BgpRouteRefreshMessageLayer + static std::vector all() + { + auto result = BgpLayer::SerializedFields::all(); + std::initializer_list extra{ Afi, Reserved, Safi }; + std::copy(extra.begin(), extra.end(), std::back_inserter(result)); + return result; + } + + /// @brief Address Family Identifier, in host byte order + static const FieldDescriptor Afi; + + /// @brief Reserved field + static const FieldDescriptor Reserved; + + /// @brief Subsequent Address Family Identifier, in host byte order + static const FieldDescriptor Safi; + + // cppcheck-suppress duplInheritedMember + /// Maximum field ID used by the layer. + static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 3; + }; + + protected: + void serializeLayer(ObjectScope& serializer) const override; }; } // namespace pcpp diff --git a/Packet++/src/BgpLayer.cpp b/Packet++/src/BgpLayer.cpp index 7ae90d8e2a..7c4f50f357 100644 --- a/Packet++/src/BgpLayer.cpp +++ b/Packet++/src/BgpLayer.cpp @@ -181,6 +181,16 @@ namespace pcpp return Layer::shortenLayer(offsetInLayer, numOfBytesToShorten); } + const FieldDescriptor BgpLayer::SerializedFields::Marker{ Layer::SerializedFields::MaxID + 1, "marker" }; + const FieldDescriptor BgpLayer::SerializedFields::MessageType{ Layer::SerializedFields::MaxID + 2, "messageType" }; + + void BgpLayer::serializeLayer(ObjectScope& serializer) const + { + auto* header = getBasicHeader(); + serializer.writeField(SerializedFields::MessageType, getMessageTypeAsString()); + serializer.writeField(SerializedFields::Marker, byteArrayToHexString(header->marker, sizeof(header->marker))); + } + // ~~~~~~~~~~~~~~~~~~~~ // BgpOpenMessageLayer // ~~~~~~~~~~~~~~~~~~~~ @@ -280,7 +290,7 @@ namespace pcpp msgHdr->bgpId = newBgpId.toInt(); } - void BgpOpenMessageLayer::getOptionalParameters(std::vector& optionalParameters) + void BgpOpenMessageLayer::getOptionalParameters(std::vector& optionalParameters) const { size_t headerLen = getHeaderLen(); bgp_open_message* msgHdr = getOpenMsgHeader(); @@ -397,6 +407,57 @@ namespace pcpp return setOptionalParameters(std::vector()); } + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::Version{ BgpLayer::SerializedFields::MaxID + 1, + "version" }; + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::MyAutonomousSystem{ + BgpLayer::SerializedFields::MaxID + 2, "myAutonomousSystem" + }; + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::HoldTime{ BgpLayer::SerializedFields::MaxID + 3, + "holdTime" }; + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::BgpId{ BgpLayer::SerializedFields::MaxID + 4, + "bgpId" }; + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameterLength{ + BgpLayer::SerializedFields::MaxID + 5, "optionalParameterLength" + }; + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameters{ + BgpLayer::SerializedFields::MaxID + 6, "optionalParameters" + }; + const ObjectFieldDescriptor + BgpOpenMessageLayer::SerializedFields::OptionalParameter{ 0, "optionalParameter" }; + + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Type{ 0, "type" }; + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Length{ 1, + "length" }; + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Value{ 2, "value" }; + + void BgpOpenMessageLayer::serializeLayer(ObjectScope& serializer) const + { + BgpLayer::serializeLayer(serializer); + + auto* header = getOpenMsgHeader(); + serializer.writeField(SerializedFields::Version, header->version); + serializer.writeField(SerializedFields::MyAutonomousSystem, be16toh(header->myAutonomousSystem)); + serializer.writeField(SerializedFields::HoldTime, be16toh(header->holdTime)); + serializer.writeField(SerializedFields::BgpId, getBgpId().toString()); + serializer.writeField(SerializedFields::OptionalParameterLength, header->optionalParameterLength); + + std::vector optionalParameters; + getOptionalParameters(optionalParameters); + auto optionalParametersArray = serializer.writeArray(SerializedFields::OptionalParameters); + for (const auto& optionalParameter : optionalParameters) + { + auto optionalParameterObject = optionalParametersArray.writeObject(SerializedFields::OptionalParameter); + optionalParameterObject.writeField( + BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Type, optionalParameter.type); + optionalParameterObject.writeField( + BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Length, + optionalParameter.length); + optionalParameterObject.writeField( + BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Value, + byteArrayToHexString(optionalParameter.value, optionalParameter.length)); + } + } + // ~~~~~~~~~~~~~~~~~~~~~ // BgpUpdateMessageLayer // ~~~~~~~~~~~~~~~~~~~~~ @@ -457,7 +518,7 @@ namespace pcpp } void BgpUpdateMessageLayer::parsePrefixAndIPData(uint8_t* dataPtr, size_t dataLen, - std::vector& result) + std::vector& result) const { size_t byteCount = 0; while (byteCount < dataLen) @@ -621,7 +682,7 @@ namespace pcpp return 0; } - void BgpUpdateMessageLayer::getWithdrawnRoutes(std::vector& withdrawnRoutes) + void BgpUpdateMessageLayer::getWithdrawnRoutes(std::vector& withdrawnRoutes) const { size_t withdrawnRouteLen = getWithdrawnRoutesLength(); if (withdrawnRouteLen == 0) @@ -705,7 +766,7 @@ namespace pcpp return setWithdrawnRoutes(std::vector()); } - void BgpUpdateMessageLayer::getPathAttributes(std::vector& pathAttributes) + void BgpUpdateMessageLayer::getPathAttributes(std::vector& pathAttributes) const { size_t pathAttrLen = getPathAttributesLength(); if (pathAttrLen == 0) @@ -803,7 +864,7 @@ namespace pcpp return 0; } - void BgpUpdateMessageLayer::getNetworkLayerReachabilityInfo(std::vector& nlri) + void BgpUpdateMessageLayer::getNetworkLayerReachabilityInfo(std::vector& nlri) const { size_t nlriSize = getNetworkLayerReachabilityInfoLength(); if (nlriSize == 0) @@ -878,6 +939,78 @@ namespace pcpp return setNetworkLayerReachabilityInfo(std::vector()); } + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::WithdrawnRoutes{ + BgpLayer::SerializedFields::MaxID + 1, "withdrawnRoutes" + }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributes{ + BgpLayer::SerializedFields::MaxID + 2, "pathAttributes" + }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::NetworkLayerReachabilityInfo{ + BgpLayer::SerializedFields::MaxID + 3, "networkLayerReachabilityInfo" + }; + + const ObjectFieldDescriptor + BgpUpdateMessageLayer::SerializedFields::WithdrawnRoute{ 0, "withdrawnRoute" }; + const ObjectFieldDescriptor + BgpUpdateMessageLayer::SerializedFields::PathAttribute{ 0, "pathAttribute" }; + const ObjectFieldDescriptor + BgpUpdateMessageLayer::SerializedFields::Nlri{ 0, "nlri" }; + + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::Prefix{ 0, "prefix" }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::IpAddr{ 1, "ipAddr" }; + + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Flags{ 0, "flags" }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Type{ 1, "type" }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Length{ 2, "length" }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Value{ 3, "value" }; + + void BgpUpdateMessageLayer::serializeLayer(ObjectScope& serializer) const + { + BgpLayer::serializeLayer(serializer); + + std::vector withdrawnRoutes; + getWithdrawnRoutes(withdrawnRoutes); + auto withdrawnRoutesArray = serializer.writeArray(SerializedFields::WithdrawnRoutes); + for (const auto& withdrawnRoute : withdrawnRoutes) + { + auto withdrawnRouteObject = withdrawnRoutesArray.writeObject(SerializedFields::WithdrawnRoute); + withdrawnRouteObject.writeField( + BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::Prefix, withdrawnRoute.prefix); + withdrawnRouteObject.writeField( + BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::IpAddr, + withdrawnRoute.ipAddr.toString()); + } + + std::vector pathAttributes; + getPathAttributes(pathAttributes); + auto pathAttributesArray = serializer.writeArray(SerializedFields::PathAttributes); + for (const auto& pathAttribute : pathAttributes) + { + auto pathAttributeObject = pathAttributesArray.writeObject(SerializedFields::PathAttribute); + pathAttributeObject.writeField( + BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Flags, pathAttribute.flags); + pathAttributeObject.writeField(BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Type, + pathAttribute.type); + pathAttributeObject.writeField( + BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Length, pathAttribute.length); + pathAttributeObject.writeField( + BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Value, + byteArrayToHexString(pathAttribute.data, pathAttribute.length)); + } + + std::vector nlri; + getNetworkLayerReachabilityInfo(nlri); + auto nlriArray = serializer.writeArray(SerializedFields::NetworkLayerReachabilityInfo); + for (const auto& nlriItem : nlri) + { + auto nlriObject = nlriArray.writeObject(SerializedFields::Nlri); + nlriObject.writeField(BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::Prefix, + nlriItem.prefix); + nlriObject.writeField(BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::IpAddr, + nlriItem.ipAddr.toString()); + } + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // BgpNotificationMessageLayer // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -946,7 +1079,7 @@ namespace pcpp std::string BgpNotificationMessageLayer::getNotificationDataAsHexString() const { - uint8_t* notificationData = getNotificationData(); + const uint8_t* notificationData = getNotificationData(); if (notificationData == nullptr) { return ""; @@ -1017,6 +1150,26 @@ namespace pcpp return setNotificationData(newNotificationData, newNotificationDataLen); } + const FieldDescriptor BgpNotificationMessageLayer::SerializedFields::ErrorCode{ + BgpLayer::SerializedFields::MaxID + 1, "errorCode" + }; + const FieldDescriptor BgpNotificationMessageLayer::SerializedFields::ErrorSubCode{ + BgpLayer::SerializedFields::MaxID + 2, "errorSubCode" + }; + const FieldDescriptor BgpNotificationMessageLayer::SerializedFields::NotificationData{ + BgpLayer::SerializedFields::MaxID + 3, "notificationData" + }; + + void BgpNotificationMessageLayer::serializeLayer(ObjectScope& serializer) const + { + BgpLayer::serializeLayer(serializer); + + auto* header = getNotificationMsgHeader(); + serializer.writeField(SerializedFields::ErrorCode, header->errorCode); + serializer.writeField(SerializedFields::ErrorSubCode, header->errorSubCode); + serializer.writeField(SerializedFields::NotificationData, getNotificationDataAsHexString()); + } + // ~~~~~~~~~~~~~~~~~~~~~~~~ // BgpKeepaliveMessageLayer // ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1029,6 +1182,11 @@ namespace pcpp m_Protocol = BGP; } + void BgpKeepaliveMessageLayer::serializeLayer(ObjectScope& serializer) const + { + BgpLayer::serializeLayer(serializer); + } + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // BgpRouteRefreshMessageLayer // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1044,4 +1202,22 @@ namespace pcpp m_Protocol = BGP; } + const FieldDescriptor BgpRouteRefreshMessageLayer::SerializedFields::Afi{ BgpLayer::SerializedFields::MaxID + 1, + "afi" }; + const FieldDescriptor BgpRouteRefreshMessageLayer::SerializedFields::Reserved{ + BgpLayer::SerializedFields::MaxID + 2, "reserved" + }; + const FieldDescriptor BgpRouteRefreshMessageLayer::SerializedFields::Safi{ BgpLayer::SerializedFields::MaxID + 3, + "safi" }; + + void BgpRouteRefreshMessageLayer::serializeLayer(ObjectScope& serializer) const + { + BgpLayer::serializeLayer(serializer); + + auto* header = getRouteRefreshHeader(); + serializer.writeField(SerializedFields::Afi, be16toh(header->afi)); + serializer.writeField(SerializedFields::Reserved, header->reserved); + serializer.writeField(SerializedFields::Safi, header->safi); + } + } // namespace pcpp diff --git a/Tests/Packet++Test/TestDefinition.h b/Tests/Packet++Test/TestDefinition.h index 96786d43ad..e8ec25e50c 100644 --- a/Tests/Packet++Test/TestDefinition.h +++ b/Tests/Packet++Test/TestDefinition.h @@ -235,6 +235,7 @@ PTF_TEST_CASE(GtpV2LayerEditTest); PTF_TEST_CASE(BgpLayerParsingTest); PTF_TEST_CASE(BgpLayerCreationTest); PTF_TEST_CASE(BgpLayerEditTest); +PTF_TEST_CASE(BgpLayerSerializationTest); PTF_TEST_CASE(BgpOpenMalformedOptionalParamsTest); // Implemented in SSHTests.cpp diff --git a/Tests/Packet++Test/Tests/BgpTests.cpp b/Tests/Packet++Test/Tests/BgpTests.cpp index 6963986ad1..9552a23a0d 100644 --- a/Tests/Packet++Test/Tests/BgpTests.cpp +++ b/Tests/Packet++Test/Tests/BgpTests.cpp @@ -7,6 +7,8 @@ #include "TcpLayer.h" #include "BgpLayer.h" #include "SystemUtils.h" +#include "Serializers.h" +#include using pcpp_tests::utils::createPacketAndBufferFromHexResource; using pcpp_tests::utils::createPacketFromHexResource; @@ -786,3 +788,108 @@ PTF_TEST_CASE(BgpOpenMalformedOptionalParamsTest) } } // BgpOpenMalformedOptionalParamsTest + +PTF_TEST_CASE(BgpLayerSerializationTest) +{ + // 1. SerializedFields::all() exposes the expected number of field descriptors for each message type. + // Base BgpLayer adds "marker" + "messageType" to Layer::SerializedFields' 3 fields => 5. + PTF_ASSERT_EQUAL(pcpp::BgpLayer::SerializedFields::all().size(), 5); + PTF_ASSERT_EQUAL(pcpp::BgpOpenMessageLayer::SerializedFields::all().size(), 11); + PTF_ASSERT_EQUAL(pcpp::BgpUpdateMessageLayer::SerializedFields::all().size(), 8); + PTF_ASSERT_EQUAL(pcpp::BgpNotificationMessageLayer::SerializedFields::all().size(), 8); + PTF_ASSERT_EQUAL(pcpp::BgpKeepaliveMessageLayer::SerializedFields::all().size(), 5); + PTF_ASSERT_EQUAL(pcpp::BgpRouteRefreshMessageLayer::SerializedFields::all().size(), 8); + + // 2. OPEN message serialization + { + auto rawPacket = createPacketFromHexResource("PacketExamples/Bgp_open.dat"); + pcpp::Packet packet(rawPacket.get()); + auto* openLayer = packet.getLayerOfType(); + PTF_ASSERT_NOT_NULL(openLayer); + + std::ostringstream jsonStream; + pcpp::JsonSerializer jsonSerializer(jsonStream); + openLayer->serialize(jsonSerializer); + std::string result = jsonStream.str(); + PTF_ASSERT_FALSE(result.empty()); + PTF_ASSERT_TRUE(result.find("\"messageType\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"OPEN\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"version\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"myAutonomousSystem\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"bgpId\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"1.1.1.1\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"optionalParameters\"") != std::string::npos); + } + + // 3. UPDATE message serialization (withdrawn routes / path attributes / NLRI) + { + auto rawPacket = createPacketFromHexResource("PacketExamples/Bgp_update2.dat"); + pcpp::Packet packet(rawPacket.get()); + auto* updateLayer = packet.getLayerOfType(); + PTF_ASSERT_NOT_NULL(updateLayer); + + std::ostringstream jsonStream; + pcpp::JsonSerializer jsonSerializer(jsonStream); + updateLayer->serialize(jsonSerializer); + std::string result = jsonStream.str(); + PTF_ASSERT_FALSE(result.empty()); + PTF_ASSERT_TRUE(result.find("\"messageType\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"UPDATE\"") != std::string::npos); + const bool hasSomeArray = result.find("\"withdrawnRoutes\"") != std::string::npos || + result.find("\"pathAttributes\"") != std::string::npos || + result.find("\"networkLayerReachabilityInfo\"") != std::string::npos; + PTF_ASSERT_TRUE(hasSomeArray); + } + + // 4. NOTIFICATION message serialization + { + auto rawPacket = createPacketFromHexResource("PacketExamples/Bgp_notification.dat"); + pcpp::Packet packet(rawPacket.get()); + auto* notificationLayer = packet.getLayerOfType(); + PTF_ASSERT_NOT_NULL(notificationLayer); + + std::ostringstream jsonStream; + pcpp::JsonSerializer jsonSerializer(jsonStream); + notificationLayer->serialize(jsonSerializer); + std::string result = jsonStream.str(); + PTF_ASSERT_FALSE(result.empty()); + PTF_ASSERT_TRUE(result.find("\"messageType\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"NOTIFICATION\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"errorCode\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"errorSubCode\"") != std::string::npos); + } + + // 5. KEEPALIVE message serialization (common header only) + { + auto rawPacket = createPacketFromHexResource("PacketExamples/Bgp_keepalive.dat"); + pcpp::Packet packet(rawPacket.get()); + auto* keepaliveLayer = packet.getLayerOfType(); + PTF_ASSERT_NOT_NULL(keepaliveLayer); + + std::ostringstream jsonStream; + pcpp::JsonSerializer jsonSerializer(jsonStream); + keepaliveLayer->serialize(jsonSerializer); + std::string result = jsonStream.str(); + PTF_ASSERT_FALSE(result.empty()); + PTF_ASSERT_TRUE(result.find("\"messageType\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"KEEPALIVE\"") != std::string::npos); + } + + // 6. ROUTE-REFRESH message serialization + { + auto rawPacket = createPacketFromHexResource("PacketExamples/Bgp_route-refresh.dat"); + pcpp::Packet packet(rawPacket.get()); + auto* routeRefreshLayer = packet.getLayerOfType(); + PTF_ASSERT_NOT_NULL(routeRefreshLayer); + + std::ostringstream jsonStream; + pcpp::JsonSerializer jsonSerializer(jsonStream); + routeRefreshLayer->serialize(jsonSerializer); + std::string result = jsonStream.str(); + PTF_ASSERT_FALSE(result.empty()); + PTF_ASSERT_TRUE(result.find("\"messageType\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"ROUTE-REFRESH\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"afi\"") != std::string::npos); + PTF_ASSERT_TRUE(result.find("\"safi\"") != std::string::npos); + } +} // BgpLayerSerializationTest diff --git a/Tests/Packet++Test/main.cpp b/Tests/Packet++Test/main.cpp index 6da67814f1..01120411e5 100644 --- a/Tests/Packet++Test/main.cpp +++ b/Tests/Packet++Test/main.cpp @@ -327,6 +327,7 @@ int main(int argc, char* argv[]) PTF_RUN_TEST(BgpLayerParsingTest, "bgp"); PTF_RUN_TEST(BgpLayerCreationTest, "bgp"); PTF_RUN_TEST(BgpLayerEditTest, "bgp"); + PTF_RUN_TEST(BgpLayerSerializationTest, "bgp"); PTF_RUN_TEST(BgpOpenMalformedOptionalParamsTest, "bgp"); PTF_RUN_TEST(SSHParsingTest, "ssh"); From f463d53a572a21ae0c11caaf66d4670a2cef261a Mon Sep 17 00:00:00 2001 From: Hack15951 Date: Thu, 19 Nov 2026 10:34:24 +0800 Subject: [PATCH 2/2] Address review feedback on BGP layer serialization --- Packet++/header/BgpLayer.h | 84 +++++--------- Packet++/src/BgpLayer.cpp | 134 +++++++++------------ Tests/Packet++Test/TestDefinition.h | 1 - Tests/Packet++Test/Tests/BgpTests.cpp | 161 +++++++++----------------- Tests/Packet++Test/main.cpp | 1 - 5 files changed, 141 insertions(+), 240 deletions(-) diff --git a/Packet++/header/BgpLayer.h b/Packet++/header/BgpLayer.h index bb16cb4cff..05d032addf 100644 --- a/Packet++/header/BgpLayer.h +++ b/Packet++/header/BgpLayer.h @@ -102,20 +102,17 @@ namespace pcpp static std::vector all() { auto result = Layer::SerializedFields::all(); - std::initializer_list extra{ Marker, MessageType }; + std::initializer_list extra{ MessageType }; std::copy(extra.begin(), extra.end(), std::back_inserter(result)); return result; } - /// @brief 16-octet BGP marker, as lowercase hexadecimal without separators - static const FieldDescriptor Marker; - /// @brief BGP message type, one of: "OPEN", "UPDATE", "NOTIFICATION", "KEEPALIVE", "ROUTE-REFRESH" static const FieldDescriptor MessageType; // cppcheck-suppress duplInheritedMember /// Maximum field ID used by the layer. - static constexpr uint16_t MaxID = Layer::SerializedFields::MaxID + 2; + static constexpr uint16_t MaxID = Layer::SerializedFields::MaxID + 1; }; /// Calculates the basic BGP fields: @@ -272,8 +269,8 @@ namespace pcpp static std::vector all() { auto result = BgpLayer::SerializedFields::all(); - std::initializer_list extra{ Version, MyAutonomousSystem, HoldTime, - BgpId, OptionalParameterLength, OptionalParameters }; + std::initializer_list extra{ Version, MyAutonomousSystem, HoldTime, BgpId, + OptionalParameters }; std::copy(extra.begin(), extra.end(), std::back_inserter(result)); return result; } @@ -290,27 +287,23 @@ namespace pcpp /// @brief BGP identifier of the sender, as an IPv4 address string static const FieldDescriptor BgpId; - /// @brief Total length of the Optional Parameters field, in bytes - static const FieldDescriptor OptionalParameterLength; - - /// @brief Optional parameters as an array of {type, length, value} objects + /// @brief Optional parameters as an array of {type, length} objects static const FieldDescriptor OptionalParameters; // cppcheck-suppress duplInheritedMember /// Maximum field ID used by the layer. - static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 6; + static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 5; - /// @struct OptionalParameterSerializedFields + /// @struct OptionalParameterObject /// Fields of a single BGP OPEN optional parameter. - struct OptionalParameterSerializedFields + struct OptionalParameterObject : ObjectFieldDescriptor { + using ObjectFieldDescriptor::ObjectFieldDescriptor; + /// @return All field descriptors for an optional parameter static std::vector all() { - auto result = std::vector{}; - std::initializer_list extra{ Type, Length, Value }; - std::copy(extra.begin(), extra.end(), std::back_inserter(result)); - return result; + return { Type, Length }; } /// @brief Parameter type @@ -318,13 +311,10 @@ namespace pcpp /// @brief Parameter length, in bytes static const FieldDescriptor Length; - - /// @brief Parameter value, as a lowercase hexadecimal string - static const FieldDescriptor Value; }; /// @brief Single optional parameter element (used as the array item type) - static const ObjectFieldDescriptor OptionalParameter; + static const OptionalParameterObject OptionalParameter; }; protected: @@ -514,7 +504,7 @@ namespace pcpp /// @brief Withdrawn routes as an array of {prefix, ipAddr} objects static const FieldDescriptor WithdrawnRoutes; - /// @brief Path attributes as an array of {flags, type, length, value} objects + /// @brief Path attributes as an array of {flags, type, length} objects static const FieldDescriptor PathAttributes; /// @brief Network Layer Reachability Information as an array of {prefix, ipAddr} objects @@ -524,17 +514,16 @@ namespace pcpp /// Maximum field ID used by the layer. static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 3; - /// @struct PrefixAndIpSerializedFields + /// @struct PrefixAndIpObject /// Fields of a single IPv4 prefix + address pair. - struct PrefixAndIpSerializedFields + struct PrefixAndIpObject : ObjectFieldDescriptor { + using ObjectFieldDescriptor::ObjectFieldDescriptor; + /// @return All field descriptors for a prefix + IP pair static std::vector all() { - auto result = std::vector{}; - std::initializer_list extra{ Prefix, IpAddr }; - std::copy(extra.begin(), extra.end(), std::back_inserter(result)); - return result; + return { Prefix, IpAddr }; } /// @brief IPv4 address mask (8, 16, 24 or 32) @@ -545,19 +534,18 @@ namespace pcpp }; /// @brief Single withdrawn route element (used as the array item type) - static const ObjectFieldDescriptor WithdrawnRoute; + static const PrefixAndIpObject WithdrawnRoute; - /// @struct PathAttributeSerializedFields + /// @struct PathAttributeObject /// Fields of a single BGP path attribute. - struct PathAttributeSerializedFields + struct PathAttributeObject : ObjectFieldDescriptor { + using ObjectFieldDescriptor::ObjectFieldDescriptor; + /// @return All field descriptors for a path attribute static std::vector all() { - auto result = std::vector{}; - std::initializer_list extra{ Flags, Type, Length, Value }; - std::copy(extra.begin(), extra.end(), std::back_inserter(result)); - return result; + return { Flags, Type, Length }; } /// @brief Path attribute flags @@ -568,16 +556,13 @@ namespace pcpp /// @brief Path attribute length, in bytes static const FieldDescriptor Length; - - /// @brief Path attribute value, as a lowercase hexadecimal string - static const FieldDescriptor Value; }; /// @brief Single path attribute element (used as the array item type) - static const ObjectFieldDescriptor PathAttribute; + static const PathAttributeObject PathAttribute; /// @brief Single NLRI element (used as the array item type) - static const ObjectFieldDescriptor Nlri; + static const PrefixAndIpObject Nlri; }; protected: @@ -694,7 +679,7 @@ namespace pcpp static std::vector all() { auto result = BgpLayer::SerializedFields::all(); - std::initializer_list extra{ ErrorCode, ErrorSubCode, NotificationData }; + std::initializer_list extra{ ErrorCode, ErrorSubCode }; std::copy(extra.begin(), extra.end(), std::back_inserter(result)); return result; } @@ -705,12 +690,9 @@ namespace pcpp /// @brief BGP notification error sub-code static const FieldDescriptor ErrorSubCode; - /// @brief Notification data, as a lowercase hexadecimal string - static const FieldDescriptor NotificationData; - // cppcheck-suppress duplInheritedMember /// Maximum field ID used by the layer. - static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 3; + static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 2; }; protected: @@ -773,9 +755,6 @@ namespace pcpp /// Maximum field ID used by the layer. static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID; }; - - protected: - void serializeLayer(ObjectScope& serializer) const override; }; /// @class BgpRouteRefreshMessageLayer @@ -835,7 +814,7 @@ namespace pcpp static std::vector all() { auto result = BgpLayer::SerializedFields::all(); - std::initializer_list extra{ Afi, Reserved, Safi }; + std::initializer_list extra{ Afi, Safi }; std::copy(extra.begin(), extra.end(), std::back_inserter(result)); return result; } @@ -843,15 +822,12 @@ namespace pcpp /// @brief Address Family Identifier, in host byte order static const FieldDescriptor Afi; - /// @brief Reserved field - static const FieldDescriptor Reserved; - /// @brief Subsequent Address Family Identifier, in host byte order static const FieldDescriptor Safi; // cppcheck-suppress duplInheritedMember /// Maximum field ID used by the layer. - static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 3; + static constexpr uint16_t MaxID = BgpLayer::SerializedFields::MaxID + 2; }; protected: diff --git a/Packet++/src/BgpLayer.cpp b/Packet++/src/BgpLayer.cpp index 7c4f50f357..c9edc3b227 100644 --- a/Packet++/src/BgpLayer.cpp +++ b/Packet++/src/BgpLayer.cpp @@ -181,14 +181,11 @@ namespace pcpp return Layer::shortenLayer(offsetInLayer, numOfBytesToShorten); } - const FieldDescriptor BgpLayer::SerializedFields::Marker{ Layer::SerializedFields::MaxID + 1, "marker" }; - const FieldDescriptor BgpLayer::SerializedFields::MessageType{ Layer::SerializedFields::MaxID + 2, "messageType" }; + const FieldDescriptor BgpLayer::SerializedFields::MessageType{ Layer::SerializedFields::MaxID + 1, "messageType" }; void BgpLayer::serializeLayer(ObjectScope& serializer) const { - auto* header = getBasicHeader(); serializer.writeField(SerializedFields::MessageType, getMessageTypeAsString()); - serializer.writeField(SerializedFields::Marker, byteArrayToHexString(header->marker, sizeof(header->marker))); } // ~~~~~~~~~~~~~~~~~~~~ @@ -416,19 +413,14 @@ namespace pcpp "holdTime" }; const FieldDescriptor BgpOpenMessageLayer::SerializedFields::BgpId{ BgpLayer::SerializedFields::MaxID + 4, "bgpId" }; - const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameterLength{ - BgpLayer::SerializedFields::MaxID + 5, "optionalParameterLength" - }; const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameters{ - BgpLayer::SerializedFields::MaxID + 6, "optionalParameters" + BgpLayer::SerializedFields::MaxID + 5, "optionalParameters" }; - const ObjectFieldDescriptor + const BgpOpenMessageLayer::SerializedFields::OptionalParameterObject BgpOpenMessageLayer::SerializedFields::OptionalParameter{ 0, "optionalParameter" }; - const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Type{ 0, "type" }; - const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Length{ 1, - "length" }; - const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Value{ 2, "value" }; + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameterObject::Type{ 0, "type" }; + const FieldDescriptor BgpOpenMessageLayer::SerializedFields::OptionalParameterObject::Length{ 1, "length" }; void BgpOpenMessageLayer::serializeLayer(ObjectScope& serializer) const { @@ -439,7 +431,6 @@ namespace pcpp serializer.writeField(SerializedFields::MyAutonomousSystem, be16toh(header->myAutonomousSystem)); serializer.writeField(SerializedFields::HoldTime, be16toh(header->holdTime)); serializer.writeField(SerializedFields::BgpId, getBgpId().toString()); - serializer.writeField(SerializedFields::OptionalParameterLength, header->optionalParameterLength); std::vector optionalParameters; getOptionalParameters(optionalParameters); @@ -447,14 +438,10 @@ namespace pcpp for (const auto& optionalParameter : optionalParameters) { auto optionalParameterObject = optionalParametersArray.writeObject(SerializedFields::OptionalParameter); - optionalParameterObject.writeField( - BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Type, optionalParameter.type); - optionalParameterObject.writeField( - BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Length, - optionalParameter.length); - optionalParameterObject.writeField( - BgpOpenMessageLayer::SerializedFields::OptionalParameterSerializedFields::Value, - byteArrayToHexString(optionalParameter.value, optionalParameter.length)); + optionalParameterObject.writeField(BgpOpenMessageLayer::SerializedFields::OptionalParameterObject::Type, + optionalParameter.type); + optionalParameterObject.writeField(BgpOpenMessageLayer::SerializedFields::OptionalParameterObject::Length, + optionalParameter.length); } } @@ -949,65 +936,67 @@ namespace pcpp BgpLayer::SerializedFields::MaxID + 3, "networkLayerReachabilityInfo" }; - const ObjectFieldDescriptor + const BgpUpdateMessageLayer::SerializedFields::PrefixAndIpObject BgpUpdateMessageLayer::SerializedFields::WithdrawnRoute{ 0, "withdrawnRoute" }; - const ObjectFieldDescriptor + const BgpUpdateMessageLayer::SerializedFields::PathAttributeObject BgpUpdateMessageLayer::SerializedFields::PathAttribute{ 0, "pathAttribute" }; - const ObjectFieldDescriptor - BgpUpdateMessageLayer::SerializedFields::Nlri{ 0, "nlri" }; + const BgpUpdateMessageLayer::SerializedFields::PrefixAndIpObject BgpUpdateMessageLayer::SerializedFields::Nlri{ + 0, "nlri" + }; - const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::Prefix{ 0, "prefix" }; - const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::IpAddr{ 1, "ipAddr" }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PrefixAndIpObject::Prefix{ 0, "prefix" }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PrefixAndIpObject::IpAddr{ 1, "ipAddr" }; - const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Flags{ 0, "flags" }; - const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Type{ 1, "type" }; - const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Length{ 2, "length" }; - const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Value{ 3, "value" }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeObject::Flags{ 0, "flags" }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeObject::Type{ 1, "type" }; + const FieldDescriptor BgpUpdateMessageLayer::SerializedFields::PathAttributeObject::Length{ 2, "length" }; void BgpUpdateMessageLayer::serializeLayer(ObjectScope& serializer) const { BgpLayer::serializeLayer(serializer); - std::vector withdrawnRoutes; - getWithdrawnRoutes(withdrawnRoutes); - auto withdrawnRoutesArray = serializer.writeArray(SerializedFields::WithdrawnRoutes); - for (const auto& withdrawnRoute : withdrawnRoutes) { - auto withdrawnRouteObject = withdrawnRoutesArray.writeObject(SerializedFields::WithdrawnRoute); - withdrawnRouteObject.writeField( - BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::Prefix, withdrawnRoute.prefix); - withdrawnRouteObject.writeField( - BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::IpAddr, - withdrawnRoute.ipAddr.toString()); + std::vector withdrawnRoutes; + getWithdrawnRoutes(withdrawnRoutes); + auto withdrawnRoutesArray = serializer.writeArray(SerializedFields::WithdrawnRoutes); + for (const auto& withdrawnRoute : withdrawnRoutes) + { + auto withdrawnRouteObject = withdrawnRoutesArray.writeObject(SerializedFields::WithdrawnRoute); + withdrawnRouteObject.writeField(BgpUpdateMessageLayer::SerializedFields::PrefixAndIpObject::Prefix, + withdrawnRoute.prefix); + withdrawnRouteObject.writeField(BgpUpdateMessageLayer::SerializedFields::PrefixAndIpObject::IpAddr, + withdrawnRoute.ipAddr.toString()); + } } - std::vector pathAttributes; - getPathAttributes(pathAttributes); - auto pathAttributesArray = serializer.writeArray(SerializedFields::PathAttributes); - for (const auto& pathAttribute : pathAttributes) { - auto pathAttributeObject = pathAttributesArray.writeObject(SerializedFields::PathAttribute); - pathAttributeObject.writeField( - BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Flags, pathAttribute.flags); - pathAttributeObject.writeField(BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Type, - pathAttribute.type); - pathAttributeObject.writeField( - BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Length, pathAttribute.length); - pathAttributeObject.writeField( - BgpUpdateMessageLayer::SerializedFields::PathAttributeSerializedFields::Value, - byteArrayToHexString(pathAttribute.data, pathAttribute.length)); + std::vector pathAttributes; + getPathAttributes(pathAttributes); + auto pathAttributesArray = serializer.writeArray(SerializedFields::PathAttributes); + for (const auto& pathAttribute : pathAttributes) + { + auto pathAttributeObject = pathAttributesArray.writeObject(SerializedFields::PathAttribute); + pathAttributeObject.writeField(BgpUpdateMessageLayer::SerializedFields::PathAttributeObject::Flags, + pathAttribute.flags); + pathAttributeObject.writeField(BgpUpdateMessageLayer::SerializedFields::PathAttributeObject::Type, + pathAttribute.type); + pathAttributeObject.writeField(BgpUpdateMessageLayer::SerializedFields::PathAttributeObject::Length, + pathAttribute.length); + } } - std::vector nlri; - getNetworkLayerReachabilityInfo(nlri); - auto nlriArray = serializer.writeArray(SerializedFields::NetworkLayerReachabilityInfo); - for (const auto& nlriItem : nlri) { - auto nlriObject = nlriArray.writeObject(SerializedFields::Nlri); - nlriObject.writeField(BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::Prefix, - nlriItem.prefix); - nlriObject.writeField(BgpUpdateMessageLayer::SerializedFields::PrefixAndIpSerializedFields::IpAddr, - nlriItem.ipAddr.toString()); + std::vector nlri; + getNetworkLayerReachabilityInfo(nlri); + auto nlriArray = serializer.writeArray(SerializedFields::NetworkLayerReachabilityInfo); + for (const auto& nlriItem : nlri) + { + auto nlriObject = nlriArray.writeObject(SerializedFields::Nlri); + nlriObject.writeField(BgpUpdateMessageLayer::SerializedFields::PrefixAndIpObject::Prefix, + nlriItem.prefix); + nlriObject.writeField(BgpUpdateMessageLayer::SerializedFields::PrefixAndIpObject::IpAddr, + nlriItem.ipAddr.toString()); + } } } @@ -1156,9 +1145,6 @@ namespace pcpp const FieldDescriptor BgpNotificationMessageLayer::SerializedFields::ErrorSubCode{ BgpLayer::SerializedFields::MaxID + 2, "errorSubCode" }; - const FieldDescriptor BgpNotificationMessageLayer::SerializedFields::NotificationData{ - BgpLayer::SerializedFields::MaxID + 3, "notificationData" - }; void BgpNotificationMessageLayer::serializeLayer(ObjectScope& serializer) const { @@ -1167,7 +1153,6 @@ namespace pcpp auto* header = getNotificationMsgHeader(); serializer.writeField(SerializedFields::ErrorCode, header->errorCode); serializer.writeField(SerializedFields::ErrorSubCode, header->errorSubCode); - serializer.writeField(SerializedFields::NotificationData, getNotificationDataAsHexString()); } // ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1182,11 +1167,6 @@ namespace pcpp m_Protocol = BGP; } - void BgpKeepaliveMessageLayer::serializeLayer(ObjectScope& serializer) const - { - BgpLayer::serializeLayer(serializer); - } - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // BgpRouteRefreshMessageLayer // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1204,10 +1184,7 @@ namespace pcpp const FieldDescriptor BgpRouteRefreshMessageLayer::SerializedFields::Afi{ BgpLayer::SerializedFields::MaxID + 1, "afi" }; - const FieldDescriptor BgpRouteRefreshMessageLayer::SerializedFields::Reserved{ - BgpLayer::SerializedFields::MaxID + 2, "reserved" - }; - const FieldDescriptor BgpRouteRefreshMessageLayer::SerializedFields::Safi{ BgpLayer::SerializedFields::MaxID + 3, + const FieldDescriptor BgpRouteRefreshMessageLayer::SerializedFields::Safi{ BgpLayer::SerializedFields::MaxID + 2, "safi" }; void BgpRouteRefreshMessageLayer::serializeLayer(ObjectScope& serializer) const @@ -1216,7 +1193,6 @@ namespace pcpp auto* header = getRouteRefreshHeader(); serializer.writeField(SerializedFields::Afi, be16toh(header->afi)); - serializer.writeField(SerializedFields::Reserved, header->reserved); serializer.writeField(SerializedFields::Safi, header->safi); } diff --git a/Tests/Packet++Test/TestDefinition.h b/Tests/Packet++Test/TestDefinition.h index e8ec25e50c..96786d43ad 100644 --- a/Tests/Packet++Test/TestDefinition.h +++ b/Tests/Packet++Test/TestDefinition.h @@ -235,7 +235,6 @@ PTF_TEST_CASE(GtpV2LayerEditTest); PTF_TEST_CASE(BgpLayerParsingTest); PTF_TEST_CASE(BgpLayerCreationTest); PTF_TEST_CASE(BgpLayerEditTest); -PTF_TEST_CASE(BgpLayerSerializationTest); PTF_TEST_CASE(BgpOpenMalformedOptionalParamsTest); // Implemented in SSHTests.cpp diff --git a/Tests/Packet++Test/Tests/BgpTests.cpp b/Tests/Packet++Test/Tests/BgpTests.cpp index 9552a23a0d..32aeff9ff7 100644 --- a/Tests/Packet++Test/Tests/BgpTests.cpp +++ b/Tests/Packet++Test/Tests/BgpTests.cpp @@ -42,6 +42,13 @@ PTF_TEST_CASE(BgpLayerParsingTest) } PTF_ASSERT_EQUAL(be16toh(bgpKALayer->getKeepaliveHeader()->length), 19); + { + std::ostringstream oss; + pcpp::JsonSerializer serializer(oss); + bgpKALayer->serialize(serializer); + PTF_ASSERT_EQUAL(oss.str(), R"({"protocolName":"BGP","protocolId":34,"length":19,"messageType":"KEEPALIVE"})"); + } + // parse BGP OPEN message pcpp::Packet bgpOpenPacket(rawPacket2.get()); @@ -78,6 +85,16 @@ PTF_TEST_CASE(BgpLayerParsingTest) PTF_ASSERT_EQUAL(optParam.value[optParamsDataInedx[i]], optParamsData[i]); } + { + std::ostringstream oss; + pcpp::JsonSerializer serializer(oss); + bgpOpenLayer->serialize(serializer); + PTF_ASSERT_EQUAL( + oss.str(), + R"({"protocolName":"BGP","protocolId":34,"length":57,"messageType":"OPEN","version":4,"myAutonomousSystem":1,"holdTime":180,"bgpId":"1.1.1.1","optionalParameters":[)" + R"({"type":2,"length":6},{"type":2,"length":2},{"type":2,"length":2},{"type":2,"length":2},{"type":2,"length":6}]})"); + } + // parse BGP NOTIFICATION message pcpp::Packet bgpNotificationPacket(rawPacket3.get()); @@ -102,6 +119,15 @@ PTF_TEST_CASE(BgpLayerParsingTest) "726520696e666f726d6174696f6e2e"; PTF_ASSERT_EQUAL(bgpNotificationLayer->getNotificationDataAsHexString(), notificationDataAsHexString); + { + std::ostringstream oss; + pcpp::JsonSerializer serializer(oss); + bgpNotificationLayer->serialize(serializer); + PTF_ASSERT_EQUAL( + oss.str(), + R"({"protocolName":"BGP","protocolId":34,"length":146,"messageType":"NOTIFICATION","errorCode":6,"errorSubCode":2})"); + } + pcpp::Packet bgpNotificationNoDataPacket(rawPacket4.get()); PTF_ASSERT_TRUE(bgpNotificationNoDataPacket.isPacketOfType(pcpp::BGP)); @@ -124,6 +150,15 @@ PTF_TEST_CASE(BgpLayerParsingTest) PTF_ASSERT_EQUAL(bgpRRLayer->getRouteRefreshHeader()->safi, 1); PTF_ASSERT_EQUAL(bgpRRLayer->getRouteRefreshHeader()->reserved, 1); + { + std::ostringstream oss; + pcpp::JsonSerializer serializer(oss); + bgpRRLayer->serialize(serializer); + PTF_ASSERT_EQUAL( + oss.str(), + R"({"protocolName":"BGP","protocolId":34,"length":23,"messageType":"ROUTE-REFRESH","afi":1,"safi":1})"); + } + // parse BGP UPDATE message with Withdrawn Routes pcpp::Packet bgpUpdatePacket1(rawPacket6.get()); @@ -156,6 +191,17 @@ PTF_TEST_CASE(BgpLayerParsingTest) PTF_ASSERT_NOT_NULL(bgpUpdateLayer->getNextLayer()); PTF_ASSERT_EQUAL(bgpUpdateLayer->getNextLayer()->getProtocol(), pcpp::BGP, enum); + { + std::ostringstream oss; + pcpp::JsonSerializer serializer(oss); + bgpUpdateLayer->serialize(serializer); + PTF_ASSERT_EQUAL( + oss.str(), R"({"protocolName":"BGP","protocolId":34,"length":38,"messageType":"UPDATE","withdrawnRoutes":[)" + R"({"prefix":24,"ipAddr":"40.1.1.0"},{"prefix":24,"ipAddr":"40.40.40.0"},)" + R"({"prefix":16,"ipAddr":"103.103.0.0"},{"prefix":24,"ipAddr":"103.103.40.0"}],)" + R"("pathAttributes":[],"networkLayerReachabilityInfo":[]})"); + } + // parse BGP UPDATE message with Path Attributes pcpp::Packet bgpUpdatePacket2(rawPacket7.get()); @@ -196,6 +242,16 @@ PTF_TEST_CASE(BgpLayerParsingTest) pcpp::BgpUpdateMessageLayer::prefix_and_ip nlri = nlriVec[0]; PTF_ASSERT_EQUAL(nlri.prefix, 24); PTF_ASSERT_EQUAL(nlri.ipAddr, pcpp::IPv4Address("104.104.40.0")); + + { + std::ostringstream oss; + pcpp::JsonSerializer serializer(oss); + bgpUpdateLayer->serialize(serializer); + PTF_ASSERT_EQUAL( + oss.str(), + R"json({"protocolName":"BGP","protocolId":34,"length":55,"messageType":"UPDATE","withdrawnRoutes":[],"pathAttributes":[{"flags":64,"type":1,"length":1},{"flags":64,"type":2,"length":14},{"flags":64,"type":3,"length":4}],"networkLayerReachabilityInfo":[{"prefix":24,"ipAddr":"104.104.40.0"}]})json"); + } + size_t pathAttrSize[3] = { 28, 24, 0 }; for (int i = 0; i < 3; i++) { @@ -788,108 +844,3 @@ PTF_TEST_CASE(BgpOpenMalformedOptionalParamsTest) } } // BgpOpenMalformedOptionalParamsTest - -PTF_TEST_CASE(BgpLayerSerializationTest) -{ - // 1. SerializedFields::all() exposes the expected number of field descriptors for each message type. - // Base BgpLayer adds "marker" + "messageType" to Layer::SerializedFields' 3 fields => 5. - PTF_ASSERT_EQUAL(pcpp::BgpLayer::SerializedFields::all().size(), 5); - PTF_ASSERT_EQUAL(pcpp::BgpOpenMessageLayer::SerializedFields::all().size(), 11); - PTF_ASSERT_EQUAL(pcpp::BgpUpdateMessageLayer::SerializedFields::all().size(), 8); - PTF_ASSERT_EQUAL(pcpp::BgpNotificationMessageLayer::SerializedFields::all().size(), 8); - PTF_ASSERT_EQUAL(pcpp::BgpKeepaliveMessageLayer::SerializedFields::all().size(), 5); - PTF_ASSERT_EQUAL(pcpp::BgpRouteRefreshMessageLayer::SerializedFields::all().size(), 8); - - // 2. OPEN message serialization - { - auto rawPacket = createPacketFromHexResource("PacketExamples/Bgp_open.dat"); - pcpp::Packet packet(rawPacket.get()); - auto* openLayer = packet.getLayerOfType(); - PTF_ASSERT_NOT_NULL(openLayer); - - std::ostringstream jsonStream; - pcpp::JsonSerializer jsonSerializer(jsonStream); - openLayer->serialize(jsonSerializer); - std::string result = jsonStream.str(); - PTF_ASSERT_FALSE(result.empty()); - PTF_ASSERT_TRUE(result.find("\"messageType\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"OPEN\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"version\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"myAutonomousSystem\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"bgpId\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"1.1.1.1\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"optionalParameters\"") != std::string::npos); - } - - // 3. UPDATE message serialization (withdrawn routes / path attributes / NLRI) - { - auto rawPacket = createPacketFromHexResource("PacketExamples/Bgp_update2.dat"); - pcpp::Packet packet(rawPacket.get()); - auto* updateLayer = packet.getLayerOfType(); - PTF_ASSERT_NOT_NULL(updateLayer); - - std::ostringstream jsonStream; - pcpp::JsonSerializer jsonSerializer(jsonStream); - updateLayer->serialize(jsonSerializer); - std::string result = jsonStream.str(); - PTF_ASSERT_FALSE(result.empty()); - PTF_ASSERT_TRUE(result.find("\"messageType\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"UPDATE\"") != std::string::npos); - const bool hasSomeArray = result.find("\"withdrawnRoutes\"") != std::string::npos || - result.find("\"pathAttributes\"") != std::string::npos || - result.find("\"networkLayerReachabilityInfo\"") != std::string::npos; - PTF_ASSERT_TRUE(hasSomeArray); - } - - // 4. NOTIFICATION message serialization - { - auto rawPacket = createPacketFromHexResource("PacketExamples/Bgp_notification.dat"); - pcpp::Packet packet(rawPacket.get()); - auto* notificationLayer = packet.getLayerOfType(); - PTF_ASSERT_NOT_NULL(notificationLayer); - - std::ostringstream jsonStream; - pcpp::JsonSerializer jsonSerializer(jsonStream); - notificationLayer->serialize(jsonSerializer); - std::string result = jsonStream.str(); - PTF_ASSERT_FALSE(result.empty()); - PTF_ASSERT_TRUE(result.find("\"messageType\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"NOTIFICATION\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"errorCode\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"errorSubCode\"") != std::string::npos); - } - - // 5. KEEPALIVE message serialization (common header only) - { - auto rawPacket = createPacketFromHexResource("PacketExamples/Bgp_keepalive.dat"); - pcpp::Packet packet(rawPacket.get()); - auto* keepaliveLayer = packet.getLayerOfType(); - PTF_ASSERT_NOT_NULL(keepaliveLayer); - - std::ostringstream jsonStream; - pcpp::JsonSerializer jsonSerializer(jsonStream); - keepaliveLayer->serialize(jsonSerializer); - std::string result = jsonStream.str(); - PTF_ASSERT_FALSE(result.empty()); - PTF_ASSERT_TRUE(result.find("\"messageType\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"KEEPALIVE\"") != std::string::npos); - } - - // 6. ROUTE-REFRESH message serialization - { - auto rawPacket = createPacketFromHexResource("PacketExamples/Bgp_route-refresh.dat"); - pcpp::Packet packet(rawPacket.get()); - auto* routeRefreshLayer = packet.getLayerOfType(); - PTF_ASSERT_NOT_NULL(routeRefreshLayer); - - std::ostringstream jsonStream; - pcpp::JsonSerializer jsonSerializer(jsonStream); - routeRefreshLayer->serialize(jsonSerializer); - std::string result = jsonStream.str(); - PTF_ASSERT_FALSE(result.empty()); - PTF_ASSERT_TRUE(result.find("\"messageType\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"ROUTE-REFRESH\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"afi\"") != std::string::npos); - PTF_ASSERT_TRUE(result.find("\"safi\"") != std::string::npos); - } -} // BgpLayerSerializationTest diff --git a/Tests/Packet++Test/main.cpp b/Tests/Packet++Test/main.cpp index 01120411e5..6da67814f1 100644 --- a/Tests/Packet++Test/main.cpp +++ b/Tests/Packet++Test/main.cpp @@ -327,7 +327,6 @@ int main(int argc, char* argv[]) PTF_RUN_TEST(BgpLayerParsingTest, "bgp"); PTF_RUN_TEST(BgpLayerCreationTest, "bgp"); PTF_RUN_TEST(BgpLayerEditTest, "bgp"); - PTF_RUN_TEST(BgpLayerSerializationTest, "bgp"); PTF_RUN_TEST(BgpOpenMalformedOptionalParamsTest, "bgp"); PTF_RUN_TEST(SSHParsingTest, "ssh");