From 884bcf7cbffcc3203cf55ae77bdb4ab5c442a91b Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Tue, 18 Jun 2024 18:00:32 +0900 Subject: [PATCH 01/13] add clang-format in CI --- . git-blame-ignore-revs | 0 .clang-format | 3 ++- .github/workflows/build_and_test.yml | 1 + .pre-commit-config.yaml | 4 +++- 4 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 . git-blame-ignore-revs diff --git a/. git-blame-ignore-revs b/. git-blame-ignore-revs new file mode 100644 index 0000000000..e69de29bb2 diff --git a/.clang-format b/.clang-format index 757c95dd69..87535d1f1c 100644 --- a/.clang-format +++ b/.clang-format @@ -3,5 +3,6 @@ BasedOnStyle: Microsoft UseTab: Always AllowShortFunctionsOnASingleLine: All NamespaceIndentation: All - +SortIncludes: false +BreakBeforeBraces: Allman ... diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index ccfd2ce65a..677f1bb01e 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -30,6 +30,7 @@ jobs: run: | apk update && apk add cppcheck python3-dev python3 -m pip install cmake-format + pip install clang-format==18.1.6 - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f80c940238..13192b809c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,9 +16,11 @@ repos: - repo: https://github.com/pocc/pre-commit-hooks rev: v1.3.5 hooks: + - id: clang-format + args: ["--style=file"] # Use the .clang-format file for configuration + files: ^Common\+\+/.*\.(cpp|h)$ - id: cppcheck args: ["--std=c++11", "--language=c++", "--suppressions-list=cppcheckSuppressions.txt", "--inline-suppr", "--force"] -# - id: clang-format - repo: https://github.com/codespell-project/codespell rev: v2.3.0 hooks: From 3b0b2283141d772783881db1bf280714a3c7c462 Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Mon, 17 Jun 2024 14:18:32 +0900 Subject: [PATCH 02/13] apply clang-format in Common++ --- .clang-format | 2 +- Common++/header/DeprecationUtils.h | 52 +-- Common++/header/GeneralUtils.h | 39 ++- Common++/header/IpAddress.h | 250 +++++++------- Common++/header/IpAddressUtils.h | 34 +- Common++/header/IpUtils.h | 26 +- Common++/header/LRUList.h | 54 ++- Common++/header/Logger.h | 200 +++++------ Common++/header/MacAddress.h | 53 +-- Common++/header/OUILookup.h | 16 +- Common++/header/PcapPlusPlusVersion.h | 17 +- Common++/header/PointerVector.h | 64 ++-- Common++/header/SystemUtils.h | 72 ++-- Common++/header/TablePrinter.h | 12 +- Common++/header/TimespecTimeval.h | 18 +- Common++/src/GeneralUtils.cpp | 123 ++++--- Common++/src/IpAddress.cpp | 135 +++----- Common++/src/IpAddressUtils.cpp | 13 +- Common++/src/IpUtils.cpp | 102 +++--- Common++/src/Logger.cpp | 79 ++--- Common++/src/MacAddress.cpp | 37 +- Common++/src/OUILookup.cpp | 145 ++++---- Common++/src/PcapPlusPlusVersion.cpp | 35 +- Common++/src/SystemUtils.cpp | 467 ++++++++++++-------------- Common++/src/TablePrinter.cpp | 176 +++++----- 25 files changed, 1064 insertions(+), 1157 deletions(-) diff --git a/.clang-format b/.clang-format index 87535d1f1c..fdee82e4f7 100644 --- a/.clang-format +++ b/.clang-format @@ -1,8 +1,8 @@ --- BasedOnStyle: Microsoft UseTab: Always +BreakBeforeBraces: Allman AllowShortFunctionsOnASingleLine: All NamespaceIndentation: All SortIncludes: false -BreakBeforeBraces: Allman ... diff --git a/Common++/header/DeprecationUtils.h b/Common++/header/DeprecationUtils.h index afdc20cb18..2f3f782bba 100644 --- a/Common++/header/DeprecationUtils.h +++ b/Common++/header/DeprecationUtils.h @@ -3,35 +3,37 @@ /// @file #ifndef PCPP_DEPRECATED - #if defined(__GNUC__) || defined(__clang__) - #define PCPP_DEPRECATED(msg) __attribute__((deprecated(msg))) - #elif defined(_MSC_VER) - #define PCPP_DEPRECATED(msg) __declspec(deprecated(msg)) - #else - #pragma message("WARNING: DEPRECATED feature is not implemented for this compiler") - #define PCPP_DEPRECATED(msg) - #endif +#if defined(__GNUC__) || defined(__clang__) +#define PCPP_DEPRECATED(msg) __attribute__((deprecated(msg))) +#elif defined(_MSC_VER) +#define PCPP_DEPRECATED(msg) __declspec(deprecated(msg)) +#else +#pragma message("WARNING: DEPRECATED feature is not implemented for this compiler") +#define PCPP_DEPRECATED(msg) +#endif #endif #if !defined(DISABLE_WARNING_PUSH) || !defined(DISABLE_WARNING_POP) - #if defined(_MSC_VER) - #define DISABLE_WARNING_PUSH __pragma(warning( push )) - #define DISABLE_WARNING_POP __pragma(warning( pop )) - #define DISABLE_WARNING(warningNumber) __pragma(warning( disable : warningNumber )) +#if defined(_MSC_VER) +#define DISABLE_WARNING_PUSH __pragma(warning(push)) +#define DISABLE_WARNING_POP __pragma(warning(pop)) +#define DISABLE_WARNING(warningNumber) __pragma(warning(disable : warningNumber)) - #define DISABLE_WARNING_DEPRECATED DISABLE_WARNING(4996) - #elif defined(__GNUC__) || defined(__clang__) - #define DO_PRAGMA(X) _Pragma(#X) - #define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) - #define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) - #define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName) +#define DISABLE_WARNING_DEPRECATED DISABLE_WARNING(4996) +#elif defined(__GNUC__) || defined(__clang__) +#define DO_PRAGMA(X) _Pragma(#X) +#define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) +#define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) +#define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName) - #define DISABLE_WARNING_DEPRECATED DISABLE_WARNING(-Wdeprecated-declarations) - #else - #pragma message("WARNING: Disabling of warnings is not implemented for this compiler") - #define DISABLE_WARNING_PUSH - #define DISABLE_WARNING_POP +// clang-format off +#define DISABLE_WARNING_DEPRECATED DISABLE_WARNING(-Wdeprecated-declarations) +// clang-format on +#else +#pragma message("WARNING: Disabling of warnings is not implemented for this compiler") +#define DISABLE_WARNING_PUSH +#define DISABLE_WARNING_POP - #define DISABLE_WARNING_DEPRECATED - #endif +#define DISABLE_WARNING_DEPRECATED +#endif #endif diff --git a/Common++/header/GeneralUtils.h b/Common++/header/GeneralUtils.h index 1f7e475b05..eb8abd8bd4 100644 --- a/Common++/header/GeneralUtils.h +++ b/Common++/header/GeneralUtils.h @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include /// @file @@ -17,13 +17,13 @@ namespace pcpp * "aa2b10" will be returned * @param[in] byteArr A byte array * @param[in] byteArrSize The size of the byte array [in bytes] - * @param[in] stringSizeLimit An optional parameter that enables to limit the returned string size. If set to a positive - * integer value the returned string size will be equal or less than this value. If the string representation of the - * whole array is longer than this size then only part of the array will be read. The default value is -1 which means no - * string size limitation + * @param[in] stringSizeLimit An optional parameter that enables to limit the returned string size. If set to a + * positive integer value the returned string size will be equal or less than this value. If the string + * representation of the whole array is longer than this size then only part of the array will be read. The default + * value is -1 which means no string size limitation * @return A string of hex characters representing the byte array */ - std::string byteArrayToHexString(const uint8_t* byteArr, size_t byteArrSize, int stringSizeLimit = -1); + std::string byteArrayToHexString(const uint8_t *byteArr, size_t byteArrSize, int stringSizeLimit = -1); /** * Convert a string of hex characters into a byte array. For example: for the string "aa2b10" an array of values @@ -31,33 +31,32 @@ namespace pcpp * @param[in] hexString A string of hex characters * @param[out] resultByteArr A pre-allocated byte array where the result will be written to * @param[in] resultByteArrSize The size of the pre-allocated byte array - * @return The size of the result array. If the string represents an array that is longer than the pre-allocated size - * (resultByteArrSize) then the result array will contain only the part of the string that managed to fit into the - * array, and the returned size will be resultByteArrSize. However if the string represents an array that is shorter - * than the pre-allocated size then some of the cells will remain empty and contain zeros, and the returned size will - * be the part of the array that contain data. If the input is an illegal hex string 0 will be returned. + * @return The size of the result array. If the string represents an array that is longer than the pre-allocated + * size (resultByteArrSize) then the result array will contain only the part of the string that managed to fit into + * the array, and the returned size will be resultByteArrSize. However if the string represents an array that is + * shorter than the pre-allocated size then some of the cells will remain empty and contain zeros, and the returned + * size will be the part of the array that contain data. If the input is an illegal hex string 0 will be returned. * Illegal hex string means odd number of characters or a string that contains non-hex characters */ - size_t hexStringToByteArray(const std::string& hexString, uint8_t* resultByteArr, size_t resultByteArrSize); + size_t hexStringToByteArray(const std::string &hexString, uint8_t *resultByteArr, size_t resultByteArrSize); /** - * This is a cross platform version of memmem (https://man7.org/linux/man-pages/man3/memmem.3.html) which is not supported - * on all platforms. + * This is a cross platform version of memmem (https://man7.org/linux/man-pages/man3/memmem.3.html) which is not + * supported on all platforms. * @param[in] haystack A pointer to the buffer to be searched * @param[in] haystackLen Length of the haystack buffer * @param[in] needle A pointer to a buffer that will be searched for * @param[in] needleLen Length of the needle buffer * @return A pointer to the beginning of the substring, or NULL if the substring is not found */ - char* cross_platform_memmem(const char* haystack, size_t haystackLen, const char* needle, size_t needleLen); + char *cross_platform_memmem(const char *haystack, size_t haystackLen, const char *needle, size_t needleLen); /** * Calculates alignment. * @param[in] number Given number * @return The aligned number - */ - template - static int align(int number) + */ + template static int align(int number) { // Only works for alignment with power of 2 constexpr bool isPowerOfTwo = alignment && ((alignment & (alignment - 1)) == 0); @@ -70,7 +69,7 @@ namespace pcpp * A template class to calculate enum class hash * @tparam EnumClass */ - template::value , bool>::type = false> + template ::value, bool>::type = false> struct EnumClassHash { size_t operator()(EnumClass value) const @@ -78,4 +77,4 @@ namespace pcpp return static_cast::type>(value); } }; -} +} // namespace pcpp diff --git a/Common++/header/IpAddress.h b/Common++/header/IpAddress.h index 52f83fb7c3..33af35f335 100644 --- a/Common++/header/IpAddress.h +++ b/Common++/header/IpAddress.h @@ -1,16 +1,15 @@ #pragma once -#include -#include -#include #include -#include #include #include +#include +#include +#include +#include /// @file - /** * \namespace pcpp * \brief The main namespace for the PcapPlusPlus lib @@ -31,7 +30,7 @@ namespace pcpp */ class IPv4Address { - public: + public: /** * A default constructor that creates an instance of the class with the zero-initialized address */ @@ -53,7 +52,7 @@ namespace pcpp * A constructor that creates an instance of the class out of a 4-byte standard array. * @param[in] bytes The address as 4-byte standard array in network byte order */ - IPv4Address(const std::array& bytes) : m_Bytes(bytes) {} + IPv4Address(const std::array &bytes) : m_Bytes(bytes) {} /** * A constructor that creates an instance of the class out of std::string value. @@ -61,7 +60,7 @@ namespace pcpp * @param[in] addrAsString The std::string representation of the address * @throws std::invalid_argument The provided string does not represent a valid IPv4 address. */ - IPv4Address(const std::string& addrAsString); + IPv4Address(const std::string &addrAsString); /** * @return A 4-byte integer in network byte order representing the IPv4 address @@ -71,12 +70,12 @@ namespace pcpp /** * @return A non-owning pointer to 4-byte C-style array representing the IPv4 address */ - const uint8_t* toBytes() const { return m_Bytes.data(); } + const uint8_t *toBytes() const { return m_Bytes.data(); } /** * @return A reference to a 4-byte standard array representing the IPv4 address */ - const std::array& toByteArray() const { return m_Bytes; } + const std::array &toByteArray() const { return m_Bytes; } /** * @return A string representation of the address @@ -93,20 +92,21 @@ namespace pcpp * @param[in] rhs The object to compare with * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPv4Address& rhs) const { return toInt() == rhs.toInt(); } + bool operator==(const IPv4Address &rhs) const { return toInt() == rhs.toInt(); } /** * Overload of the less-than operator * @param[in] rhs The object to compare with * @return True if the address value is lower than the other address value, false otherwise */ - bool operator<(const IPv4Address& rhs) const + bool operator<(const IPv4Address &rhs) const { uint32_t intVal = toInt(); - std::reverse(reinterpret_cast(&intVal), reinterpret_cast(&intVal) + sizeof(intVal)); + std::reverse(reinterpret_cast(&intVal), reinterpret_cast(&intVal) + sizeof(intVal)); uint32_t rhsIntVal = rhs.toInt(); - std::reverse(reinterpret_cast(&rhsIntVal), reinterpret_cast(&rhsIntVal) + sizeof(rhsIntVal)); + std::reverse(reinterpret_cast(&rhsIntVal), + reinterpret_cast(&rhsIntVal) + sizeof(rhsIntVal)); return intVal < rhsIntVal; } @@ -116,14 +116,14 @@ namespace pcpp * @param[in] rhs The object to compare with * @return True if the addresses are not equal, false otherwise */ - bool operator!=(const IPv4Address& rhs) const { return !(*this == rhs); } + bool operator!=(const IPv4Address &rhs) const { return !(*this == rhs); } /** * Checks whether the address matches a network. * @param network An IPv4Network network * @return True if the address matches the network or false otherwise */ - bool matchNetwork(const IPv4Network& network) const; + bool matchNetwork(const IPv4Network &network) const; /** * Checks whether the address matches a network. @@ -136,14 +136,14 @@ namespace pcpp * - X.X.X.X/Y.Y.Y.Y where X.X.X.X is a valid IP address and Y.Y.Y.Y is a valid netmask * @return True if the address matches the network or false if it doesn't or if the network is invalid */ - bool matchNetwork(const std::string& network) const; + bool matchNetwork(const std::string &network) const; /** * A static method that checks whether a string represents a valid IPv4 address * @param[in] addrAsString The std::string representation of the address * @return True if the address is valid, false otherwise */ - static bool isValidIPv4Address(const std::string& addrAsString); + static bool isValidIPv4Address(const std::string &addrAsString); /** * A static value representing a zero value of IPv4 address, meaning address of value "0.0.0.0". @@ -159,11 +159,10 @@ namespace pcpp static const IPv4Address MulticastRangeLowerBound; static const IPv4Address MulticastRangeUpperBound; - private: + private: std::array m_Bytes = {0}; }; // class IPv4Address - // Implementation of inline methods uint32_t IPv4Address::toInt() const @@ -179,7 +178,7 @@ namespace pcpp */ class IPv6Address { - public: + public: /** * A default constructor that creates an instance of the class with the zero-initialized address. */ @@ -195,7 +194,7 @@ namespace pcpp * A constructor that creates an instance of the class out of a 16-byte standard array. * @param[in] bytes The address as 16-byte standard array in network byte order */ - IPv6Address(const std::array& bytes) : m_Bytes(bytes) {} + IPv6Address(const std::array &bytes) : m_Bytes(bytes) {} /** * A constructor that creates an instance of the class out of std::string value. @@ -203,19 +202,19 @@ namespace pcpp * @param[in] addrAsString The std::string representation of the address * @throws std::invalid_argument The provided string does not represent a valid IPv6 address. */ - IPv6Address(const std::string& addrAsString); + IPv6Address(const std::string &addrAsString); /** * Returns a view of the IPv6 address as a 16-byte raw C-style array * @return A non-owning pointer to 16-byte array representing the IPv6 address */ - const uint8_t* toBytes() const { return m_Bytes.data(); } + const uint8_t *toBytes() const { return m_Bytes.data(); } /** * Returns a view of the IPv6 address as a std::array of bytes * @return A reference to a 16-byte standard array representing the IPv6 address */ - const std::array& toByteArray() const { return m_Bytes; } + const std::array &toByteArray() const { return m_Bytes; } /** * Returns a std::string representation of the address @@ -234,14 +233,14 @@ namespace pcpp * @param[in] rhs The object to compare with * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPv6Address& rhs) const { return memcmp(toBytes(), rhs.toBytes(), sizeof(m_Bytes)) == 0; } + bool operator==(const IPv6Address &rhs) const { return memcmp(toBytes(), rhs.toBytes(), sizeof(m_Bytes)) == 0; } /** * Overload of the less-than operator * @param[in] rhs The object to compare with * @return True if the address value is lower than the other address value, false otherwise */ - bool operator<(const IPv6Address& rhs) const { return memcmp(toBytes(), rhs.toBytes(), sizeof(m_Bytes)) < 0; } + bool operator<(const IPv6Address &rhs) const { return memcmp(toBytes(), rhs.toBytes(), sizeof(m_Bytes)) < 0; } /** * Overload of the not-equal-to operator @@ -250,27 +249,26 @@ namespace pcpp */ bool operator!=(const IPv6Address &rhs) const { return !(*this == rhs); } - /** * Allocates a byte array and copies address value into it. Array deallocation is user responsibility * @param[in] arr A pointer to where array will be allocated * @param[out] length Returns the length in bytes of the array that was allocated */ - void copyTo(uint8_t** arr, size_t& length) const; + void copyTo(uint8_t **arr, size_t &length) const; /** * Gets a pointer to an already allocated byte array and copies the address value to it. * This method assumes array allocated size is at least 16 (the size of an IPv6 address) * @param[in] arr A pointer to the array which address will be copied to */ - void copyTo(uint8_t* arr) const { memcpy(arr, m_Bytes.data(), m_Bytes.size() * sizeof(uint8_t)); } + void copyTo(uint8_t *arr) const { memcpy(arr, m_Bytes.data(), m_Bytes.size() * sizeof(uint8_t)); } /** * Checks whether the address matches a network. * @param network An IPv6Network network * @return True if the address matches the network or false otherwise */ - bool matchNetwork(const IPv6Network& network) const; + bool matchNetwork(const IPv6Network &network) const; /** * Checks whether the address matches a network. @@ -285,17 +283,18 @@ namespace pcpp * IPv6 netmask * @return True if the address matches the network or false if it doesn't or if the network is invalid */ - bool matchNetwork(const std::string& network) const; + bool matchNetwork(const std::string &network) const; /** * A static method that checks whether a string represents a valid IPv6 address * @param[in] addrAsString The std::string representation of the address * @return True if the address is valid, false otherwise */ - static bool isValidIPv6Address(const std::string& addrAsString); + static bool isValidIPv6Address(const std::string &addrAsString); /** - * A static value representing a zero value of IPv6 address, meaning address of value "0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0". + * A static value representing a zero value of IPv6 address, meaning address of value + * "0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0". */ static const IPv6Address Zero; @@ -306,18 +305,17 @@ namespace pcpp */ static const IPv6Address MulticastRangeLowerBound; - private: + private: std::array m_Bytes = {0}; }; // class IPv6Address - /** * @class IPAddress * The class is a version-independent representation for an IP address */ class IPAddress { - public: + public: /** * An enum representing the address type: IPv4 or IPv6 */ @@ -342,13 +340,13 @@ namespace pcpp * A constructor that creates an instance of the class out of IPv4Address. * @param[in] addr A const reference to instance of IPv4Address */ - IPAddress(const IPv4Address& addr) : m_Type(IPv4AddressType), m_IPv4(addr) {} + IPAddress(const IPv4Address &addr) : m_Type(IPv4AddressType), m_IPv4(addr) {} /** * A constructor that creates an instance of the class out of IPv6Address. * @param[in] addr A const reference to instance of IPv6Address */ - IPAddress(const IPv6Address& addr) : m_Type(IPv6AddressType), m_IPv6(addr) {} + IPAddress(const IPv6Address &addr) : m_Type(IPv6AddressType), m_IPv6(addr) {} /** * A constructor that creates an instance of the class out of std::string value @@ -356,21 +354,21 @@ namespace pcpp * @param[in] addrAsString The std::string representation of the address * @throws std::invalid_argument The provided string does not represent a valid IPv4 or IPv6 address. */ - IPAddress(const std::string& addrAsString); + IPAddress(const std::string &addrAsString); /** * Overload of an assignment operator. * @param[in] addr A const reference to instance of IPv4Address * @return A reference to the assignee */ - inline IPAddress& operator=(const IPv4Address& addr); + inline IPAddress &operator=(const IPv4Address &addr); /** * Overload of an assignment operator. * @param[in] addr A const reference to instance of IPv6Address * @return A reference to the assignee */ - inline IPAddress& operator=(const IPv6Address& addr); + inline IPAddress &operator=(const IPv6Address &addr); /** * Gets the address type: IPv4 or IPv6 @@ -382,7 +380,7 @@ namespace pcpp * Returns a std::string representation of the address * @return A string representation of the address */ - std::string toString() const { return (getType() == IPv4AddressType) ? m_IPv4.toString() : m_IPv6.toString(); } + std::string toString() const { return (getType() == IPv4AddressType) ? m_IPv4.toString() : m_IPv6.toString(); } /** * @return Determine whether the object contains an IP version 4 address @@ -398,56 +396,61 @@ namespace pcpp * Determine whether the address is a multicast address * @return True if an address is multicast */ - bool isMulticast() const { return (getType() == IPv4AddressType) ? m_IPv4.isMulticast() : m_IPv6.isMulticast(); } + bool isMulticast() const + { + return (getType() == IPv4AddressType) ? m_IPv4.isMulticast() : m_IPv6.isMulticast(); + } /** * Get a reference to IPv4 address instance * @return The const reference to IPv4Address instance */ - const IPv4Address& getIPv4() const { return m_IPv4; } + const IPv4Address &getIPv4() const { return m_IPv4; } /** * Get a reference to IPv6 address instance * @return The const reference to IPv6Address instance */ - const IPv6Address& getIPv6() const { return m_IPv6; } + const IPv6Address &getIPv6() const { return m_IPv6; } /** * @return True if the address is zero, false otherwise */ - bool isZero() const { return (getType() == IPv4AddressType) ? m_IPv4 == IPv4Address::Zero : m_IPv6 == IPv6Address::Zero; } + bool isZero() const + { + return (getType() == IPv4AddressType) ? m_IPv4 == IPv4Address::Zero : m_IPv6 == IPv6Address::Zero; + } /** * Overload of the equal-to operator * @param[in] rhs The object to compare with * @return True if the addresses are equal, false otherwise */ - inline bool operator==(const IPAddress& rhs) const; + inline bool operator==(const IPAddress &rhs) const; /** * Overload of the less-than operator * @param[in] rhs The object to compare with * @return True if the address value is lower than the other address value, false otherwise */ - inline bool operator<(const IPAddress& rhs) const; + inline bool operator<(const IPAddress &rhs) const; /** * Overload of the not-equal-to operator * @param[in] rhs The object to compare with * @return True if the addresses are not equal, false otherwise */ - bool operator!=(const IPAddress& rhs) const { return !(*this == rhs); } + bool operator!=(const IPAddress &rhs) const { return !(*this == rhs); } - private: + private: uint8_t m_Type; IPv4Address m_IPv4; IPv6Address m_IPv6; }; - // implementation of inline methods - bool IPAddress::operator==(const IPAddress& rhs) const + bool IPAddress::operator==(const IPAddress &rhs) const { if (isIPv4()) return rhs.isIPv4() ? (m_IPv4 == rhs.m_IPv4) : false; @@ -455,9 +458,9 @@ namespace pcpp return rhs.isIPv6() ? m_IPv6 == rhs.m_IPv6 : false; } - bool IPAddress::operator<(const IPAddress& rhs) const + bool IPAddress::operator<(const IPAddress &rhs) const { - if(isIPv4()) + if (isIPv4()) { // treat IPv4 as less than IPv6 // If current obj is IPv4 and other is IPv6 return true @@ -466,35 +469,34 @@ namespace pcpp return rhs.isIPv6() ? m_IPv6 < rhs.m_IPv6 : false; } - IPAddress& IPAddress::operator=(const IPv4Address& addr) + IPAddress &IPAddress::operator=(const IPv4Address &addr) { m_Type = IPv4AddressType; m_IPv4 = addr; return *this; } - IPAddress& IPAddress::operator=(const IPv6Address& addr) + IPAddress &IPAddress::operator=(const IPv6Address &addr) { m_Type = IPv6AddressType; m_IPv6 = addr; return *this; } - /** * @class IPv4Network * A class representing IPv4 network definition */ class IPv4Network { - public: + public: /** * A constructor that creates an instance of the class out of an address and a full prefix length, * essentially making a network of consisting of only 1 address. * * @param address An address representing the network prefix. */ - explicit IPv4Network(const IPv4Address& address) : IPv4Network(address, 32u) {} + explicit IPv4Network(const IPv4Address &address) : IPv4Network(address, 32u) {} /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -504,7 +506,7 @@ namespace pcpp * @param prefixLen A number between 0 and 32 representing the prefix length. * @throws std::invalid_argument Prefix length is out of acceptable range. */ - IPv4Network(const IPv4Address& address, uint8_t prefixLen); + IPv4Network(const IPv4Address &address, uint8_t prefixLen); /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -516,7 +518,7 @@ namespace pcpp * starting with zeros that is valid is 0.0.0.0. * @throws std::invalid_argument The provided netmask is invalid. */ - IPv4Network(const IPv4Address& address, const std::string& netmask); + IPv4Network(const IPv4Address &address, const std::string &netmask); /** * A constructor that creates an instance of the class out of a string representing the network prefix and @@ -528,7 +530,7 @@ namespace pcpp * a valid netmask * @throws std::invalid_argument The provided string does not represent a valid address and netmask format. */ - IPv4Network(const std::string& addressAndNetmask); + IPv4Network(const std::string &addressAndNetmask); /** * @return The prefix length, for example: the prefix length of 10.10.10.10/255.0.0.0 is 8 @@ -542,7 +544,7 @@ namespace pcpp /** * @return The network prefix, for example: the network prefix of 10.10.10.10/16 is 10.10.0.0 - */ + */ IPv4Address getNetworkPrefix() const { return IPv4Address(m_NetworkPrefix); } /** @@ -567,14 +569,14 @@ namespace pcpp * @param address An IPv4 address * @return True is the address belongs to the network, false otherwise or if the address isn't valid */ - bool includes(const IPv4Address& address) const; + bool includes(const IPv4Address &address) const; /** * @param network An IPv4 network * @return True is the input network is completely included within this network, false otherwise, for example: * 10.10.10.10/16 includes 10.10.10.10/24 but doesn't include 10.10.10.10/8 */ - bool includes(const IPv4Network& network) const; + bool includes(const IPv4Network &network) const; /** * @return A string representation of the network in a format of NETWORK_PREFIX/PREFIX_LEN, for example: @@ -582,30 +584,29 @@ namespace pcpp */ std::string toString() const; - private: + private: uint32_t m_NetworkPrefix; uint32_t m_Mask; - bool isValidNetmask(const IPv4Address& netmaskAddress); - void initFromAddressAndPrefixLength(const IPv4Address& address, uint8_t prefixLen); - void initFromAddressAndNetmask(const IPv4Address& address, const IPv4Address& netmaskAddress); + bool isValidNetmask(const IPv4Address &netmaskAddress); + void initFromAddressAndPrefixLength(const IPv4Address &address, uint8_t prefixLen); + void initFromAddressAndNetmask(const IPv4Address &address, const IPv4Address &netmaskAddress); }; - /** * @class IPv6Network * A class representing IPv6 network definition */ class IPv6Network { - public: + public: /** * A constructor that creates an instance of the class out of an address and a full prefix length, * essentially making a network of consisting of only 1 address. * * @param address An address representing the network prefix. */ - explicit IPv6Network(const IPv6Address& address) : IPv6Network(address, 128u) {} + explicit IPv6Network(const IPv6Address &address) : IPv6Network(address, 128u) {} /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -615,7 +616,7 @@ namespace pcpp * @param prefixLen A number between 0 and 128 representing the prefix length. * @throws std::invalid_argument Prefix length is out of acceptable range. */ - IPv6Network(const IPv6Address& address, uint8_t prefixLen); + IPv6Network(const IPv6Address &address, uint8_t prefixLen); /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -627,7 +628,7 @@ namespace pcpp * starting with zeros that is valid is all zeros (::). * @throws std::invalid_argument The provided netmask is invalid. */ - IPv6Network(const IPv6Address& address, const std::string& netmask); + IPv6Network(const IPv6Address &address, const std::string &netmask); /** * A constructor that creates an instance of the class out of a string representing the network prefix and @@ -639,7 +640,7 @@ namespace pcpp * and IPV6_NETMASK is a valid IPv6 netmask * @throws std::invalid_argument The provided string does not represent a valid address and netmask format. */ - IPv6Network(const std::string& addressAndNetmask); + IPv6Network(const std::string &addressAndNetmask); /** * @return The prefix length, for example: the prefix length of 3546::/ffff:: is 16 @@ -653,13 +654,13 @@ namespace pcpp /** * @return The network prefix, for example: the network prefix of 3546:f321::/16 is 3546:: - */ + */ IPv6Address getNetworkPrefix() const { return IPv6Address(m_NetworkPrefix); } /** - * @return The lowest non-reserved IPv6 address in this network, for example: the lowest address in 3546::/16 is - * 3546::1 - */ + * @return The lowest non-reserved IPv6 address in this network, for example: the lowest address in 3546::/16 is + * 3546::1 + */ IPv6Address getLowestAddress() const; /** @@ -678,14 +679,14 @@ namespace pcpp * @param address An IPv6 address * @return True is the address belongs to the network, false otherwise or if the address isn't valid */ - bool includes(const IPv6Address& address) const; + bool includes(const IPv6Address &address) const; /** * @param network An IPv6 network * @return True is the input network is completely included within this network, false otherwise, for example: * 3546::/64 includes 3546::/120 but doesn't include 3546::/16 */ - bool includes(const IPv6Network& network) const; + bool includes(const IPv6Network &network) const; /** * @return A string representation of the network in a format of NETWORK_PREFIX/PREFIX_LEN, for example: @@ -693,40 +694,40 @@ namespace pcpp */ std::string toString() const; - private: + private: uint8_t m_NetworkPrefix[16]; uint8_t m_Mask[16]; - bool isValidNetmask(const IPv6Address& netmaskAddress); - void initFromAddressAndPrefixLength(const IPv6Address& address, uint8_t prefixLen); - void initFromAddressAndNetmask(const IPv6Address& address, const IPv6Address& netmaskAddress); + bool isValidNetmask(const IPv6Address &netmaskAddress); + void initFromAddressAndPrefixLength(const IPv6Address &address, uint8_t prefixLen); + void initFromAddressAndNetmask(const IPv6Address &address, const IPv6Address &netmaskAddress); }; - /** * @class IPNetwork * A class representing version independent IP network definition, both IPv4 and IPv6 are included */ class IPNetwork { - public: + public: /** * A constructor that creates an instance of the class out of an IP address and a full prefix length, * essentially making a network of consisting of only 1 address. * * @param address An address representing the network prefix. */ - explicit IPNetwork(const IPAddress& address) : IPNetwork(address, address.isIPv4() ? 32u : 128u) {} + explicit IPNetwork(const IPAddress &address) : IPNetwork(address, address.isIPv4() ? 32u : 128u) {} /** * A constructor that creates an instance of the class out of an address representing the network prefix * and a prefix length * @param address An address representing the network prefix. If the address is invalid std::invalid_argument * exception is thrown - * @param prefixLen A number representing the prefix length. Allowed ranges are 0 - 32 for IPv4 networks and 0 - 128 for IPv6 networks. + * @param prefixLen A number representing the prefix length. Allowed ranges are 0 - 32 for IPv4 networks and 0 - + * 128 for IPv6 networks. * @throws std::invalid_argument Prefix length is out of acceptable range. */ - IPNetwork(const IPAddress& address, uint8_t prefixLen) + IPNetwork(const IPAddress &address, uint8_t prefixLen) { if (address.isIPv4()) { @@ -749,7 +750,7 @@ namespace pcpp * The only netmask starting with zeros that is valid is all zeros (:: or 0.0.0.0). * @throws std::invalid_argument The provided netmask is invalid. */ - IPNetwork(const IPAddress& address, const std::string& netmask) + IPNetwork(const IPAddress &address, const std::string &netmask) { if (address.isIPv4()) { @@ -771,13 +772,13 @@ namespace pcpp * is a valid netmask for this type of network (IPv4 or IPv6 network) * @throws std::invalid_argument The provided string does not represent a valid address and netmask format. */ - IPNetwork(const std::string& addressAndNetmask) + IPNetwork(const std::string &addressAndNetmask) { try { m_IPv4Network = std::unique_ptr(new IPv4Network(addressAndNetmask)); } - catch (const std::invalid_argument&) + catch (const std::invalid_argument &) { m_IPv6Network = std::unique_ptr(new IPv6Network(addressAndNetmask)); } @@ -787,7 +788,7 @@ namespace pcpp * A copy c'tor for this class * @param other The instance to copy from */ - IPNetwork(const IPNetwork& other) + IPNetwork(const IPNetwork &other) { if (other.m_IPv4Network) { @@ -805,7 +806,7 @@ namespace pcpp * @param[in] other An instance of IPNetwork to assign * @return A reference to the assignee */ - IPNetwork& operator=(const IPNetwork& other) + IPNetwork &operator=(const IPNetwork &other) { if (other.isIPv4Network()) { @@ -822,7 +823,7 @@ namespace pcpp * @param[in] other An instance of IPv4Network to assign * @return A reference to the assignee */ - IPNetwork& operator=(const IPv4Network& other) + IPNetwork &operator=(const IPv4Network &other) { if (m_IPv4Network) { @@ -844,7 +845,7 @@ namespace pcpp * @param[in] other An instance of IPv6Network to assign * @return A reference to the assignee */ - IPNetwork& operator=(const IPv6Network& other) + IPNetwork &operator=(const IPv6Network &other) { if (m_IPv4Network) { @@ -871,8 +872,9 @@ namespace pcpp } /** - * @return The netmask, for example: the netmask of 3546::/16 is ffff::, the netmask of 10.10.10.10/8 is 255.0.0.0 - */ + * @return The netmask, for example: the netmask of 3546::/16 is ffff::, the netmask of 10.10.10.10/8 is + * 255.0.0.0 + */ std::string getNetmask() const { return (m_IPv4Network != nullptr ? m_IPv4Network->getNetmask() : m_IPv6Network->getNetmask()); @@ -881,19 +883,21 @@ namespace pcpp /** * @return The network prefix, for example: the network prefix of 3546:f321::/16 is 3546::, the network prefix * of 10.10.10.10/16 is 10.10.0.0 - */ + */ IPAddress getNetworkPrefix() const { - return (m_IPv4Network != nullptr ? IPAddress(m_IPv4Network->getNetworkPrefix()) : IPAddress(m_IPv6Network->getNetworkPrefix())); + return (m_IPv4Network != nullptr ? IPAddress(m_IPv4Network->getNetworkPrefix()) + : IPAddress(m_IPv6Network->getNetworkPrefix())); } /** - * @return The lowest non-reserved IP address in this network, for example: the lowest address in 3546::/16 is - * 3546::1, the lowest address in 10.10.10.10/16 is 10.10.0.1 - */ + * @return The lowest non-reserved IP address in this network, for example: the lowest address in 3546::/16 is + * 3546::1, the lowest address in 10.10.10.10/16 is 10.10.0.1 + */ IPAddress getLowestAddress() const { - return (m_IPv4Network != nullptr ? IPAddress(m_IPv4Network->getLowestAddress()) : IPAddress(m_IPv6Network->getLowestAddress())); + return (m_IPv4Network != nullptr ? IPAddress(m_IPv4Network->getLowestAddress()) + : IPAddress(m_IPv6Network->getLowestAddress())); } /** @@ -902,7 +906,8 @@ namespace pcpp */ IPAddress getHighestAddress() const { - return (m_IPv4Network != nullptr ? IPAddress(m_IPv4Network->getHighestAddress()) : IPAddress(m_IPv6Network->getHighestAddress())); + return (m_IPv4Network != nullptr ? IPAddress(m_IPv4Network->getHighestAddress()) + : IPAddress(m_IPv6Network->getHighestAddress())); } /** @@ -912,30 +917,25 @@ namespace pcpp */ uint64_t getTotalAddressCount() const { - return (m_IPv4Network != nullptr ? m_IPv4Network->getTotalAddressCount() : m_IPv6Network->getTotalAddressCount()); + return (m_IPv4Network != nullptr ? m_IPv4Network->getTotalAddressCount() + : m_IPv6Network->getTotalAddressCount()); } /** * @return True if this is an IPv4 network, false otherwise */ - bool isIPv4Network() const - { - return m_IPv4Network != nullptr; - } + bool isIPv4Network() const { return m_IPv4Network != nullptr; } /** * @return True if this is an IPv6 network, false otherwise */ - bool isIPv6Network() const - { - return m_IPv6Network != nullptr; - } + bool isIPv6Network() const { return m_IPv6Network != nullptr; } /** * @param address An IP address * @return True is the address belongs to the network, false otherwise or if the address isn't valid */ - bool includes(const IPAddress& address) const + bool includes(const IPAddress &address) const { if (m_IPv4Network != nullptr) { @@ -961,7 +961,7 @@ namespace pcpp * @param network An IP network * @return True is the input network is completely included within this network, false otherwise */ - bool includes(const IPNetwork& network) const + bool includes(const IPNetwork &network) const { if (m_IPv4Network != nullptr) { @@ -992,43 +992,43 @@ namespace pcpp return (m_IPv4Network != nullptr ? m_IPv4Network->toString() : m_IPv6Network->toString()); } - private: + private: std::unique_ptr m_IPv4Network; std::unique_ptr m_IPv6Network; }; } // namespace pcpp -inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv4Address& ipv4Address) +inline std::ostream &operator<<(std::ostream &os, const pcpp::IPv4Address &ipv4Address) { os << ipv4Address.toString(); return os; } -inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv6Address& ipv6Address) +inline std::ostream &operator<<(std::ostream &os, const pcpp::IPv6Address &ipv6Address) { os << ipv6Address.toString(); return os; } -inline std::ostream& operator<<(std::ostream& os, const pcpp::IPAddress& ipAddress) +inline std::ostream &operator<<(std::ostream &os, const pcpp::IPAddress &ipAddress) { os << ipAddress.toString(); return os; } -inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv4Network& network) +inline std::ostream &operator<<(std::ostream &os, const pcpp::IPv4Network &network) { os << network.toString(); return os; } -inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv6Network& network) +inline std::ostream &operator<<(std::ostream &os, const pcpp::IPv6Network &network) { os << network.toString(); return os; } -inline std::ostream& operator<<(std::ostream& os, const pcpp::IPNetwork& network) +inline std::ostream &operator<<(std::ostream &os, const pcpp::IPNetwork &network) { os << network.toString(); return os; diff --git a/Common++/header/IpAddressUtils.h b/Common++/header/IpAddressUtils.h index f561a634a7..c881779016 100644 --- a/Common++/header/IpAddressUtils.h +++ b/Common++/header/IpAddressUtils.h @@ -21,83 +21,83 @@ namespace pcpp * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPv4Address& lhs, const in_addr& rhs); + bool operator==(const IPv4Address &lhs, const in_addr &rhs); /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const IPv4Address& lhs, const in_addr& rhs) { return !(lhs == rhs); } + inline bool operator!=(const IPv4Address &lhs, const in_addr &rhs) { return !(lhs == rhs); } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - inline bool operator==(const in_addr& lhs, const IPv4Address& rhs) { return rhs == lhs; } + inline bool operator==(const in_addr &lhs, const IPv4Address &rhs) { return rhs == lhs; } /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const in_addr& lhs, const IPv4Address& rhs) { return !(lhs == rhs); } + inline bool operator!=(const in_addr &lhs, const IPv4Address &rhs) { return !(lhs == rhs); } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPv6Address& lhs, const in6_addr& rhs); + bool operator==(const IPv6Address &lhs, const in6_addr &rhs); /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const IPv6Address& lhs, const in6_addr& rhs) { return !(lhs == rhs); } + inline bool operator!=(const IPv6Address &lhs, const in6_addr &rhs) { return !(lhs == rhs); } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - inline bool operator==(const in6_addr& lhs, const IPv6Address& rhs) { return rhs == lhs; } + inline bool operator==(const in6_addr &lhs, const IPv6Address &rhs) { return rhs == lhs; } /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const in6_addr& lhs, const IPv6Address& rhs) { return !(lhs == rhs); } + inline bool operator!=(const in6_addr &lhs, const IPv6Address &rhs) { return !(lhs == rhs); } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPAddress& lhs, const in_addr& rhs); + bool operator==(const IPAddress &lhs, const in_addr &rhs); /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const IPAddress& lhs, const in_addr& rhs) { return !(lhs == rhs); } + inline bool operator!=(const IPAddress &lhs, const in_addr &rhs) { return !(lhs == rhs); } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - inline bool operator==(const in_addr& lhs, const IPAddress& rhs) { return rhs == lhs; } + inline bool operator==(const in_addr &lhs, const IPAddress &rhs) { return rhs == lhs; } /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const in_addr& lhs, const IPAddress& rhs) { return !(lhs == rhs); } + inline bool operator!=(const in_addr &lhs, const IPAddress &rhs) { return !(lhs == rhs); } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPAddress& lhs, const in6_addr& rhs); + bool operator==(const IPAddress &lhs, const in6_addr &rhs); /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const IPAddress& lhs, const in6_addr& rhs) { return !(lhs == rhs); } + inline bool operator!=(const IPAddress &lhs, const in6_addr &rhs) { return !(lhs == rhs); } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - inline bool operator==(const in6_addr& lhs, const IPAddress& rhs) { return rhs == lhs; } + inline bool operator==(const in6_addr &lhs, const IPAddress &rhs) { return rhs == lhs; } /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const in6_addr& lhs, const IPAddress& rhs) { return !(lhs == rhs); } -} + inline bool operator!=(const in6_addr &lhs, const IPAddress &rhs) { return !(lhs == rhs); } +} // namespace pcpp diff --git a/Common++/header/IpUtils.h b/Common++/header/IpUtils.h index 6ad4d83146..5ddcdca6a8 100644 --- a/Common++/header/IpUtils.h +++ b/Common++/header/IpUtils.h @@ -2,20 +2,20 @@ #include #ifdef __linux__ -#include #include +#include #endif #if defined(__APPLE__) -#include #include +#include #endif #if defined(_WIN32) #include #endif #if defined(__FreeBSD__) -#include -#include #include +#include +#include #endif /// @file @@ -33,7 +33,7 @@ * @param[in] size 'dst' Maximum size * @return pointer to presentation format address ('dst'), or NULL (see errno). */ -const char* inet_ntop(int af, const void* src, char* dst, size_t size); +const char *inet_ntop(int af, const void *src, char *dst, size_t size); /** * Convert from presentation format (which usually means ASCII printable) @@ -46,10 +46,9 @@ const char* inet_ntop(int af, const void* src, char* dst, size_t size); * 0 if the address wasn't valid ('dst' is untouched in this case); * -1 if some other error occurred ('dst' is untouched in this case, too) */ -int inet_pton(int af, const char* src, void* dst); +int inet_pton(int af, const char *src, void *dst); #endif - /** * \namespace pcpp * \brief The main namespace for the PcapPlusPlus lib @@ -64,14 +63,14 @@ namespace pcpp * @return Address in in_addr format * @throws std::invalid_argument Sockaddr family is not AF_INET or sockaddr is nullptr. */ - in_addr* sockaddr2in_addr(sockaddr* sa); + in_addr *sockaddr2in_addr(sockaddr *sa); /** * Attempt to extract IPv4 address from sockaddr * @param[in] sa - input sockaddr * @return Pointer to address in in_addr format or nullptr if extraction fails. */ - in_addr* try_sockaddr2in_addr(sockaddr* sa); + in_addr *try_sockaddr2in_addr(sockaddr *sa); /** * Extract IPv6 address from sockaddr @@ -79,23 +78,24 @@ namespace pcpp * @return Address in in6_addr format * @throws std::invalid_argument Sockaddr family is not AF_INET6 or sockaddr is nullptr. */ - in6_addr* sockaddr2in6_addr(sockaddr* sa); + in6_addr *sockaddr2in6_addr(sockaddr *sa); /** * Attempt to extract IPv6 address from sockaddr * @param[in] sa - input sockaddr * @return Pointer to address in in6_addr format or nullptr if extraction fails. */ - in6_addr* try_sockaddr2in6_addr(sockaddr* sa); + in6_addr *try_sockaddr2in6_addr(sockaddr *sa); /** * Converts a sockaddr format address to its string representation * @param[in] sa Address in sockaddr format * @param[out] resultString String representation of the address * @param[in] resultBufLen Length of the result buffer. - * @throws std::invalid_argument Sockaddr family is not AF_INET or AF_INET6, sockaddr is nullptr or the result str buffer is insufficient. + * @throws std::invalid_argument Sockaddr family is not AF_INET or AF_INET6, sockaddr is nullptr or the result + * str buffer is insufficient. */ - void sockaddr2string(sockaddr const* sa, char* resultString, size_t resultBufLen); + void sockaddr2string(sockaddr const *sa, char *resultString, size_t resultBufLen); /** * Convert a in_addr format address to 32bit representation diff --git a/Common++/header/LRUList.h b/Common++/header/LRUList.h index 89eb1c9470..7cb84f96ed 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #if __cplusplus > 199711L || _MSC_VER >= 1800 #include @@ -18,16 +18,14 @@ namespace pcpp /** * @class LRUList - * A template class that implements a LRU cache with limited size. Each time the user puts an element it goes to head of the - * list as the most recently used element (if the element was already in the list it advances to the head of the list). - * The last element in the list is the one least recently used and will be pulled out of the list if it reaches its max size - * and a new element comes in. All actions on this LRU list are O(1) + * A template class that implements a LRU cache with limited size. Each time the user puts an element it goes to + * head of the list as the most recently used element (if the element was already in the list it advances to the + * head of the list). The last element in the list is the one least recently used and will be pulled out of the list + * if it reaches its max size and a new element comes in. All actions on this LRU list are O(1) */ - template - class LRUList + template class LRUList { - public: - + public: typedef typename std::list::iterator ListIterator; typedef typename std::unordered_map::iterator MapIterator; @@ -35,27 +33,27 @@ namespace pcpp * A c'tor for this class * @param[in] maxSize The max size this list can go */ - explicit LRUList(size_t maxSize) - { - m_MaxSize = maxSize; - } + explicit LRUList(size_t maxSize) { m_MaxSize = maxSize; } /** - * Puts an element in the list. This element will be inserted (or advanced if it already exists) to the head of the - * list as the most recently used element. If the list already reached its max size and the element is new this method - * will remove the least recently used element and return a value in deletedValue. Method complexity is O(log(getSize())). - * This is a optimized version of the method T* put(const T&). + * Puts an element in the list. This element will be inserted (or advanced if it already exists) to the head of + * the list as the most recently used element. If the list already reached its max size and the element is new + * this method will remove the least recently used element and return a value in deletedValue. Method complexity + * is O(log(getSize())). This is a optimized version of the method T* put(const T&). * @param[in] element The element to insert or to advance to the head of the list (if already exists) * @param[out] deletedValue The value of deleted element if a pointer is not NULL. This parameter is optional. * @return 0 if the list didn't reach its max size, 1 otherwise. In case the list already reached its max size - * and deletedValue is not NULL the value of deleted element is copied into the place the deletedValue points to. + * and deletedValue is not NULL the value of deleted element is copied into the place the deletedValue points + * to. */ - int put(const T& element, T* deletedValue = NULL) + int put(const T &element, T *deletedValue = NULL) { m_CacheItemsList.push_front(element); - // Inserting a new element. If an element with an equivalent key already exists the method returns an iterator to the element that prevented the insertion - std::pair pair = m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin())); + // Inserting a new element. If an element with an equivalent key already exists the method returns an + // iterator to the element that prevented the insertion + std::pair pair = + m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin())); if (pair.second == false) // already exists { m_CacheItemsList.erase(pair.first->second); @@ -85,25 +83,19 @@ namespace pcpp * Get the most recently used element (the one at the beginning of the list) * @return The most recently used element */ - const T& getMRUElement() const - { - return m_CacheItemsList.front(); - } + const T &getMRUElement() const { return m_CacheItemsList.front(); } /** * Get the least recently used element (the one at the end of the list) * @return The least recently used element */ - const T& getLRUElement() const - { - return m_CacheItemsList.back(); - } + const T &getLRUElement() const { return m_CacheItemsList.back(); } /** * Erase an element from the list. If element isn't found in the list nothing happens * @param[in] element The element to erase */ - void eraseElement(const T& element) + void eraseElement(const T &element) { MapIterator iter = m_CacheItemsMap.find(element); if (iter == m_CacheItemsMap.end()) @@ -123,7 +115,7 @@ namespace pcpp */ size_t getSize() const { return m_CacheItemsMap.size(); } - private: + private: std::list m_CacheItemsList; std::unordered_map m_CacheItemsMap; size_t m_MaxSize; diff --git a/Common++/header/Logger.h b/Common++/header/Logger.h index ad73716274..91866ee317 100644 --- a/Common++/header/Logger.h +++ b/Common++/header/Logger.h @@ -1,10 +1,10 @@ #pragma once -#include +#include #include #include -#include #include +#include #ifndef LOG_MODULE #define LOG_MODULE UndefinedLogModule @@ -17,24 +17,27 @@ #define PCAPPP_FILENAME __FILE__ #endif -#define PCPP_LOG(level, message) do \ - { \ - std::ostringstream* sstream = pcpp::Logger::getInstance().internalCreateLogStream(); \ - (*sstream) << message; \ - pcpp::Logger::getInstance().internalPrintLogMessage(sstream, level, PCAPPP_FILENAME, __FUNCTION__, __LINE__); \ - } while(0) +#define PCPP_LOG(level, message) \ + do \ + { \ + std::ostringstream *sstream = pcpp::Logger::getInstance().internalCreateLogStream(); \ + (*sstream) << message; \ + pcpp::Logger::getInstance().internalPrintLogMessage(sstream, level, PCAPPP_FILENAME, __FUNCTION__, __LINE__); \ + } while (0) -#define PCPP_LOG_DEBUG(message) do \ - { \ - if (pcpp::Logger::getInstance().logsEnabled() && pcpp::Logger::getInstance().isDebugEnabled(LOG_MODULE)) \ - { \ - PCPP_LOG(pcpp::Logger::Debug, message); \ - } \ - } while(0) +#define PCPP_LOG_DEBUG(message) \ + do \ + { \ + if (pcpp::Logger::getInstance().logsEnabled() && pcpp::Logger::getInstance().isDebugEnabled(LOG_MODULE)) \ + { \ + PCPP_LOG(pcpp::Logger::Debug, message); \ + } \ + } while (0) -#define PCPP_LOG_ERROR(message) do \ - { \ - PCPP_LOG(pcpp::Logger::Error, message); \ +#define PCPP_LOG_ERROR(message) \ + do \ + { \ + PCPP_LOG(pcpp::Logger::Error, message); \ } while (0) /// @file @@ -52,64 +55,64 @@ namespace pcpp enum LogModule { UndefinedLogModule, - CommonLogModuleIpUtils, ///< IP Utils module (Common++) - CommonLogModuleTablePrinter, ///< Table printer module (Common++) - CommonLogModuleGenericUtils, ///< Generic Utils (Common++) - PacketLogModuleRawPacket, ///< RawPacket module (Packet++) - PacketLogModulePacket, ///< Packet module (Packet++) - PacketLogModuleLayer, ///< Layer module (Packet++) - PacketLogModuleAsn1Codec, ///< Asn1Codec module (Packet++) - PacketLogModuleArpLayer, ///< ArpLayer module (Packet++) - PacketLogModuleEthLayer, ///< EthLayer module (Packet++) - PacketLogModuleIPv4Layer, ///< IPv4Layer module (Packet++) - PacketLogModuleIPv6Layer, ///< IPv6Layer module (Packet++) - PacketLogModulePayloadLayer, ///< PayloadLayer module (Packet++) - PacketLogModuleTcpLayer, ///< TcpLayer module (Packet++) - PacketLogModuleUdpLayer, ///< UdpLayer module (Packet++) - PacketLogModuleVlanLayer, ///< VlanLayer module (Packet++) - PacketLogModuleHttpLayer, ///< HttpLayer module (Packet++) - PacketLogModulePPPoELayer, ///< PPPoELayer module (Packet++) - PacketLogModuleDnsLayer, ///< DnsLayer module (Packet++) - PacketLogModuleMplsLayer, ///< MplsLayer module (Packet++) - PacketLogModuleIcmpLayer, ///< IcmpLayer module (Packet++) - PacketLogModuleIcmpV6Layer, ///< IcmpV6Layer module (Packet++) - PacketLogModuleGreLayer, ///< GreLayer module (Packet++) - PacketLogModuleSSLLayer, ///< SSLLayer module (Packet++) - PacketLogModuleSllLayer, ///< SllLayer module (Packet++) - PacketLogModuleNflogLayer, ///< NflogLayer module (Packet++) - PacketLogModuleDhcpLayer, ///< DhcpLayer module (Packet++) - PacketLogModuleDhcpV6Layer, ///< DhcpV6Layer module (Packet++) - PacketLogModuleIgmpLayer, ///< IgmpLayer module (Packet++) - PacketLogModuleSipLayer, ///< SipLayer module (Packet++) - PacketLogModuleSdpLayer, ///< SdpLayer module (Packet++) - PacketLogModuleRadiusLayer, ///< RadiusLayer module (Packet++) - PacketLogModuleGtpLayer, ///< GtpLayer module (Packet++) - PacketLogModuleBgpLayer, ///< GtpLayer module (Packet++) - PacketLogModuleSSHLayer, ///< SSHLayer module (Packet++) - PacketLogModuleVrrpLayer, ///< Vrrp Record module (Packet++) - PacketLogModuleTcpReassembly, ///< TcpReassembly module (Packet++) - PacketLogModuleIPReassembly, ///< IPReassembly module (Packet++) - PacketLogModuleIPSecLayer, ///< IPSecLayers module (Packet++) - PacketLogModuleNtpLayer, ///< NtpLayer module (Packet++) - PacketLogModuleTelnetLayer, ///< TelnetLayer module (Packet++) - PacketLogModuleStpLayer, ///< StpLayer module (Packet++) - PacketLogModuleLLCLayer, ///< LLCLayer module (Packet++) - PacketLogModuleNdpLayer, ///< NdpLayer module (Packet++) - PacketLogModuleFtpLayer, ///< FtpLayer module (Packet++) - PacketLogModuleSomeIpLayer, ///< SomeIpLayer module (Packet++) - PacketLogModuleSomeIpSdLayer, ///< SomeIpSdLayer module (Packet++) - PacketLogModuleWakeOnLanLayer, ///< WakeOnLanLayer module (Packet++) - PacketLogModuleSmtpLayer, ///< SmtpLayer module (Packet++) + CommonLogModuleIpUtils, ///< IP Utils module (Common++) + CommonLogModuleTablePrinter, ///< Table printer module (Common++) + CommonLogModuleGenericUtils, ///< Generic Utils (Common++) + PacketLogModuleRawPacket, ///< RawPacket module (Packet++) + PacketLogModulePacket, ///< Packet module (Packet++) + PacketLogModuleLayer, ///< Layer module (Packet++) + PacketLogModuleAsn1Codec, ///< Asn1Codec module (Packet++) + PacketLogModuleArpLayer, ///< ArpLayer module (Packet++) + PacketLogModuleEthLayer, ///< EthLayer module (Packet++) + PacketLogModuleIPv4Layer, ///< IPv4Layer module (Packet++) + PacketLogModuleIPv6Layer, ///< IPv6Layer module (Packet++) + PacketLogModulePayloadLayer, ///< PayloadLayer module (Packet++) + PacketLogModuleTcpLayer, ///< TcpLayer module (Packet++) + PacketLogModuleUdpLayer, ///< UdpLayer module (Packet++) + PacketLogModuleVlanLayer, ///< VlanLayer module (Packet++) + PacketLogModuleHttpLayer, ///< HttpLayer module (Packet++) + PacketLogModulePPPoELayer, ///< PPPoELayer module (Packet++) + PacketLogModuleDnsLayer, ///< DnsLayer module (Packet++) + PacketLogModuleMplsLayer, ///< MplsLayer module (Packet++) + PacketLogModuleIcmpLayer, ///< IcmpLayer module (Packet++) + PacketLogModuleIcmpV6Layer, ///< IcmpV6Layer module (Packet++) + PacketLogModuleGreLayer, ///< GreLayer module (Packet++) + PacketLogModuleSSLLayer, ///< SSLLayer module (Packet++) + PacketLogModuleSllLayer, ///< SllLayer module (Packet++) + PacketLogModuleNflogLayer, ///< NflogLayer module (Packet++) + PacketLogModuleDhcpLayer, ///< DhcpLayer module (Packet++) + PacketLogModuleDhcpV6Layer, ///< DhcpV6Layer module (Packet++) + PacketLogModuleIgmpLayer, ///< IgmpLayer module (Packet++) + PacketLogModuleSipLayer, ///< SipLayer module (Packet++) + PacketLogModuleSdpLayer, ///< SdpLayer module (Packet++) + PacketLogModuleRadiusLayer, ///< RadiusLayer module (Packet++) + PacketLogModuleGtpLayer, ///< GtpLayer module (Packet++) + PacketLogModuleBgpLayer, ///< GtpLayer module (Packet++) + PacketLogModuleSSHLayer, ///< SSHLayer module (Packet++) + PacketLogModuleVrrpLayer, ///< Vrrp Record module (Packet++) + PacketLogModuleTcpReassembly, ///< TcpReassembly module (Packet++) + PacketLogModuleIPReassembly, ///< IPReassembly module (Packet++) + PacketLogModuleIPSecLayer, ///< IPSecLayers module (Packet++) + PacketLogModuleNtpLayer, ///< NtpLayer module (Packet++) + PacketLogModuleTelnetLayer, ///< TelnetLayer module (Packet++) + PacketLogModuleStpLayer, ///< StpLayer module (Packet++) + PacketLogModuleLLCLayer, ///< LLCLayer module (Packet++) + PacketLogModuleNdpLayer, ///< NdpLayer module (Packet++) + PacketLogModuleFtpLayer, ///< FtpLayer module (Packet++) + PacketLogModuleSomeIpLayer, ///< SomeIpLayer module (Packet++) + PacketLogModuleSomeIpSdLayer, ///< SomeIpSdLayer module (Packet++) + PacketLogModuleWakeOnLanLayer, ///< WakeOnLanLayer module (Packet++) + PacketLogModuleSmtpLayer, ///< SmtpLayer module (Packet++) PcapLogModuleWinPcapLiveDevice, ///< WinPcapLiveDevice module (Pcap++) - PcapLogModuleRemoteDevice, ///< WinPcapRemoteDevice module (Pcap++) - PcapLogModuleLiveDevice, ///< PcapLiveDevice module (Pcap++) - PcapLogModuleFileDevice, ///< FileDevice module (Pcap++) - PcapLogModulePfRingDevice, ///< PfRingDevice module (Pcap++) - PcapLogModuleMBufRawPacket, ///< MBufRawPacket module (Pcap++) - PcapLogModuleDpdkDevice, ///< DpdkDevice module (Pcap++) - PcapLogModuleKniDevice, ///< KniDevice module (Pcap++) - PcapLogModuleXdpDevice, ///< XdpDevice module (Pcap++) - NetworkUtils, ///< NetworkUtils module (Pcap++) + PcapLogModuleRemoteDevice, ///< WinPcapRemoteDevice module (Pcap++) + PcapLogModuleLiveDevice, ///< PcapLiveDevice module (Pcap++) + PcapLogModuleFileDevice, ///< FileDevice module (Pcap++) + PcapLogModulePfRingDevice, ///< PfRingDevice module (Pcap++) + PcapLogModuleMBufRawPacket, ///< MBufRawPacket module (Pcap++) + PcapLogModuleDpdkDevice, ///< DpdkDevice module (Pcap++) + PcapLogModuleKniDevice, ///< KniDevice module (Pcap++) + PcapLogModuleXdpDevice, ///< XdpDevice module (Pcap++) + NetworkUtils, ///< NetworkUtils module (Pcap++) NumOfLogModules }; @@ -119,13 +122,14 @@ namespace pcpp * PcapPlusPlus uses this logger to output both error and debug logs. * There are currently 3 log levels: Logger#Error, Logger#Info and Logger#Debug. * - * PcapPlusPlus is divided into modules (described in #LogModule enum). The user can set the log level got each module or to all modules at once. - * The default is Logger#Info which outputs only error messages. Changing log level for modules can be done dynamically while the application is running. + * PcapPlusPlus is divided into modules (described in #LogModule enum). The user can set the log level got each + * module or to all modules at once. The default is Logger#Info which outputs only error messages. Changing log + * level for modules can be done dynamically while the application is running. * * The logger also exposes a method to retrieve the last error log message. * - * Logs are printed to console by default in a certain format. The user can set a different print function to change the format or to print to - * other media (such as files, etc.). + * Logs are printed to console by default in a certain format. The user can set a different print function to change + * the format or to print to other media (such as files, etc.). * * PcapPlusPlus logger is a singleton which can be reached from anywhere in the code. * @@ -133,15 +137,16 @@ namespace pcpp */ class Logger { - public: + public: /** - * An enum representing the log level. Currently 3 log levels are supported: Error, Info and Debug. Info is the default log level + * An enum representing the log level. Currently 3 log levels are supported: Error, Info and Debug. Info is the + * default log level */ enum LogLevel { Error, ///< Error log level - Info, ///< Info log level - Debug ///< Debug log level + Info, ///< Info log level + Debug ///< Debug log level }; /** @@ -153,7 +158,8 @@ namespace pcpp * @param[in] method The method in PcapPlusPlus code the log message is coming from * @param[in] line The line in PcapPlusPlus code the log message is coming from */ - typedef void (*LogPrinter)(LogLevel logLevel, const std::string& logMessage, const std::string& file, const std::string& method, const int line); + typedef void (*LogPrinter)(LogLevel logLevel, const std::string &logMessage, const std::string &file, + const std::string &method, const int line); /** * A static method for converting the log level enum to a string. @@ -187,7 +193,11 @@ namespace pcpp * Set all PcapPlusPlus modules to a certain log level * @param[in] level The log level to set all modules to */ - void setAllModulesToLogLevel(LogLevel level) { for (int i=1; i - Logger& operator<<(const T& msg) + template Logger &operator<<(const T &msg) { (*m_LogStream) << msg; return *this; } - std::ostringstream * internalCreateLogStream(); + std::ostringstream *internalCreateLogStream(); /** * An internal method to print log messages. Shouldn't be used externally. */ - void internalPrintLogMessage(std::ostringstream* logStream, Logger::LogLevel logLevel, const char* file, const char* method, int line); + void internalPrintLogMessage(std::ostringstream *logStream, Logger::LogLevel logLevel, const char *file, + const char *method, int line); /** * Get access to Logger singleton * @todo: make this singleton thread-safe/ * @return a pointer to the Logger singleton - **/ - static Logger& getInstance() + **/ + static Logger &getInstance() { static Logger instance; return instance; } - private: + + private: bool m_LogsEnabled; Logger::LogLevel m_LogModulesArray[NumOfLogModules]; LogPrinter m_LogPrinter; std::string m_LastError; - std::ostringstream* m_LogStream; + std::ostringstream *m_LogStream; // private c'tor - this class is a singleton Logger(); - static void defaultLogPrinter(LogLevel logLevel, const std::string& logMessage, const std::string& file, const std::string& method, const int line); + static void defaultLogPrinter(LogLevel logLevel, const std::string &logMessage, const std::string &file, + const std::string &method, const int line); }; } // namespace pcpp diff --git a/Common++/header/MacAddress.h b/Common++/header/MacAddress.h index 854e03ffe1..4270501105 100644 --- a/Common++/header/MacAddress.h +++ b/Common++/header/MacAddress.h @@ -1,12 +1,12 @@ #pragma once -#include -#include -#include -#include #include +#include #include #include +#include +#include +#include /// @file @@ -23,7 +23,7 @@ namespace pcpp */ class MacAddress { - public: + public: /** * Default constructor for this class. * Initializes the address as 00:00:00:00:00:00. @@ -36,23 +36,22 @@ namespace pcpp * If the byte array is invalid, the constructor throws an exception. * @param[in] addr A pointer to the byte array containing 6 bytes representing the MAC address */ - explicit MacAddress(const uint8_t* addr) { memcpy(m_Address, addr, sizeof(m_Address)); } + explicit MacAddress(const uint8_t *addr) { memcpy(m_Address, addr, sizeof(m_Address)); } /** * A constructor that creates an instance of the class out of a std::string. * If the string doesn't represent a valid MAC address, the constructor throws an exception. - * @param[in] addr the string representing the MAC address in format "00:00:00:00:00:00" + * @param[in] addr the string representing the MAC address in format "00:00:00:00:00:00" */ - explicit MacAddress(const std::string& addr); + explicit MacAddress(const std::string &addr); /** * A template constructor that creates an instance of the class out of a string convertible to std::string. * If the string doesn't represent a valid MAC address, the constructor throws an exception. * @param[in] addr the string representing the MAC address in format "00:00:00:00:00:00" */ - template::value>::type> - MacAddress(const T& addr) : MacAddress(static_cast(addr)) {}; - + template ::value>::type> + MacAddress(const T &addr) : MacAddress(static_cast(addr)){}; /** * A constructor that creates an instance of 6 bytes representing the MAC address @@ -63,7 +62,8 @@ namespace pcpp * @param[in] fifthOctet Represent the fifth octet in the address * @param[in] sixthOctet Represent the sixth octet in the address */ - inline MacAddress(uint8_t firstOctet, uint8_t secondOctet, uint8_t thirdOctet, uint8_t fourthOctet, uint8_t fifthOctet, uint8_t sixthOctet) + inline MacAddress(uint8_t firstOctet, uint8_t secondOctet, uint8_t thirdOctet, uint8_t fourthOctet, + uint8_t fifthOctet, uint8_t sixthOctet) { m_Address[0] = firstOctet; m_Address[1] = secondOctet; @@ -81,7 +81,7 @@ namespace pcpp */ MacAddress(std::initializer_list octets) { - if(octets.size() != sizeof(m_Address)) + if (octets.size() != sizeof(m_Address)) { throw std::invalid_argument("Invalid initializer list size, should be 6"); } @@ -93,23 +93,27 @@ namespace pcpp * @param[in] other The object to compare with * @return True if addresses are equal, false otherwise */ - bool operator==(const MacAddress& other) const { return memcmp(m_Address, other.m_Address, sizeof(m_Address)) == 0; } + bool operator==(const MacAddress &other) const + { + return memcmp(m_Address, other.m_Address, sizeof(m_Address)) == 0; + } /** * Overload of the not-equal operator * @param[in] other The object to compare with * @return True if addresses are not equal, false otherwise */ - bool operator!=(const MacAddress& other) const { return !operator==(other); } + bool operator!=(const MacAddress &other) const { return !operator==(other); } /** * Overload of the assignment operator. * If the list is invalid, the constructor throws an exception. - * @param[in] octets An initializer list containing the values of type uint8_t representing the MAC address, the length of the list must be equal to 6 + * @param[in] octets An initializer list containing the values of type uint8_t representing the MAC address, the + * length of the list must be equal to 6 */ - MacAddress& operator=(std::initializer_list octets) + MacAddress &operator=(std::initializer_list octets) { - if(octets.size() != sizeof(m_Address)) + if (octets.size() != sizeof(m_Address)) { throw std::invalid_argument("Invalid initializer list size, should be 6"); } @@ -122,7 +126,7 @@ namespace pcpp * Returns the pointer to raw data * @return The pointer to raw data */ - const uint8_t* getRawData() const { return m_Address; } + const uint8_t *getRawData() const { return m_Address; } /** * Returns a std::string representation of the address @@ -131,10 +135,11 @@ namespace pcpp std::string toString() const; /** - * Allocates a byte array of length 6 and copies address value into it. Array deallocation is user responsibility + * Allocates a byte array of length 6 and copies address value into it. Array deallocation is user + * responsibility * @param[in] arr A pointer to where array will be allocated */ - void copyTo(uint8_t** arr) const + void copyTo(uint8_t **arr) const { *arr = new uint8_t[sizeof(m_Address)]; memcpy(*arr, m_Address, sizeof(m_Address)); @@ -145,19 +150,19 @@ namespace pcpp * This method assumes array allocated size is at least 6 (the size of a MAC address) * @param[in] arr A pointer to the array which address will be copied to */ - void copyTo(uint8_t* arr) const { memcpy(arr, m_Address, sizeof(m_Address)); } + void copyTo(uint8_t *arr) const { memcpy(arr, m_Address, sizeof(m_Address)); } /** * A static value representing a zero value of MAC address, meaning address of value "00:00:00:00:00:00" */ static MacAddress Zero; - private: + private: uint8_t m_Address[6] = {0}; }; } // namespace pcpp -inline std::ostream& operator<<(std::ostream& os, const pcpp::MacAddress& macAddress) +inline std::ostream &operator<<(std::ostream &os, const pcpp::MacAddress &macAddress) { os << macAddress.toString(); return os; diff --git a/Common++/header/OUILookup.h b/Common++/header/OUILookup.h index ddc84e0d71..7c5bc7af6a 100644 --- a/Common++/header/OUILookup.h +++ b/Common++/header/OUILookup.h @@ -15,10 +15,11 @@ namespace pcpp { /** * @class OUILookup - * Provides vendor name matching functionality from MAC addresses. It uses an internal database to define name of the vendor. - * The class itself should be initialized by using initOUIDatabaseFromJson() otherwise all requests will return "Unknown" as vendor. - * The class itself currently does not support on-fly modifying the database but anyone who wants to add/modify/remove entries, - * should modify 3rdParty/OUILookup/PCPP_OUIDatabase.json file and call to initOUIDatabaseFromJson() function to renew the internal data. + * Provides vendor name matching functionality from MAC addresses. It uses an internal database to define name of + * the vendor. The class itself should be initialized by using initOUIDatabaseFromJson() otherwise all requests will + * return "Unknown" as vendor. The class itself currently does not support on-fly modifying the database but anyone + * who wants to add/modify/remove entries, should modify 3rdParty/OUILookup/PCPP_OUIDatabase.json file and call to + * initOUIDatabaseFromJson() function to renew the internal data. */ class OUILookup { @@ -49,14 +50,13 @@ namespace pcpp /// Internal vendor list for MAC addresses OUIVendorMap vendorMap; - template - int64_t internalParser(T &jsonData); + template int64_t internalParser(T &jsonData); public: - /** * Initialise internal OUI database from a JSON file - * @param[in] path Path to OUI database. The database itself is located at 3rdParty/OUILookup/PCPP_OUIDatabase.json + * @param[in] path Path to OUI database. The database itself is located at + * 3rdParty/OUILookup/PCPP_OUIDatabase.json * @return Returns the number of total vendors, negative on errors */ int64_t initOUIDatabaseFromJson(const std::string &path = ""); diff --git a/Common++/header/PcapPlusPlusVersion.h b/Common++/header/PcapPlusPlusVersion.h index ceb813ba39..58848dd3d5 100644 --- a/Common++/header/PcapPlusPlusVersion.h +++ b/Common++/header/PcapPlusPlusVersion.h @@ -10,20 +10,21 @@ */ namespace pcpp { - #define PCAPPLUSPLUS_VERSION "23.09+" - #define PCAPPLUSPLUS_VERSION_OFFICIAL "non-official release" +#define PCAPPLUSPLUS_VERSION "23.09+" +#define PCAPPLUSPLUS_VERSION_OFFICIAL "non-official release" - #define PCAPPLUSPLUS_VERSION_FULL "v" PCAPPLUSPLUS_VERSION " (" PCAPPLUSPLUS_VERSION_OFFICIAL ")" +#define PCAPPLUSPLUS_VERSION_FULL "v" PCAPPLUSPLUS_VERSION " (" PCAPPLUSPLUS_VERSION_OFFICIAL ")" /** - * @return PcapPlusPlus current version, e.g: 23.09. Notice that for non-official releases (which were pulled from GitHub) the version will end with a '+'. - * For example: '23.09+' means non-official release but '23.09' means official release + * @return PcapPlusPlus current version, e.g: 23.09. Notice that for non-official releases (which were pulled from + * GitHub) the version will end with a '+'. For example: '23.09+' means non-official release but '23.09' means + * official release */ inline std::string getPcapPlusPlusVersion() { return PCAPPLUSPLUS_VERSION; } /** - * @return PcapPlusPlus long version string which includes the version and info whether it's an official or non-official release. For example: "v23.09+ (non-official release)" - * or "v23.09 (official release)" + * @return PcapPlusPlus long version string which includes the version and info whether it's an official or + * non-official release. For example: "v23.09+ (non-official release)" or "v23.09 (official release)" */ inline std::string getPcapPlusPlusVersionFull() { return PCAPPLUSPLUS_VERSION_FULL; } @@ -48,4 +49,4 @@ namespace pcpp */ std::string getGitInfo(); -} +} // namespace pcpp diff --git a/Common++/header/PointerVector.h b/Common++/header/PointerVector.h index d73d60238f..7e3159d404 100644 --- a/Common++/header/PointerVector.h +++ b/Common++/header/PointerVector.h @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include /// @file @@ -15,28 +15,28 @@ namespace pcpp /** * @class PointerVector - * A template class for representing a std::vector of pointers. Once (a pointer to) an element is added to this vector, - * the element responsibility moves to the vector, meaning the PointerVector will free the object once it's removed from the vector - * This class wraps std::vector and adds the capability of freeing objects once they're removed from it + * A template class for representing a std::vector of pointers. Once (a pointer to) an element is added to this + * vector, the element responsibility moves to the vector, meaning the PointerVector will free the object once it's + * removed from the vector This class wraps std::vector and adds the capability of freeing objects once they're + * removed from it */ - template - class PointerVector + template class PointerVector { - public: + public: /** * Iterator object that is used for iterating all elements in the vector */ - typedef typename std::vector::iterator VectorIterator; + typedef typename std::vector::iterator VectorIterator; /** * Const iterator object that is used for iterating all elements in a constant vector */ - typedef typename std::vector::const_iterator ConstVectorIterator; + typedef typename std::vector::const_iterator ConstVectorIterator; /** * A constructor that create an empty instance of this object */ - PointerVector() { } + PointerVector() {} /** * A destructor for this class. The destructor frees all elements that are binded to the vector @@ -51,27 +51,28 @@ namespace pcpp /** * Copy constructor. Once a vector is copied from another vector, all elements inside it are copied, - * meaning the new vector will contain pointers to copied elements, not pointers to the elements of the original vector + * meaning the new vector will contain pointers to copied elements, not pointers to the elements of the original + * vector */ - PointerVector(const PointerVector& other) + PointerVector(const PointerVector &other) { try { for (const auto iter : other) { - T* objCopy = new T(*iter); + T *objCopy = new T(*iter); try { m_Vector.push_back(objCopy); } - catch (const std::exception&) + catch (const std::exception &) { delete objCopy; throw; } } } - catch (const std::exception&) + catch (const std::exception &) { for (auto obj : m_Vector) { @@ -97,7 +98,7 @@ namespace pcpp /** * Add a new (pointer to an) element to the vector */ - void pushBack(T* element) { m_Vector.push_back(element); } + void pushBack(T *element) { m_Vector.push_back(element); } /** * Get the first element of the vector @@ -123,8 +124,7 @@ namespace pcpp */ ConstVectorIterator end() const { return m_Vector.end(); } - - //inline size_t size() { return m_Vector.size(); } + // inline size_t size() { return m_Vector.size(); } /** * Get number of elements in the vector @@ -136,17 +136,18 @@ namespace pcpp * Returns a pointer of the first element in the vector * @return A pointer of the first element in the vector */ - T* front() { return m_Vector.front(); } + T *front() { return m_Vector.front(); } /** * @return A pointer to the last element in the vector */ - T* back() { return m_Vector.back(); } + T *back() { return m_Vector.back(); } /** * Removes from the vector a single element (position). Once the element is erased, it's also freed * @param[in] position The position of the element to erase - * @return An iterator pointing to the new location of the element that followed the last element erased by the function call + * @return An iterator pointing to the new location of the element that followed the last element erased by the + * function call */ VectorIterator erase(VectorIterator position) { @@ -157,11 +158,12 @@ namespace pcpp /** * Remove an element from the vector without freeing it * param[in] position The position of the element to remove from the vector - * @return A pointer to the element which is no longer managed by the vector. It's user responsibility to free it + * @return A pointer to the element which is no longer managed by the vector. It's user responsibility to free + * it */ - T* getAndRemoveFromVector(VectorIterator& position) + T *getAndRemoveFromVector(VectorIterator &position) { - T* result = (*position); + T *result = (*position); VectorIterator tempPos = position; tempPos = m_Vector.erase(tempPos); position = tempPos; @@ -173,23 +175,17 @@ namespace pcpp * @param[in] index The index to retrieve the element from * @return The element at the specified position in the vector */ - T* at(int index) - { - return m_Vector.at(index); - } + T *at(int index) { return m_Vector.at(index); } /** * Return a const pointer to the element in a certain index * @param[in] index The index to retrieve the element from * @return The element at the specified position in the vector */ - const T* at(int index) const - { - return m_Vector.at(index); - } + const T *at(int index) const { return m_Vector.at(index); } - private: - std::vector m_Vector; + private: + std::vector m_Vector; }; } // namespace pcpp diff --git a/Common++/header/SystemUtils.h b/Common++/header/SystemUtils.h index ad03d1dec8..8435fbf90c 100644 --- a/Common++/header/SystemUtils.h +++ b/Common++/header/SystemUtils.h @@ -9,7 +9,7 @@ #define MAX_NUM_OF_CORES 32 #ifdef _MSC_VER -int gettimeofday(struct timeval * tp, struct timezone * tzp); +int gettimeofday(struct timeval *tp, struct timezone *tzp); #endif /** @@ -26,8 +26,8 @@ namespace pcpp struct SystemCore { /** - * Core position in a 32-bit mask. For each core this attribute holds a 4B integer where only 1 bit is set, according to the core ID. - * For example: + * Core position in a 32-bit mask. For each core this attribute holds a 4B integer where only 1 bit is set, + * according to the core ID. For example: * - In core #0 the right-most bit will be set (meaning the number 0x01); * - in core #5 the 5th right-most bit will be set (meaning the number 0x20) */ @@ -39,10 +39,10 @@ namespace pcpp uint8_t Id; /** - * Overload of the comparison operator - * @return true if 2 addresses are equal. False otherwise - */ - bool operator==(const SystemCore& other) const { return Id == other.Id; } + * Overload of the comparison operator + * @return true if 2 addresses are equal. False otherwise + */ + bool operator==(const SystemCore &other) const { return Id == other.Id; } }; /** @@ -200,7 +200,6 @@ namespace pcpp */ CoreMask getCoreMaskForAllMachineCores(); - /** * Create a core mask from a vector of system cores * @param[in] cores A vector of SystemCore instances @@ -208,7 +207,6 @@ namespace pcpp */ CoreMask createCoreMaskFromCoreVector(const std::vector &cores); - /** * Create a core mask from a vector of core IDs * @param[in] coreIds A vector of core IDs @@ -216,13 +214,12 @@ namespace pcpp */ CoreMask createCoreMaskFromCoreIds(const std::vector &coreIds); - /** * Convert a core mask into a vector of its appropriate system cores * @param[in] coreMask The input core mask * @param[out] resultVec The vector that will contain the system cores */ - void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector& resultVec); + void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector &resultVec); /** * Execute a shell command and return its output @@ -230,7 +227,7 @@ namespace pcpp * @return The output of the command (both stdout and stderr) * @throws std::runtime_error Error executing the command. */ - std::string executeShellCommand(const std::string& command); + std::string executeShellCommand(const std::string &command); /** * Check if a directory exists @@ -240,24 +237,24 @@ namespace pcpp bool directoryExists(const std::string &dirPath); /** - * Retrieve a system-wide real-time accurate clock. It's actually a multi-platform version of clock_gettime() which is - * fully supported only on Linux + * Retrieve a system-wide real-time accurate clock. It's actually a multi-platform version of clock_gettime() which + * is fully supported only on Linux * @param[out] sec The second portion of the time * @param[out] nsec The nanosecond portion of the time * @return 0 for success, or -1 for failure */ - int clockGetTime(long& sec, long& nsec); + int clockGetTime(long &sec, long &nsec); /** - * A multi-platform version of the popular sleep method. This method simply runs the right sleep method, according to the platform - * it is running on. + * A multi-platform version of the popular sleep method. This method simply runs the right sleep method, according + * to the platform it is running on. * @param[in] seconds Number of seconds to sleep */ void multiPlatformSleep(uint32_t seconds); /** - * A multi-platform version of sleep in milliseconds resolution. This method simply runs the right sleep method, according to the platform - * it is running on. + * A multi-platform version of sleep in milliseconds resolution. This method simply runs the right sleep method, + * according to the platform it is running on. * @param[in] milliseconds Number of milliseconds to sleep */ void multiPlatformMSleep(uint32_t milliseconds); @@ -292,22 +289,23 @@ namespace pcpp /** * @class AppName - * This class extracts the application name from the current running executable and stores it for usage of the application throughout its runtime. - * This class should be initialized once in the beginning of the main() method using AppName#init() and from then on the app name could be retrieved using AppName#get() + * This class extracts the application name from the current running executable and stores it for usage of the + * application throughout its runtime. This class should be initialized once in the beginning of the main() method + * using AppName#init() and from then on the app name could be retrieved using AppName#get() */ class AppName { - private: + private: static std::string m_AppName; - public: + public: /** * Static init method which should be called once at the beginning of the main method. * @param[in] argc The argc param from main() * @param[in] argv The argv param from main() */ // cppcheck-suppress constParameter - static void init(int argc, char* argv[]) + static void init(int argc, char *argv[]) { if (argc == 0) { @@ -333,7 +331,8 @@ namespace pcpp // remove file extension lastPos = m_AppName.rfind('.'); - if (lastPos != std::string::npos) { + if (lastPos != std::string::npos) + { m_AppName.resize(lastPos); } } @@ -341,29 +340,29 @@ namespace pcpp /** * @return The app name as extracted from the current running executable */ - static const std::string& get() { return m_AppName; } + static const std::string &get() { return m_AppName; } }; /** * @class ApplicationEventHandler - * A singleton class that provides callbacks for events that occur during application life-cycle such as ctrl+c pressed, - * application closed, killed, etc. + * A singleton class that provides callbacks for events that occur during application life-cycle such as ctrl+c + * pressed, application closed, killed, etc. */ class ApplicationEventHandler { - public: + public: /** * @typedef EventHandlerCallback * The callback to be invoked when the event occurs * @param[in] cookie A pointer the the cookie provided by the user in ApplicationEventHandler c'tor */ - typedef void (*EventHandlerCallback)(void* cookie); + typedef void (*EventHandlerCallback)(void *cookie); /** * As ApplicationEventHandler is a singleton, this is the static getter to retrieve its instance * @return The singleton instance of ApplicationEventHandler */ - static ApplicationEventHandler& getInstance() + static ApplicationEventHandler &getInstance() { static ApplicationEventHandler instance; return instance; @@ -372,14 +371,15 @@ namespace pcpp /** * Register for an application-interrupted event, meaning ctrl+c was pressed * @param[in] handler The callback to be activated when the event occurs - * @param[in] cookie A pointer to a user provided object. This object will be transferred to the EventHandlerCallback callback. - * This cookie is very useful for transferring objects that give context to the event callback + * @param[in] cookie A pointer to a user provided object. This object will be transferred to the + * EventHandlerCallback callback. This cookie is very useful for transferring objects that give context to the + * event callback */ - void onApplicationInterrupted(EventHandlerCallback handler, void* cookie); + void onApplicationInterrupted(EventHandlerCallback handler, void *cookie); - private: + private: EventHandlerCallback m_ApplicationInterruptedHandler; - void* m_ApplicationInterruptedCookie; + void *m_ApplicationInterruptedCookie; // private c'tor ApplicationEventHandler(); diff --git a/Common++/header/TablePrinter.h b/Common++/header/TablePrinter.h index d4011ce54d..ab4dcf8f37 100644 --- a/Common++/header/TablePrinter.h +++ b/Common++/header/TablePrinter.h @@ -15,7 +15,7 @@ namespace pcpp */ class TablePrinter { - public: + public: /** * C'tor - get column names and column widths * @param[in] columnNames A vector of strings containing column names @@ -37,7 +37,7 @@ namespace pcpp * @return True if row was printed successfully or false otherwise (in any case of error an appropriate message * will be printed to log) */ - bool printRow(const std::string& values, char delimiter); + bool printRow(const std::string &values, char delimiter); /** * Print a single row @@ -53,12 +53,12 @@ namespace pcpp void printSeparator(); /** - * Close the table - should be called after all rows were printed. Calling this method is not a must as it's called - * in the class d'tor + * Close the table - should be called after all rows were printed. Calling this method is not a must as it's + * called in the class d'tor */ void closeTable(); - private: + private: std::vector m_ColumnNames; std::vector m_ColumnWidths; bool m_FirstRow; @@ -70,4 +70,4 @@ namespace pcpp void printHeadline(); }; -} +} // namespace pcpp diff --git a/Common++/header/TimespecTimeval.h b/Common++/header/TimespecTimeval.h index 7a496c150e..d469f112f7 100644 --- a/Common++/header/TimespecTimeval.h +++ b/Common++/header/TimespecTimeval.h @@ -3,15 +3,17 @@ #pragma once #ifndef TIMEVAL_TO_TIMESPEC -#define TIMEVAL_TO_TIMESPEC(tv, ts) { \ - (ts)->tv_sec = (tv)->tv_sec; \ - (ts)->tv_nsec = (tv)->tv_usec * 1000; \ -} +#define TIMEVAL_TO_TIMESPEC(tv, ts) \ + { \ + (ts)->tv_sec = (tv)->tv_sec; \ + (ts)->tv_nsec = (tv)->tv_usec * 1000; \ + } #endif #ifndef TIMESPEC_TO_TIMEVAL -#define TIMESPEC_TO_TIMEVAL(tv, ts) { \ - (tv)->tv_sec = (ts)->tv_sec; \ - (tv)->tv_usec = (ts)->tv_nsec / 1000; \ -} +#define TIMESPEC_TO_TIMEVAL(tv, ts) \ + { \ + (tv)->tv_sec = (ts)->tv_sec; \ + (tv)->tv_usec = (ts)->tv_nsec / 1000; \ + } #endif diff --git a/Common++/src/GeneralUtils.cpp b/Common++/src/GeneralUtils.cpp index 7d8113184d..13de3c5da4 100644 --- a/Common++/src/GeneralUtils.cpp +++ b/Common++/src/GeneralUtils.cpp @@ -10,88 +10,87 @@ namespace pcpp { -std::string byteArrayToHexString(const uint8_t* byteArr, size_t byteArrSize, int stringSizeLimit) -{ - if (stringSizeLimit <= 0) - stringSizeLimit = byteArrSize; - - std::stringstream dataStream; - dataStream << std::hex; - for (size_t i = 0; i < byteArrSize; ++i) + std::string byteArrayToHexString(const uint8_t *byteArr, size_t byteArrSize, int stringSizeLimit) { - if (i >= (size_t)stringSizeLimit) - break; + if (stringSizeLimit <= 0) + stringSizeLimit = byteArrSize; - dataStream << std::setw(2) << std::setfill('0') << (int)byteArr[i]; - } + std::stringstream dataStream; + dataStream << std::hex; + for (size_t i = 0; i < byteArrSize; ++i) + { + if (i >= (size_t)stringSizeLimit) + break; - return dataStream.str(); -} + dataStream << std::setw(2) << std::setfill('0') << (int)byteArr[i]; + } -static int char2int(char input) -{ - if(input >= '0' && input <= '9') - return input - '0'; - if(input >= 'A' && input <= 'F') - return input - 'A' + 10; - if(input >= 'a' && input <= 'f') - return input - 'a' + 10; - return -1; -} - -size_t hexStringToByteArray(const std::string& hexString, uint8_t* resultByteArr, size_t resultByteArrSize) -{ - if (hexString.size() % 2 != 0) - { - PCPP_LOG_ERROR("Input string is in odd size"); - return 0; + return dataStream.str(); } - memset(resultByteArr, 0, resultByteArrSize); - for (size_t i = 0; i < hexString.length(); i += 2) + static int char2int(char input) { - if (i >= resultByteArrSize * 2) - return resultByteArrSize; + if (input >= '0' && input <= '9') + return input - '0'; + if (input >= 'A' && input <= 'F') + return input - 'A' + 10; + if (input >= 'a' && input <= 'f') + return input - 'a' + 10; + return -1; + } - int firstChar = char2int(hexString[i]); - int secondChar = char2int(hexString[i + 1]); - if (firstChar < 0 || secondChar < 0) + size_t hexStringToByteArray(const std::string &hexString, uint8_t *resultByteArr, size_t resultByteArrSize) + { + if (hexString.size() % 2 != 0) { - PCPP_LOG_ERROR("Input string has an illegal character"); - resultByteArr[0] = '\0'; + PCPP_LOG_ERROR("Input string is in odd size"); return 0; } - resultByteArr[i / 2] = (firstChar << 4) | secondChar; - } + memset(resultByteArr, 0, resultByteArrSize); + for (size_t i = 0; i < hexString.length(); i += 2) + { + if (i >= resultByteArrSize * 2) + return resultByteArrSize; - return hexString.length() / 2; -} + int firstChar = char2int(hexString[i]); + int secondChar = char2int(hexString[i + 1]); + if (firstChar < 0 || secondChar < 0) + { + PCPP_LOG_ERROR("Input string has an illegal character"); + resultByteArr[0] = '\0'; + return 0; + } + resultByteArr[i / 2] = (firstChar << 4) | secondChar; + } -char* cross_platform_memmem(const char* haystack, size_t haystackLen, const char* needle, size_t needleLen) -{ - char* ptr = (char*)haystack; - while (needleLen <= (haystackLen - (ptr - haystack))) + return hexString.length() / 2; + } + + char *cross_platform_memmem(const char *haystack, size_t haystackLen, const char *needle, size_t needleLen) { - if (nullptr != (ptr = (char*)memchr(ptr, (int)(*needle), haystackLen - (ptr - haystack)))) + char *ptr = (char *)haystack; + while (needleLen <= (haystackLen - (ptr - haystack))) { - // check if there is room to do a memcmp - if(needleLen > (haystackLen - (ptr - haystack))) + if (nullptr != (ptr = (char *)memchr(ptr, (int)(*needle), haystackLen - (ptr - haystack)))) { - return nullptr; + // check if there is room to do a memcmp + if (needleLen > (haystackLen - (ptr - haystack))) + { + return nullptr; + } + + if (0 == memcmp(ptr, needle, needleLen)) + return ptr; + else + ++ptr; } - - if (0 == memcmp(ptr, needle, needleLen)) - return ptr; else - ++ptr; + break; } - else - break; - } - return nullptr; -} + return nullptr; + } -} +} // namespace pcpp diff --git a/Common++/src/IpAddress.cpp b/Common++/src/IpAddress.cpp index ac4ffb8afa..039d9e0fd9 100644 --- a/Common++/src/IpAddress.cpp +++ b/Common++/src/IpAddress.cpp @@ -17,7 +17,6 @@ #include #endif - namespace pcpp { @@ -32,7 +31,6 @@ namespace pcpp // IPv4Address // ~~~~~~~~~~~ - std::string IPv4Address::toString() const { char addrBuffer[INET_ADDRSTRLEN]; @@ -43,13 +41,13 @@ namespace pcpp return std::string(); } - bool IPv4Address::isMulticast() const { - return !operator<(MulticastRangeLowerBound) && (operator<(MulticastRangeUpperBound) || operator==(MulticastRangeUpperBound)); + return !operator<(MulticastRangeLowerBound) && + (operator<(MulticastRangeUpperBound) || operator==(MulticastRangeUpperBound)); } - IPv4Address::IPv4Address(const std::string& addrAsString) + IPv4Address::IPv4Address(const std::string &addrAsString) { if (inet_pton(AF_INET, addrAsString.data(), m_Bytes.data()) <= 0) { @@ -57,39 +55,32 @@ namespace pcpp } } + bool IPv4Address::matchNetwork(const IPv4Network &network) const { return network.includes(*this); } - bool IPv4Address::matchNetwork(const IPv4Network& network) const - { - return network.includes(*this); - } - - - bool IPv4Address::matchNetwork(const std::string& network) const + bool IPv4Address::matchNetwork(const std::string &network) const { try { auto ipv4Network = IPv4Network(network); return ipv4Network.includes(*this); } - catch (const std::invalid_argument& e) + catch (const std::invalid_argument &e) { PCPP_LOG_ERROR(e.what()); return false; } } - bool IPv4Address::isValidIPv4Address(const std::string& addrAsString) + bool IPv4Address::isValidIPv4Address(const std::string &addrAsString) { struct sockaddr_in sa_in; return inet_pton(AF_INET, addrAsString.data(), &(sa_in.sin_addr)) > 0; } - // ~~~~~~~~~~~ // IPv6Address // ~~~~~~~~~~~ - std::string IPv6Address::toString() const { char addrBuffer[INET6_ADDRSTRLEN]; @@ -100,23 +91,17 @@ namespace pcpp return std::string(); } + bool IPv6Address::isMulticast() const { return !operator<(MulticastRangeLowerBound); } - bool IPv6Address::isMulticast() const - { - return !operator<(MulticastRangeLowerBound); - } - - - IPv6Address::IPv6Address(const std::string& addrAsString) + IPv6Address::IPv6Address(const std::string &addrAsString) { - if(inet_pton(AF_INET6, addrAsString.data(), m_Bytes.data()) <= 0) + if (inet_pton(AF_INET6, addrAsString.data(), m_Bytes.data()) <= 0) { throw std::invalid_argument("Not a valid IPv6 address: " + addrAsString); } } - - void IPv6Address::copyTo(uint8_t** arr, size_t& length) const + void IPv6Address::copyTo(uint8_t **arr, size_t &length) const { const size_t addrLen = m_Bytes.size() * sizeof(uint8_t); length = addrLen; @@ -124,40 +109,33 @@ namespace pcpp memcpy(*arr, m_Bytes.data(), addrLen); } + bool IPv6Address::matchNetwork(const IPv6Network &network) const { return network.includes(*this); } - bool IPv6Address::matchNetwork(const IPv6Network &network) const - { - return network.includes(*this); - } - - - bool IPv6Address::matchNetwork(const std::string& network) const + bool IPv6Address::matchNetwork(const std::string &network) const { try { auto ipv6Network = IPv6Network(network); return ipv6Network.includes(*this); } - catch (const std::invalid_argument& e) + catch (const std::invalid_argument &e) { PCPP_LOG_ERROR(e.what()); return false; } } - bool IPv6Address::isValidIPv6Address(const std::string& addrAsString) + bool IPv6Address::isValidIPv6Address(const std::string &addrAsString) { struct sockaddr_in6 sa_in6; return inet_pton(AF_INET6, addrAsString.data(), &(sa_in6.sin6_addr)) > 0; } - // ~~~~~~~~~ // IPAddress // ~~~~~~~~~ - - IPAddress::IPAddress(const std::string& addrAsString) + IPAddress::IPAddress(const std::string &addrAsString) { if (IPv4Address::isValidIPv4Address(addrAsString)) { @@ -175,13 +153,11 @@ namespace pcpp } } - // ~~~~~~~~~~~ // IPv4Network // ~~~~~~~~~~~ - - bool IPv4Network::isValidNetmask(const IPv4Address& maskAddress) + bool IPv4Network::isValidNetmask(const IPv4Address &maskAddress) { if (maskAddress == IPv4Address::Zero) { @@ -202,22 +178,19 @@ namespace pcpp } } - - void IPv4Network::initFromAddressAndPrefixLength(const IPv4Address& address, uint8_t prefixLen) + void IPv4Network::initFromAddressAndPrefixLength(const IPv4Address &address, uint8_t prefixLen) { - m_Mask = be32toh(0xffffffff ^ (prefixLen < 32 ? 0xffffffff >> prefixLen: 0)); + m_Mask = be32toh(0xffffffff ^ (prefixLen < 32 ? 0xffffffff >> prefixLen : 0)); m_NetworkPrefix = address.toInt() & m_Mask; } - - void IPv4Network::initFromAddressAndNetmask(const IPv4Address& address, const IPv4Address& netmaskAddress) + void IPv4Network::initFromAddressAndNetmask(const IPv4Address &address, const IPv4Address &netmaskAddress) { m_Mask = netmaskAddress.toInt(); m_NetworkPrefix = address.toInt() & m_Mask; } - - IPv4Network::IPv4Network(const IPv4Address& address, uint8_t prefixLen) + IPv4Network::IPv4Network(const IPv4Address &address, uint8_t prefixLen) { if (prefixLen > 32) { @@ -227,15 +200,14 @@ namespace pcpp initFromAddressAndPrefixLength(address, prefixLen); } - - IPv4Network::IPv4Network(const IPv4Address& address, const std::string& netmask) + IPv4Network::IPv4Network(const IPv4Address &address, const std::string &netmask) { IPv4Address netmaskAddr; try { netmaskAddr = IPv4Address(netmask); } - catch(const std::exception&) + catch (const std::exception &) { throw std::invalid_argument("Netmask is not valid IPv4 format: " + netmask); } @@ -246,8 +218,7 @@ namespace pcpp initFromAddressAndNetmask(address, netmaskAddr); } - - IPv4Network::IPv4Network(const std::string& addressAndNetmask) + IPv4Network::IPv4Network(const std::string &addressAndNetmask) { std::stringstream stream(addressAndNetmask); std::string networkPrefixStr, netmaskStr; @@ -256,7 +227,8 @@ namespace pcpp if (netmaskStr.empty()) { - throw std::invalid_argument("The input should be in the format of
/ or
/"); + throw std::invalid_argument( + "The input should be in the format of
/ or
/"); } IPv4Address networkPrefix; @@ -264,7 +236,7 @@ namespace pcpp { networkPrefix = IPv4Address(networkPrefixStr); } - catch (const std::invalid_argument&) + catch (const std::invalid_argument &) { throw std::invalid_argument("The input doesn't contain a valid IPv4 network prefix: " + networkPrefixStr); } @@ -286,7 +258,7 @@ namespace pcpp { netmaskAddr = IPv4Address(netmaskStr); } - catch (const std::invalid_argument&) + catch (const std::invalid_argument &) { throw std::invalid_argument("Netmask is not valid IPv4 format: " + netmaskStr); } @@ -298,50 +270,43 @@ namespace pcpp } } - uint8_t IPv4Network::getPrefixLen() const { std::bitset<32> bitset(m_Mask); return bitset.count(); } - IPv4Address IPv4Network::getLowestAddress() const { std::bitset<32> bitset(m_Mask); return bitset.count() < 32 ? m_NetworkPrefix + htobe32(1) : m_NetworkPrefix; } - IPv4Address IPv4Network::getHighestAddress() const { - auto tempAddress = static_cast(m_NetworkPrefix | ~m_Mask); + auto tempAddress = static_cast(m_NetworkPrefix | ~m_Mask); std::bitset<32> bitset(m_Mask); return bitset.count() < 32 ? tempAddress - htobe32(1) : tempAddress; } - uint64_t IPv4Network::getTotalAddressCount() const { std::bitset<32> bitset(static_cast(~m_Mask)); return 1ULL << bitset.count(); } - - bool IPv4Network::includes(const IPv4Address& address) const + bool IPv4Network::includes(const IPv4Address &address) const { return (address.toInt() & m_Mask) == m_NetworkPrefix; } - - bool IPv4Network::includes(const IPv4Network& network) const + bool IPv4Network::includes(const IPv4Network &network) const { uint32_t lowestAddress = network.m_NetworkPrefix; uint32_t highestAddress = network.m_NetworkPrefix | ~network.m_Mask; return ((lowestAddress & m_Mask) == m_NetworkPrefix && (highestAddress & m_Mask) == m_NetworkPrefix); } - std::string IPv4Network::toString() const { std::ostringstream stream; @@ -349,18 +314,15 @@ namespace pcpp return stream.str(); } - // ~~~~~~~~~~~ // IPv6Network // ~~~~~~~~~~~ - #define IPV6_ADDR_SIZE 16 - - bool IPv6Network::isValidNetmask(const IPv6Address& netmask) + bool IPv6Network::isValidNetmask(const IPv6Address &netmask) { - if(netmask == IPv6Address::Zero) + if (netmask == IPv6Address::Zero) { return true; } @@ -382,7 +344,8 @@ namespace pcpp return false; } expectingValue = 0; - } else if (expectingValue == 0 && curByte != 0) + } + else if (expectingValue == 0 && curByte != 0) { return false; } @@ -391,7 +354,6 @@ namespace pcpp return true; } - void IPv6Network::initFromAddressAndPrefixLength(const IPv6Address &address, uint8_t prefixLen) { memset(m_Mask, 0, IPV6_ADDR_SIZE); @@ -422,8 +384,7 @@ namespace pcpp } } - - void IPv6Network::initFromAddressAndNetmask(const IPv6Address &address, const IPv6Address& netmaskAddr) + void IPv6Network::initFromAddressAndNetmask(const IPv6Address &address, const IPv6Address &netmaskAddr) { netmaskAddr.copyTo(m_Mask); @@ -435,7 +396,6 @@ namespace pcpp } } - IPv6Network::IPv6Network(const IPv6Address &address, uint8_t prefixLen) { if (prefixLen > 128) @@ -446,7 +406,6 @@ namespace pcpp initFromAddressAndPrefixLength(address, prefixLen); } - IPv6Network::IPv6Network(const IPv6Address &address, const std::string &netmask) { IPv6Address netmaskAddr; @@ -454,7 +413,7 @@ namespace pcpp { netmaskAddr = IPv6Address(netmask); } - catch(const std::exception&) + catch (const std::exception &) { throw std::invalid_argument("Netmask is not valid IPv6 format: " + netmask); } @@ -465,7 +424,6 @@ namespace pcpp initFromAddressAndNetmask(address, netmaskAddr); } - IPv6Network::IPv6Network(const std::string &addressAndNetmask) { std::stringstream stream(addressAndNetmask); @@ -475,14 +433,16 @@ namespace pcpp if (netmaskStr.empty()) { - throw std::invalid_argument("The input should be in the format of
/ or
/"); + throw std::invalid_argument( + "The input should be in the format of
/ or
/"); } IPv6Address networkPrefix; try { networkPrefix = IPv6Address(networkPrefixStr); - } catch (const std::invalid_argument&) + } + catch (const std::invalid_argument &) { throw std::invalid_argument("The input doesn't contain a valid IPv6 network prefix: " + networkPrefixStr); } @@ -503,7 +463,7 @@ namespace pcpp { netmaskAddr = IPv6Address(netmaskStr); } - catch(const std::exception&) + catch (const std::exception &) { throw std::invalid_argument("Netmask is not valid IPv6 format: " + netmaskStr); } @@ -515,7 +475,6 @@ namespace pcpp } } - uint8_t IPv6Network::getPrefixLen() const { uint8_t result = 0; @@ -527,7 +486,6 @@ namespace pcpp return result; } - IPv6Address IPv6Network::getLowestAddress() const { if (getPrefixLen() == 128) @@ -541,7 +499,6 @@ namespace pcpp return lowestAddress; } - IPv6Address IPv6Network::getHighestAddress() const { uint8_t result[IPV6_ADDR_SIZE]; @@ -554,7 +511,6 @@ namespace pcpp return result; } - uint64_t IPv6Network::getTotalAddressCount() const { int numOfBitset = 0; @@ -571,8 +527,7 @@ namespace pcpp return 1ULL << numOfBitset; } - - bool IPv6Network::includes(const IPv6Address& address) const + bool IPv6Network::includes(const IPv6Address &address) const { uint8_t maskedBytes[IPV6_ADDR_SIZE]; address.copyTo(maskedBytes); @@ -584,13 +539,11 @@ namespace pcpp return memcmp(m_NetworkPrefix, maskedBytes, IPV6_ADDR_SIZE) == 0; } - - bool IPv6Network::includes(const IPv6Network& network) const + bool IPv6Network::includes(const IPv6Network &network) const { return includes(network.getLowestAddress()) && includes(network.getHighestAddress()); } - std::string IPv6Network::toString() const { std::ostringstream stream; diff --git a/Common++/src/IpAddressUtils.cpp b/Common++/src/IpAddressUtils.cpp index c72c944cb5..396d09f898 100644 --- a/Common++/src/IpAddressUtils.cpp +++ b/Common++/src/IpAddressUtils.cpp @@ -5,17 +5,14 @@ namespace pcpp { - bool operator==(const IPv4Address& lhs, const in_addr& rhs) - { - return lhs.toInt() == rhs.s_addr; - } + bool operator==(const IPv4Address &lhs, const in_addr &rhs) { return lhs.toInt() == rhs.s_addr; } - bool operator==(const IPv6Address& lhs, const in6_addr& rhs) + bool operator==(const IPv6Address &lhs, const in6_addr &rhs) { return memcmp(lhs.toBytes(), &rhs, sizeof(struct in6_addr)) == 0; } - bool operator==(const IPAddress& lhs, const in_addr& rhs) + bool operator==(const IPAddress &lhs, const in_addr &rhs) { if (lhs.isIPv4()) { @@ -24,7 +21,7 @@ namespace pcpp return false; } - bool operator==(const IPAddress& lhs, const in6_addr& rhs) + bool operator==(const IPAddress &lhs, const in6_addr &rhs) { if (lhs.isIPv6()) { @@ -32,4 +29,4 @@ namespace pcpp } return false; } -} +} // namespace pcpp diff --git a/Common++/src/IpUtils.cpp b/Common++/src/IpUtils.cpp index 04337eae30..349e02bf09 100644 --- a/Common++/src/IpUtils.cpp +++ b/Common++/src/IpUtils.cpp @@ -6,20 +6,20 @@ #include #include #ifndef NS_INADDRSZ -#define NS_INADDRSZ 4 +#define NS_INADDRSZ 4 #endif #ifndef NS_IN6ADDRSZ -#define NS_IN6ADDRSZ 16 +#define NS_IN6ADDRSZ 16 #endif #ifndef NS_INT16SZ -#define NS_INT16SZ 2 +#define NS_INT16SZ 2 #endif namespace pcpp { namespace internal { - in_addr* sockaddr2in_addr(sockaddr* sa) + in_addr *sockaddr2in_addr(sockaddr *sa) { if (sa == nullptr) throw std::invalid_argument("sockaddr is nullptr"); @@ -27,23 +27,23 @@ namespace pcpp if (sa->sa_family != AF_INET) throw std::invalid_argument("sockaddr family is not AF_INET."); - return &(reinterpret_cast(sa)->sin_addr); + return &(reinterpret_cast(sa)->sin_addr); } - in_addr* try_sockaddr2in_addr(sockaddr* sa) + in_addr *try_sockaddr2in_addr(sockaddr *sa) { try { return sockaddr2in_addr(sa); } - catch (const std::invalid_argument& e) + catch (const std::invalid_argument &e) { PCPP_LOG_DEBUG("Extraction failed: " << e.what() << " Returning nullptr."); return nullptr; } } - in6_addr* sockaddr2in6_addr(sockaddr* sa) + in6_addr *sockaddr2in6_addr(sockaddr *sa) { if (sa == nullptr) throw std::invalid_argument("sockaddr is nullptr"); @@ -51,23 +51,23 @@ namespace pcpp if (sa->sa_family != AF_INET6) throw std::invalid_argument("sockaddr family is not AF_INET6."); - return &(reinterpret_cast(sa)->sin6_addr); + return &(reinterpret_cast(sa)->sin6_addr); } - in6_addr* try_sockaddr2in6_addr(sockaddr* sa) + in6_addr *try_sockaddr2in6_addr(sockaddr *sa) { try { return sockaddr2in6_addr(sa); } - catch (const std::invalid_argument& e) + catch (const std::invalid_argument &e) { PCPP_LOG_DEBUG("Extraction failed: " << e.what() << " Returning nullptr."); return nullptr; } } - void sockaddr2string(sockaddr const* sa, char* resultString, size_t resultBufLen) + void sockaddr2string(sockaddr const *sa, char *resultString, size_t resultBufLen) { if (sa == nullptr) throw std::invalid_argument("sockaddr is nullptr"); @@ -80,7 +80,8 @@ namespace pcpp if (resultBufLen < INET_ADDRSTRLEN) throw std::invalid_argument("Insufficient buffer"); - if (inet_ntop(AF_INET, &(reinterpret_cast(sa)->sin_addr), resultString, resultBufLen) == nullptr) + if (inet_ntop(AF_INET, &(reinterpret_cast(sa)->sin_addr), resultString, + resultBufLen) == nullptr) { throw std::runtime_error("Unknown error during conversion"); } @@ -92,7 +93,8 @@ namespace pcpp if (resultBufLen < INET6_ADDRSTRLEN) throw std::invalid_argument("Insufficient buffer"); - if(inet_ntop(AF_INET6, &(reinterpret_cast(sa)->sin6_addr), resultString, resultBufLen) == nullptr) + if (inet_ntop(AF_INET6, &(reinterpret_cast(sa)->sin6_addr), resultString, + resultBufLen) == nullptr) { throw std::runtime_error("Unknown error during conversion"); } @@ -105,11 +107,11 @@ namespace pcpp uint32_t in_addr2int(in_addr inAddr) { - #ifdef _WIN32 +#ifdef _WIN32 return inAddr.S_un.S_addr; - #else +#else return inAddr.s_addr; - #endif +#endif } } // namespace internal } // namespace pcpp @@ -127,14 +129,13 @@ namespace pcpp * author: * Paul Vixie, 1996. */ -static const char * -inet_ntop4(const uint8_t* src, char* dst, size_t size) +static const char *inet_ntop4(const uint8_t *src, char *dst, size_t size) { static const char fmt[] = "%u.%u.%u.%u"; char tmp[sizeof "255.255.255.255"]; int nprinted; nprinted = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]); - /* Note: nprinted *excludes* the trailing '\0' character */ + /* Note: nprinted *excludes* the trailing '\0' character */ if ((size_t)nprinted >= size) { return (NULL); @@ -149,8 +150,7 @@ inet_ntop4(const uint8_t* src, char* dst, size_t size) * author: * Paul Vixie, 1996. */ -static const char * -inet_ntop6(const uint8_t* src, char* dst, size_t size) +static const char *inet_ntop6(const uint8_t *src, char *dst, size_t size) { /* * Note that int32_t and int16_t need only be "at least" large enough @@ -160,7 +160,10 @@ inet_ntop6(const uint8_t* src, char* dst, size_t size) * to use pointer overlays. All the world's not a VAX. */ char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp; - struct { int base, len; } best, cur; + struct + { + int base, len; + } best, cur; u_int words[NS_IN6ADDRSZ / NS_INT16SZ]; int i; @@ -222,16 +225,15 @@ inet_ntop6(const uint8_t* src, char* dst, size_t size) /* Is this address an encapsulated IPv4? */ if (i == 6 && best.base == 0 && (best.len == 6 || (best.len == 5 && words[5] == 0xffff))) { - if (!inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp))) + if (!inet_ntop4(src + 12, tp, sizeof tmp - (tp - tmp))) return (NULL); tp += strlen(tp); break; } - tp += snprintf(tp, (unsigned long) (sizeof tmp - (tp - tmp)), "%x", words[i]); + tp += snprintf(tp, (unsigned long)(sizeof tmp - (tp - tmp)), "%x", words[i]); } /* Was it a trailing run of 0x00's? */ - if (best.base != -1 && (best.base + best.len) == - (NS_IN6ADDRSZ / NS_INT16SZ)) + if (best.base != -1 && (best.base + best.len) == (NS_IN6ADDRSZ / NS_INT16SZ)) *tp++ = ':'; *tp++ = '\0'; @@ -246,7 +248,6 @@ inet_ntop6(const uint8_t* src, char* dst, size_t size) return (dst); } - /* int * inet_pton4(src, dst) * like inet_aton() but without all the hexadecimal and shorthand. @@ -257,8 +258,7 @@ inet_ntop6(const uint8_t* src, char* dst, size_t size) * author: * Paul Vixie, 1996. */ -static int -inet_pton4(const char* src, uint8_t* dst) +static int inet_pton4(const char *src, uint8_t *dst) { static const char digits[] = "0123456789"; int saw_digit, octets, ch; @@ -277,8 +277,8 @@ inet_pton4(const char* src, uint8_t* dst) if (newSize > 255) return (0); - *tp = (u_char) newSize; - if (! saw_digit) + *tp = (u_char)newSize; + if (!saw_digit) { if (++octets > 4) return (0); @@ -291,7 +291,8 @@ inet_pton4(const char* src, uint8_t* dst) return (0); *++tp = 0; saw_digit = 0; - } else + } + else return (0); } if (octets < 4) @@ -313,11 +314,9 @@ inet_pton4(const char* src, uint8_t* dst) * author: * Paul Vixie, 1996. */ -static int -inet_pton6(const char* src, uint8_t* dst) +static int inet_pton6(const char *src, uint8_t *dst) { - static const char xdigits_l[] = "0123456789abcdef", - xdigits_u[] = "0123456789ABCDEF"; + static const char xdigits_l[] = "0123456789abcdef", xdigits_u[] = "0123456789ABCDEF"; u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; const char *curtok; int ch, saw_xdigit; @@ -335,7 +334,7 @@ inet_pton6(const char* src, uint8_t* dst) val = 0; while ((ch = *src++) != '\0') { - const char* pch, *xdigits; + const char *pch, *xdigits; if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) pch = strchr((xdigits = xdigits_u), ch); @@ -364,8 +363,8 @@ inet_pton6(const char* src, uint8_t* dst) } if (tp + NS_INT16SZ > endp) return (0); - *tp++ = (u_char) (val >> 8) & 0xff; - *tp++ = (u_char) val & 0xff; + *tp++ = (u_char)(val >> 8) & 0xff; + *tp++ = (u_char)val & 0xff; saw_xdigit = 0; val = 0; continue; @@ -374,7 +373,7 @@ inet_pton6(const char* src, uint8_t* dst) { tp += NS_INADDRSZ; saw_xdigit = 0; - break; /* '\0' was seen by inet_pton4(). */ + break; /* '\0' was seen by inet_pton4(). */ } return (0); } @@ -382,8 +381,8 @@ inet_pton6(const char* src, uint8_t* dst) { if (tp + NS_INT16SZ > endp) return (0); - *tp++ = (u_char) (val >> 8) & 0xff; - *tp++ = (u_char) val & 0xff; + *tp++ = (u_char)(val >> 8) & 0xff; + *tp++ = (u_char)val & 0xff; } if (colonp != NULL) { @@ -391,14 +390,14 @@ inet_pton6(const char* src, uint8_t* dst) * Since some memmove()'s erroneously fail to handle * overlapping regions, we'll do the shift by hand. */ - const int n = (int) (tp - colonp); + const int n = (int)(tp - colonp); int i; if (tp == endp) return (0); for (i = 1; i <= n; i++) { - endp[- i] = colonp[n - i]; + endp[-i] = colonp[n - i]; colonp[n - i] = 0; } tp = endp; @@ -409,32 +408,31 @@ inet_pton6(const char* src, uint8_t* dst) return (1); } - -const char* inet_ntop(int af, const void* src, char* dst, size_t size) +const char *inet_ntop(int af, const void *src, char *dst, size_t size) { switch (af) { case AF_INET: - return (inet_ntop4((const uint8_t*)src, dst, size)); + return (inet_ntop4((const uint8_t *)src, dst, size)); case AF_INET6: - return (inet_ntop6((const uint8_t*)src, dst, size)); + return (inet_ntop6((const uint8_t *)src, dst, size)); default: return (NULL); } /* NOTREACHED */ } -int inet_pton(int af, const char* src, void* dst) +int inet_pton(int af, const char *src, void *dst) { switch (af) { #ifdef AF_INET case AF_INET: - return (inet_pton4(src, (uint8_t*)dst)); + return (inet_pton4(src, (uint8_t *)dst)); #endif #ifdef AF_INET6 case AF_INET6: - return (inet_pton6(src, (uint8_t*)dst)); + return (inet_pton6(src, (uint8_t *)dst)); #endif default: return (-1); diff --git a/Common++/src/Logger.cpp b/Common++/src/Logger.cpp index f78641caff..b584095c16 100644 --- a/Common++/src/Logger.cpp +++ b/Common++/src/Logger.cpp @@ -4,55 +4,50 @@ namespace pcpp { -Logger::Logger() : m_LogsEnabled(true), m_LogPrinter(&defaultLogPrinter) -{ - m_LastError.reserve(200); - for (int i = 0; istr(); - delete logStream; - if (logLevel == Logger::Error) + void Logger::defaultLogPrinter(LogLevel logLevel, const std::string &logMessage, const std::string &file, + const std::string &method, const int line) { - m_LastError = logMessage; + std::ostringstream sstream; + sstream << file << ": " << method << ":" << line; + std::cout << std::left << "[" << std::setw(5) << Logger::logLevelAsString(logLevel) << ": " << std::setw(45) + << sstream.str() << "] " << logMessage << std::endl; } - if (m_LogsEnabled) + + std::ostringstream *Logger::internalCreateLogStream() { return new std::ostringstream(); } + + void Logger::internalPrintLogMessage(std::ostringstream *logStream, Logger::LogLevel logLevel, const char *file, + const char *method, int line) { - m_LogPrinter(logLevel, logMessage, file, method, line); + std::string logMessage = logStream->str(); + delete logStream; + if (logLevel == Logger::Error) + { + m_LastError = logMessage; + } + if (m_LogsEnabled) + { + m_LogPrinter(logLevel, logMessage, file, method, line); + } } -} } // namespace pcpp diff --git a/Common++/src/MacAddress.cpp b/Common++/src/MacAddress.cpp index bc61c41861..cf5e653b4f 100644 --- a/Common++/src/MacAddress.cpp +++ b/Common++/src/MacAddress.cpp @@ -5,27 +5,30 @@ namespace pcpp { -MacAddress MacAddress::Zero(0,0,0,0,0,0); + MacAddress MacAddress::Zero(0, 0, 0, 0, 0, 0); -std::string MacAddress::toString() const -{ - char str[19]; - snprintf(str, sizeof str, "%02x:%02x:%02x:%02x:%02x:%02x", m_Address[0], m_Address[1], m_Address[2], m_Address[3], m_Address[4], m_Address[5]); - return std::string(str); -} - -MacAddress::MacAddress(const std::string& address) -{ - constexpr size_t validMacAddressLength = 17; - unsigned int values[6]; - if (address.size() != validMacAddressLength || sscanf(address.c_str(), "%x:%x:%x:%x:%x:%x", &values[0], &values[1], &values[2], &values[3], &values[4], &values[5]) != 6) + std::string MacAddress::toString() const { - throw std::invalid_argument("Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); + char str[19]; + snprintf(str, sizeof str, "%02x:%02x:%02x:%02x:%02x:%02x", m_Address[0], m_Address[1], m_Address[2], + m_Address[3], m_Address[4], m_Address[5]); + return std::string(str); } - for (int i = 0; i < 6; ++i) + + MacAddress::MacAddress(const std::string &address) { - m_Address[i] = values[i]; + constexpr size_t validMacAddressLength = 17; + unsigned int values[6]; + if (address.size() != validMacAddressLength || + sscanf(address.c_str(), "%x:%x:%x:%x:%x:%x", &values[0], &values[1], &values[2], &values[3], &values[4], + &values[5]) != 6) + { + throw std::invalid_argument("Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); + } + for (int i = 0; i < 6; ++i) + { + m_Address[i] = values[i]; + } } -} } // namespace pcpp diff --git a/Common++/src/OUILookup.cpp b/Common++/src/OUILookup.cpp index 0d5f5fc4e4..09a919e1f4 100644 --- a/Common++/src/OUILookup.cpp +++ b/Common++/src/OUILookup.cpp @@ -8,103 +8,102 @@ namespace pcpp { -template -int64_t OUILookup::internalParser(T &jsonData) -{ - // Clear all entries before adding - vendorMap.clear(); - - int64_t ctrRead = 0; - nlohmann::json parsedJson = nlohmann::json::parse(jsonData); - for (const auto &line : parsedJson.items()) + template int64_t OUILookup::internalParser(T &jsonData) { - if (!(line.value().is_object())) - continue; - auto val = line.value().get(); - if (!(val.contains("vendor"))) - continue; - - std::vector vLocalMaskedFilter; - if (val.contains("maskedFilters") && val["maskedFilters"].is_array()) + // Clear all entries before adding + vendorMap.clear(); + + int64_t ctrRead = 0; + nlohmann::json parsedJson = nlohmann::json::parse(jsonData); + for (const auto &line : parsedJson.items()) { - // Iterate through masked filters - for (const auto &entry : val["maskedFilters"]) + if (!(line.value().is_object())) + continue; + auto val = line.value().get(); + if (!(val.contains("vendor"))) + continue; + + std::vector vLocalMaskedFilter; + if (val.contains("maskedFilters") && val["maskedFilters"].is_array()) { - if (!entry.is_object()) - continue; - auto subVal = entry.get(); - if (subVal.contains("mask") && subVal.contains("vendors") && subVal["mask"].is_number_integer() && - subVal["vendors"].is_object()) + // Iterate through masked filters + for (const auto &entry : val["maskedFilters"]) { - int maskValue = subVal["mask"].get(); - vLocalMaskedFilter.push_back({maskValue, {}}); - - // Parse masked filter - for (const auto &subentry : subVal["vendors"].items()) + if (!entry.is_object()) + continue; + auto subVal = entry.get(); + if (subVal.contains("mask") && subVal.contains("vendors") && subVal["mask"].is_number_integer() && + subVal["vendors"].is_object()) { - if (subentry.value().is_string()) + int maskValue = subVal["mask"].get(); + vLocalMaskedFilter.push_back({maskValue, {}}); + + // Parse masked filter + for (const auto &subentry : subVal["vendors"].items()) { - vLocalMaskedFilter.back().vendorMap.insert( - {std::stoull(subentry.key()), subentry.value()}); - ++ctrRead; + if (subentry.value().is_string()) + { + vLocalMaskedFilter.back().vendorMap.insert( + {std::stoull(subentry.key()), subentry.value()}); + ++ctrRead; + } } } } } + + vendorMap.insert({std::stoull(line.key()), {val["vendor"], vLocalMaskedFilter}}); + ++ctrRead; } - vendorMap.insert({std::stoull(line.key()), {val["vendor"], vLocalMaskedFilter}}); - ++ctrRead; + PCPP_LOG_DEBUG(std::to_string(ctrRead) + " vendors read successfully"); + return ctrRead; } - PCPP_LOG_DEBUG(std::to_string(ctrRead) + " vendors read successfully"); - return ctrRead; -} + int64_t OUILookup::initOUIDatabaseFromJson(const std::string &path) + { + std::ifstream dataFile; -int64_t OUILookup::initOUIDatabaseFromJson(const std::string &path) -{ - std::ifstream dataFile; + // Open database + dataFile.open(path); + if (!dataFile.is_open()) + { + PCPP_LOG_ERROR(std::string("Can't open OUI database: ") + strerror(errno)); + return -1; + } - // Open database - dataFile.open(path); - if (!dataFile.is_open()) - { - PCPP_LOG_ERROR(std::string("Can't open OUI database: ") + strerror(errno)); - return -1; + // Parse values + return internalParser(dataFile); } - // Parse values - return internalParser(dataFile); -} + std::string OUILookup::getVendorName(const pcpp::MacAddress &addr) + { + if (vendorMap.empty()) + PCPP_LOG_DEBUG("Vendor map is empty"); -std::string OUILookup::getVendorName(const pcpp::MacAddress &addr) -{ - if (vendorMap.empty()) - PCPP_LOG_DEBUG("Vendor map is empty"); + // Get MAC address + uint8_t buffArray[6]; + addr.copyTo(buffArray); - // Get MAC address - uint8_t buffArray[6]; - addr.copyTo(buffArray); + uint64_t macAddr = (((uint64_t)((buffArray)[5]) << 0) + ((uint64_t)((buffArray)[4]) << 8) + + ((uint64_t)((buffArray)[3]) << 16) + ((uint64_t)((buffArray)[2]) << 24) + + ((uint64_t)((buffArray)[1]) << 32) + ((uint64_t)((buffArray)[0]) << 40)); - uint64_t macAddr = (((uint64_t)((buffArray)[5]) << 0) + ((uint64_t)((buffArray)[4]) << 8) + - ((uint64_t)((buffArray)[3]) << 16) + ((uint64_t)((buffArray)[2]) << 24) + - ((uint64_t)((buffArray)[1]) << 32) + ((uint64_t)((buffArray)[0]) << 40)); + auto itr = vendorMap.find(macAddr >> 24); + if (itr == vendorMap.end()) + return "Unknown"; - auto itr = vendorMap.find(macAddr >> 24); - if (itr == vendorMap.end()) - return "Unknown"; + for (const auto &entry : itr->second.maskedFilter) + { + uint64_t maskValue = ~((1 << (48 - entry.mask)) - 1); + uint64_t bufferAddr = macAddr & maskValue; - for (const auto &entry : itr->second.maskedFilter) - { - uint64_t maskValue = ~((1 << (48 - entry.mask)) - 1); - uint64_t bufferAddr = macAddr & maskValue; + auto subItr = entry.vendorMap.find(bufferAddr); + if (subItr != entry.vendorMap.end()) + return subItr->second; + } - auto subItr = entry.vendorMap.find(bufferAddr); - if (subItr != entry.vendorMap.end()) - return subItr->second; + return itr->second.vendorName; } - return itr->second.vendorName; -} - } // namespace pcpp diff --git a/Common++/src/PcapPlusPlusVersion.cpp b/Common++/src/PcapPlusPlusVersion.cpp index 4038147395..0c861f2572 100644 --- a/Common++/src/PcapPlusPlusVersion.cpp +++ b/Common++/src/PcapPlusPlusVersion.cpp @@ -3,25 +3,22 @@ namespace pcpp { -std::string getGitCommit() -{ - #ifdef GIT_COMMIT - return GIT_COMMIT; - #endif - return "unavailable"; -} + std::string getGitCommit() + { +#ifdef GIT_COMMIT + return GIT_COMMIT; +#endif + return "unavailable"; + } -std::string getGitBranch() -{ - #ifdef GIT_BRANCH - return GIT_BRANCH; - #endif - return "unavailable"; -} + std::string getGitBranch() + { +#ifdef GIT_BRANCH + return GIT_BRANCH; +#endif + return "unavailable"; + } -std::string getGitInfo() -{ - return "Git branch '" + getGitBranch() + "', commit '" + getGitCommit() + "'"; -} + std::string getGitInfo() { return "Git branch '" + getGitBranch() + "', commit '" + getGitCommit() + "'"; } -} +} // namespace pcpp diff --git a/Common++/src/SystemUtils.cpp b/Common++/src/SystemUtils.cpp index 85dbbc0d37..1f35753ae7 100644 --- a/Common++/src/SystemUtils.cpp +++ b/Common++/src/SystemUtils.cpp @@ -31,14 +31,14 @@ #endif #ifdef _MSC_VER -int gettimeofday(struct timeval * tp, struct timezone * tzp) +int gettimeofday(struct timeval *tp, struct timezone *tzp) { // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL); - SYSTEMTIME system_time; - FILETIME file_time; - uint64_t time; + SYSTEMTIME system_time; + FILETIME file_time; + uint64_t time; GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); @@ -61,7 +61,7 @@ namespace */ struct PcloseDeleter { - void operator()(FILE* ptr) const { PCLOSE(ptr); } + void operator()(FILE *ptr) const { PCLOSE(ptr); } }; } // namespace @@ -70,341 +70,300 @@ namespace namespace pcpp { -const SystemCore SystemCores::Core0 = { 0x01, 0 }; -const SystemCore SystemCores::Core1 = { 0x02, 1 }; -const SystemCore SystemCores::Core2 = { 0x04, 2 }; -const SystemCore SystemCores::Core3 = { 0x08, 3 }; -const SystemCore SystemCores::Core4 = { 0x10, 4 }; -const SystemCore SystemCores::Core5 = { 0x20, 5 }; -const SystemCore SystemCores::Core6 = { 0x40, 6 }; -const SystemCore SystemCores::Core7 = { 0x80, 7 }; -const SystemCore SystemCores::Core8 = { 0x100, 8 }; -const SystemCore SystemCores::Core9 = { 0x200, 9 }; -const SystemCore SystemCores::Core10 = { 0x400, 10 }; -const SystemCore SystemCores::Core11 = { 0x800, 11 }; -const SystemCore SystemCores::Core12 = { 0x1000, 12 }; -const SystemCore SystemCores::Core13 = { 0x2000, 13 }; -const SystemCore SystemCores::Core14 = { 0x4000, 14 }; -const SystemCore SystemCores::Core15 = { 0x8000, 15 }; -const SystemCore SystemCores::Core16 = { 0x10000, 16 }; -const SystemCore SystemCores::Core17 = { 0x20000, 17 }; -const SystemCore SystemCores::Core18 = { 0x40000, 18 }; -const SystemCore SystemCores::Core19 = { 0x80000, 19 }; -const SystemCore SystemCores::Core20 = { 0x100000, 20 }; -const SystemCore SystemCores::Core21 = { 0x200000, 21 }; -const SystemCore SystemCores::Core22 = { 0x400000, 22 }; -const SystemCore SystemCores::Core23 = { 0x800000, 23 }; -const SystemCore SystemCores::Core24 = { 0x1000000, 24 }; -const SystemCore SystemCores::Core25 = { 0x2000000, 25 }; -const SystemCore SystemCores::Core26 = { 0x4000000, 26 }; -const SystemCore SystemCores::Core27 = { 0x8000000, 27 }; -const SystemCore SystemCores::Core28 = { 0x10000000, 28 }; -const SystemCore SystemCores::Core29 = { 0x20000000, 29 }; -const SystemCore SystemCores::Core30 = { 0x40000000, 30 }; -const SystemCore SystemCores::Core31 = { 0x80000000, 31 }; - -const SystemCore SystemCores::IdToSystemCore[MAX_NUM_OF_CORES] = -{ - SystemCores::Core0, - SystemCores::Core1, - SystemCores::Core2, - SystemCores::Core3, - SystemCores::Core4, - SystemCores::Core5, - SystemCores::Core6, - SystemCores::Core7, - SystemCores::Core8, - SystemCores::Core9, - SystemCores::Core10, - SystemCores::Core11, - SystemCores::Core12, - SystemCores::Core13, - SystemCores::Core14, - SystemCores::Core15, - SystemCores::Core16, - SystemCores::Core17, - SystemCores::Core18, - SystemCores::Core19, - SystemCores::Core20, - SystemCores::Core21, - SystemCores::Core22, - SystemCores::Core23, - SystemCores::Core24, - SystemCores::Core25, - SystemCores::Core26, - SystemCores::Core27, - SystemCores::Core28, - SystemCores::Core29, - SystemCores::Core30, - SystemCores::Core31 -}; - - -int getNumOfCores() -{ + const SystemCore SystemCores::Core0 = {0x01, 0}; + const SystemCore SystemCores::Core1 = {0x02, 1}; + const SystemCore SystemCores::Core2 = {0x04, 2}; + const SystemCore SystemCores::Core3 = {0x08, 3}; + const SystemCore SystemCores::Core4 = {0x10, 4}; + const SystemCore SystemCores::Core5 = {0x20, 5}; + const SystemCore SystemCores::Core6 = {0x40, 6}; + const SystemCore SystemCores::Core7 = {0x80, 7}; + const SystemCore SystemCores::Core8 = {0x100, 8}; + const SystemCore SystemCores::Core9 = {0x200, 9}; + const SystemCore SystemCores::Core10 = {0x400, 10}; + const SystemCore SystemCores::Core11 = {0x800, 11}; + const SystemCore SystemCores::Core12 = {0x1000, 12}; + const SystemCore SystemCores::Core13 = {0x2000, 13}; + const SystemCore SystemCores::Core14 = {0x4000, 14}; + const SystemCore SystemCores::Core15 = {0x8000, 15}; + const SystemCore SystemCores::Core16 = {0x10000, 16}; + const SystemCore SystemCores::Core17 = {0x20000, 17}; + const SystemCore SystemCores::Core18 = {0x40000, 18}; + const SystemCore SystemCores::Core19 = {0x80000, 19}; + const SystemCore SystemCores::Core20 = {0x100000, 20}; + const SystemCore SystemCores::Core21 = {0x200000, 21}; + const SystemCore SystemCores::Core22 = {0x400000, 22}; + const SystemCore SystemCores::Core23 = {0x800000, 23}; + const SystemCore SystemCores::Core24 = {0x1000000, 24}; + const SystemCore SystemCores::Core25 = {0x2000000, 25}; + const SystemCore SystemCores::Core26 = {0x4000000, 26}; + const SystemCore SystemCores::Core27 = {0x8000000, 27}; + const SystemCore SystemCores::Core28 = {0x10000000, 28}; + const SystemCore SystemCores::Core29 = {0x20000000, 29}; + const SystemCore SystemCores::Core30 = {0x40000000, 30}; + const SystemCore SystemCores::Core31 = {0x80000000, 31}; + + const SystemCore SystemCores::IdToSystemCore[MAX_NUM_OF_CORES] = { + SystemCores::Core0, SystemCores::Core1, SystemCores::Core2, SystemCores::Core3, SystemCores::Core4, + SystemCores::Core5, SystemCores::Core6, SystemCores::Core7, SystemCores::Core8, SystemCores::Core9, + SystemCores::Core10, SystemCores::Core11, SystemCores::Core12, SystemCores::Core13, SystemCores::Core14, + SystemCores::Core15, SystemCores::Core16, SystemCores::Core17, SystemCores::Core18, SystemCores::Core19, + SystemCores::Core20, SystemCores::Core21, SystemCores::Core22, SystemCores::Core23, SystemCores::Core24, + SystemCores::Core25, SystemCores::Core26, SystemCores::Core27, SystemCores::Core28, SystemCores::Core29, + SystemCores::Core30, SystemCores::Core31}; + + int getNumOfCores() + { #if defined(_WIN32) - SYSTEM_INFO sysinfo; - GetSystemInfo( &sysinfo ); - return sysinfo.dwNumberOfProcessors; + SYSTEM_INFO sysinfo; + GetSystemInfo(&sysinfo); + return sysinfo.dwNumberOfProcessors; #else - return sysconf(_SC_NPROCESSORS_ONLN); + return sysconf(_SC_NPROCESSORS_ONLN); #endif -} - -CoreMask getCoreMaskForAllMachineCores() -{ - int numOfCores = getNumOfCores() < 32 ? getNumOfCores() : 32; - CoreMask result = 0; - for (int i = 0; i < numOfCores; i++) - { - result = result | SystemCores::IdToSystemCore[i].Mask; } - return result; -} - -CoreMask createCoreMaskFromCoreVector(const std::vector &cores) -{ - CoreMask result = 0; - for (const auto &core : cores) + CoreMask getCoreMaskForAllMachineCores() { - // cppcheck-suppress useStlAlgorithm - result |= core.Mask; - } - - return result; -} + int numOfCores = getNumOfCores() < 32 ? getNumOfCores() : 32; + CoreMask result = 0; + for (int i = 0; i < numOfCores; i++) + { + result = result | SystemCores::IdToSystemCore[i].Mask; + } -CoreMask createCoreMaskFromCoreIds(const std::vector &coreIds) -{ - CoreMask result = 0; - for (const auto &coreId : coreIds) - { - // cppcheck-suppress useStlAlgorithm - result |= SystemCores::IdToSystemCore[coreId].Mask; + return result; } - return result; -} - -void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector& resultVec) -{ - int i = 0; - while (coreMask != 0) + CoreMask createCoreMaskFromCoreVector(const std::vector &cores) { - if (1 & coreMask) + CoreMask result = 0; + for (const auto &core : cores) { - resultVec.push_back(SystemCores::IdToSystemCore[i]); + // cppcheck-suppress useStlAlgorithm + result |= core.Mask; } - coreMask = coreMask >> 1; - i++; + return result; } -} -std::string executeShellCommand(const std::string& command) -{ - std::unique_ptr pipe = std::unique_ptr(POPEN(command.c_str(), "r")); - if (!pipe) + CoreMask createCoreMaskFromCoreIds(const std::vector &coreIds) { - throw std::runtime_error("Error executing command: " + command); + CoreMask result = 0; + for (const auto &coreId : coreIds) + { + // cppcheck-suppress useStlAlgorithm + result |= SystemCores::IdToSystemCore[coreId].Mask; + } + + return result; } - std::array buffer; - std::string result; - while(!feof(pipe.get())) + void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector &resultVec) { - if(fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) - result += buffer.data(); // Using the C-string overload of string append. + int i = 0; + while (coreMask != 0) + { + if (1 & coreMask) + { + resultVec.push_back(SystemCores::IdToSystemCore[i]); + } + + coreMask = coreMask >> 1; + i++; + } } - return result; -} + std::string executeShellCommand(const std::string &command) + { + std::unique_ptr pipe = std::unique_ptr(POPEN(command.c_str(), "r")); + if (!pipe) + { + throw std::runtime_error("Error executing command: " + command); + } -bool directoryExists(const std::string &dirPath) -{ - struct stat info; - - if (stat(dirPath.c_str(), &info) != 0) - return false; - else if(info.st_mode & S_IFDIR) - return true; - else - return false; -} + std::array buffer; + std::string result; + while (!feof(pipe.get())) + { + if (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) + result += buffer.data(); // Using the C-string overload of string append. + } + return result; + } + bool directoryExists(const std::string &dirPath) + { + struct stat info; + + if (stat(dirPath.c_str(), &info) != 0) + return false; + else if (info.st_mode & S_IFDIR) + return true; + else + return false; + } -int clockGetTime(long& sec, long& nsec) -{ - sec = 0; - nsec = 0; + int clockGetTime(long &sec, long &nsec) + { + sec = 0; + nsec = 0; #if defined(_WIN32) #define CLOCK_GETTIME_BILLION (1E9) - static BOOL clock_gettime_first_time = 1; - static LARGE_INTEGER clock_gettime_counts_per_sec; - - LARGE_INTEGER count ; + static BOOL clock_gettime_first_time = 1; + static LARGE_INTEGER clock_gettime_counts_per_sec; - if (clock_gettime_first_time) - { - clock_gettime_first_time = 0; + LARGE_INTEGER count; - if (0 == QueryPerformanceFrequency(&clock_gettime_counts_per_sec)) + if (clock_gettime_first_time) { - clock_gettime_counts_per_sec.QuadPart = 0; + clock_gettime_first_time = 0; + + if (0 == QueryPerformanceFrequency(&clock_gettime_counts_per_sec)) + { + clock_gettime_counts_per_sec.QuadPart = 0; + } } - } - if ((clock_gettime_counts_per_sec.QuadPart <= 0) || (0 == QueryPerformanceCounter(&count))) - { - return -1; - } + if ((clock_gettime_counts_per_sec.QuadPart <= 0) || (0 == QueryPerformanceCounter(&count))) + { + return -1; + } - sec = count.QuadPart / clock_gettime_counts_per_sec.QuadPart; - nsec = ((count.QuadPart % clock_gettime_counts_per_sec.QuadPart) * CLOCK_GETTIME_BILLION) / clock_gettime_counts_per_sec.QuadPart; + sec = count.QuadPart / clock_gettime_counts_per_sec.QuadPart; + nsec = ((count.QuadPart % clock_gettime_counts_per_sec.QuadPart) * CLOCK_GETTIME_BILLION) / + clock_gettime_counts_per_sec.QuadPart; - return 0; + return 0; #elif defined(__APPLE__) - clock_serv_t cclock; - mach_timespec_t mts; - host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); - clock_get_time(cclock, &mts); - mach_port_deallocate(mach_task_self(), cclock); - sec = mts.tv_sec; - nsec = mts.tv_nsec; + clock_serv_t cclock; + mach_timespec_t mts; + host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); + clock_get_time(cclock, &mts); + mach_port_deallocate(mach_task_self(), cclock); + sec = mts.tv_sec; + nsec = mts.tv_nsec; - return 0; + return 0; #else // Linux - #include +#include - timespec ts; - int res = clock_gettime(CLOCK_REALTIME, &ts); - if (res == 0) - { - sec = ts.tv_sec; - nsec = ts.tv_nsec; - } - return res; + timespec ts; + int res = clock_gettime(CLOCK_REALTIME, &ts); + if (res == 0) + { + sec = ts.tv_sec; + nsec = ts.tv_nsec; + } + return res; #endif -} + } -void multiPlatformSleep(uint32_t seconds) -{ + void multiPlatformSleep(uint32_t seconds) + { #if defined(_WIN32) - Sleep(seconds*1000); + Sleep(seconds * 1000); #else - sleep(seconds); + sleep(seconds); #endif -} + } -void multiPlatformMSleep(uint32_t milliseconds) -{ + void multiPlatformMSleep(uint32_t milliseconds) + { #if defined(_WIN32) - Sleep(milliseconds); + Sleep(milliseconds); #else - usleep(milliseconds*1000); + usleep(milliseconds * 1000); #endif -} - -uint16_t hostToNet16(uint16_t host) -{ - return htobe16(host); -} + } -uint16_t netToHost16(uint16_t net) -{ - return be16toh(net); -} + uint16_t hostToNet16(uint16_t host) { return htobe16(host); } -uint32_t hostToNet32(uint32_t host) -{ - return htobe32(host); -} + uint16_t netToHost16(uint16_t net) { return be16toh(net); } -uint32_t netToHost32(uint32_t net) -{ - return be32toh(net); -} + uint32_t hostToNet32(uint32_t host) { return htobe32(host); } + uint32_t netToHost32(uint32_t net) { return be32toh(net); } -std::string AppName::m_AppName; + std::string AppName::m_AppName; #if defined(_WIN32) -int ApplicationEventHandler::handlerRoutine(unsigned long fdwCtrlType) -{ - switch (fdwCtrlType) + int ApplicationEventHandler::handlerRoutine(unsigned long fdwCtrlType) { + switch (fdwCtrlType) + { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: { if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL) - ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler(ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); + ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler( + ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); return TRUE; } default: return FALSE; + } } - -} #else -static std::mutex UnixLinuxHandlerRoutineMutex; + static std::mutex UnixLinuxHandlerRoutineMutex; -void ApplicationEventHandler::handlerRoutine(int signum) -{ - switch (signum) + void ApplicationEventHandler::handlerRoutine(int signum) { - case SIGINT: - { - // Most calls are unsafe in a signal handler, and this includes printf(). In particular, - // if the signal is caught while inside printf() it may be called twice at the same time which might not be a good idea - // The way to make sure the signal is called only once is using this lock and putting NULL in m_ApplicationInterruptedHandler - const std::lock_guard lock(UnixLinuxHandlerRoutineMutex); + switch (signum) + { + case SIGINT: + { + // Most calls are unsafe in a signal handler, and this includes printf(). In particular, + // if the signal is caught while inside printf() it may be called twice at the same time which might not be + // a good idea The way to make sure the signal is called only once is using this lock and putting NULL in + // m_ApplicationInterruptedHandler + const std::lock_guard lock(UnixLinuxHandlerRoutineMutex); - if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != nullptr) - ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler(ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); + if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != nullptr) + ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler( + ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); - ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler = nullptr; + ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler = nullptr; - return; - } - default: - { - return; - } + return; + } + default: + { + return; + } + } } -} #endif + ApplicationEventHandler::ApplicationEventHandler() + : m_ApplicationInterruptedHandler(nullptr), m_ApplicationInterruptedCookie(nullptr) + { + } -ApplicationEventHandler::ApplicationEventHandler() : - m_ApplicationInterruptedHandler(nullptr), m_ApplicationInterruptedCookie(nullptr) -{ -} - -void ApplicationEventHandler::onApplicationInterrupted(EventHandlerCallback handler, void* cookie) -{ - m_ApplicationInterruptedHandler = handler; - m_ApplicationInterruptedCookie = cookie; + void ApplicationEventHandler::onApplicationInterrupted(EventHandlerCallback handler, void *cookie) + { + m_ApplicationInterruptedHandler = handler; + m_ApplicationInterruptedCookie = cookie; #if defined(_WIN32) - SetConsoleCtrlHandler((PHANDLER_ROUTINE)handlerRoutine, TRUE); + SetConsoleCtrlHandler((PHANDLER_ROUTINE)handlerRoutine, TRUE); #else - struct sigaction action; - memset(&action, 0, sizeof(struct sigaction)); - action.sa_handler = handlerRoutine; - sigemptyset(&action.sa_mask); - sigaction(SIGINT, &action, nullptr); + struct sigaction action; + memset(&action, 0, sizeof(struct sigaction)); + action.sa_handler = handlerRoutine; + sigemptyset(&action.sa_mask); + sigaction(SIGINT, &action, nullptr); #endif -} + } } // namespace pcpp diff --git a/Common++/src/TablePrinter.cpp b/Common++/src/TablePrinter.cpp index 153801def2..74d5397dfa 100644 --- a/Common++/src/TablePrinter.cpp +++ b/Common++/src/TablePrinter.cpp @@ -12,121 +12,119 @@ namespace pcpp { -TablePrinter::TablePrinter(std::vector columnNames, std::vector columnWidths) : - m_ColumnNames(std::move(columnNames)), m_ColumnWidths(std::move(columnWidths)), - m_FirstRow(true), m_TableClosed(false) -{ - if (m_ColumnWidths.size() != m_ColumnNames.size()) + TablePrinter::TablePrinter(std::vector columnNames, std::vector columnWidths) + : m_ColumnNames(std::move(columnNames)), m_ColumnWidths(std::move(columnWidths)), m_FirstRow(true), + m_TableClosed(false) { - PCPP_LOG_ERROR("Cannot create table: number of column names provided is different than number of column widths provided"); - m_TableClosed = true; + if (m_ColumnWidths.size() != m_ColumnNames.size()) + { + PCPP_LOG_ERROR("Cannot create table: number of column names provided is different than number of column " + "widths provided"); + m_TableClosed = true; + } } -} -TablePrinter::~TablePrinter() -{ - closeTable(); -} + TablePrinter::~TablePrinter() { closeTable(); } -bool TablePrinter::printRow(std::vector values) -{ - // if table is already closed return false - if (m_TableClosed) + bool TablePrinter::printRow(std::vector values) { - PCPP_LOG_ERROR("Table is closed"); - return false; - } - - if (values.size() != m_ColumnWidths.size()) - { - PCPP_LOG_ERROR("Number of values in input doesn't equal to number of columns"); - return false; - } + // if table is already closed return false + if (m_TableClosed) + { + PCPP_LOG_ERROR("Table is closed"); + return false; + } - // if this is the first row printed - print the headline first - if (m_FirstRow) - { - printHeadline(); - m_FirstRow = false; - } + if (values.size() != m_ColumnWidths.size()) + { + PCPP_LOG_ERROR("Number of values in input doesn't equal to number of columns"); + return false; + } - for (int i = 0; i < (int)m_ColumnWidths.size(); i++) - { - std::string val = values.at(i); - if (val.length() > (size_t)m_ColumnWidths.at(i)) + // if this is the first row printed - print the headline first + if (m_FirstRow) { - val.erase(m_ColumnWidths.at(i)-3, std::string::npos); - val += "..."; + printHeadline(); + m_FirstRow = false; } - std::cout << std::left << "| " << std::setw(m_ColumnWidths.at(i)) << val << " "; - } + for (int i = 0; i < (int)m_ColumnWidths.size(); i++) + { + std::string val = values.at(i); + if (val.length() > (size_t)m_ColumnWidths.at(i)) + { + val.erase(m_ColumnWidths.at(i) - 3, std::string::npos); + val += "..."; + } + + std::cout << std::left << "| " << std::setw(m_ColumnWidths.at(i)) << val << " "; + } - std::cout << "|" << std::endl; + std::cout << "|" << std::endl; - return true; -} + return true; + } -bool TablePrinter::printRow(const std::string& values, char delimiter) -{ - std::string singleValue; - std::istringstream valueStream(values); - std::vector valuesAsVec; - while (std::getline(valueStream, singleValue, delimiter)) + bool TablePrinter::printRow(const std::string &values, char delimiter) { - valuesAsVec.push_back(singleValue); - } + std::string singleValue; + std::istringstream valueStream(values); + std::vector valuesAsVec; + while (std::getline(valueStream, singleValue, delimiter)) + { + valuesAsVec.push_back(singleValue); + } - return printRow(valuesAsVec); -} + return printRow(valuesAsVec); + } -void TablePrinter::printSeparator() -{ - // if table is already closed return - if (m_TableClosed) + void TablePrinter::printSeparator() { - PCPP_LOG_ERROR("Table is closed"); - return; - } + // if table is already closed return + if (m_TableClosed) + { + PCPP_LOG_ERROR("Table is closed"); + return; + } - auto totalLen = std::accumulate(m_ColumnWidths.begin(), m_ColumnWidths.end(), m_ColumnWidths.size() * 3) + 1; - std::cout << std::string(totalLen, '-') << std::endl; -} + auto totalLen = std::accumulate(m_ColumnWidths.begin(), m_ColumnWidths.end(), m_ColumnWidths.size() * 3) + 1; + std::cout << std::string(totalLen, '-') << std::endl; + } -void TablePrinter::closeTable() -{ - // if this method was already called - do nothing - if (m_TableClosed) - return; + void TablePrinter::closeTable() + { + // if this method was already called - do nothing + if (m_TableClosed) + return; - // if no rows were printed - do nothing - if (m_FirstRow) - return; + // if no rows were printed - do nothing + if (m_FirstRow) + return; - printSeparator(); + printSeparator(); - m_TableClosed = true; -} + m_TableClosed = true; + } -void TablePrinter::printHeadline() -{ - // if table is already closed return - if (m_TableClosed) + void TablePrinter::printHeadline() { - PCPP_LOG_ERROR("Table is closed"); - return; - } + // if table is already closed return + if (m_TableClosed) + { + PCPP_LOG_ERROR("Table is closed"); + return; + } - printSeparator(); + printSeparator(); - for (int i = 0; i < (int)m_ColumnWidths.size(); i++) - { - std::cout << std::left << "| " << std::setw(m_ColumnWidths.at(i)) << m_ColumnNames.at(i) << " "; - } + for (int i = 0; i < (int)m_ColumnWidths.size(); i++) + { + std::cout << std::left << "| " << std::setw(m_ColumnWidths.at(i)) << m_ColumnNames.at(i) << " "; + } - std::cout << "|" << std::endl; + std::cout << "|" << std::endl; - printSeparator(); -} + printSeparator(); + } -} +} // namespace pcpp From 8531104d182ecd71f484630d11bce6251b37f711 Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Tue, 18 Jun 2024 18:06:22 +0900 Subject: [PATCH 03/13] ignore format commit --- . git-blame-ignore-revs | 1 + 1 file changed, 1 insertion(+) diff --git a/. git-blame-ignore-revs b/. git-blame-ignore-revs index e69de29bb2..6742caea3a 100644 --- a/. git-blame-ignore-revs +++ b/. git-blame-ignore-revs @@ -0,0 +1 @@ +3b0b2283141d772783881db1bf280714a3c7c462 From e30c33846f7025507c774edc0a9608a2432c3d58 Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Tue, 18 Jun 2024 18:16:06 +0900 Subject: [PATCH 04/13] concate install --- .github/workflows/build_and_test.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index 677f1bb01e..f3044812e2 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -29,8 +29,7 @@ jobs: - name: Install dependencies run: | apk update && apk add cppcheck python3-dev - python3 -m pip install cmake-format - pip install clang-format==18.1.6 + python3 -m pip install cmake-format clang-format==18.1.6 - uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1 From bddf121c314543c112a3e87ff40deaa72c5232ca Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Tue, 18 Jun 2024 18:25:43 +0900 Subject: [PATCH 05/13] Revert "ignore format commit" This reverts commit 8531104d182ecd71f484630d11bce6251b37f711. --- . git-blame-ignore-revs | 1 - 1 file changed, 1 deletion(-) diff --git a/. git-blame-ignore-revs b/. git-blame-ignore-revs index 6742caea3a..e69de29bb2 100644 --- a/. git-blame-ignore-revs +++ b/. git-blame-ignore-revs @@ -1 +0,0 @@ -3b0b2283141d772783881db1bf280714a3c7c462 From 7a8d3ea0b09b254afc2d6187fc7f7aa4d1ae357c Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Wed, 19 Jun 2024 10:25:47 +0900 Subject: [PATCH 06/13] add indent for macro --- .clang-format | 2 ++ Common++/header/DeprecationUtils.h | 48 +++++++++++++++--------------- Common++/header/IpUtils.h | 16 +++++----- Common++/header/LRUList.h | 2 +- Common++/header/Logger.h | 6 ++-- Common++/header/TimespecTimeval.h | 20 ++++++------- Common++/src/IpAddress.cpp | 2 +- Common++/src/IpUtils.cpp | 14 ++++----- Common++/src/SystemUtils.cpp | 18 +++++------ 9 files changed, 65 insertions(+), 63 deletions(-) diff --git a/.clang-format b/.clang-format index fdee82e4f7..418faad0b9 100644 --- a/.clang-format +++ b/.clang-format @@ -5,4 +5,6 @@ BreakBeforeBraces: Allman AllowShortFunctionsOnASingleLine: All NamespaceIndentation: All SortIncludes: false +IndentPPDirectives: AfterHash +IndentWidth: 4 ... diff --git a/Common++/header/DeprecationUtils.h b/Common++/header/DeprecationUtils.h index 2f3f782bba..ab91c87c86 100644 --- a/Common++/header/DeprecationUtils.h +++ b/Common++/header/DeprecationUtils.h @@ -3,37 +3,37 @@ /// @file #ifndef PCPP_DEPRECATED -#if defined(__GNUC__) || defined(__clang__) -#define PCPP_DEPRECATED(msg) __attribute__((deprecated(msg))) -#elif defined(_MSC_VER) -#define PCPP_DEPRECATED(msg) __declspec(deprecated(msg)) -#else -#pragma message("WARNING: DEPRECATED feature is not implemented for this compiler") -#define PCPP_DEPRECATED(msg) -#endif +# if defined(__GNUC__) || defined(__clang__) +# define PCPP_DEPRECATED(msg) __attribute__((deprecated(msg))) +# elif defined(_MSC_VER) +# define PCPP_DEPRECATED(msg) __declspec(deprecated(msg)) +# else +# pragma message("WARNING: DEPRECATED feature is not implemented for this compiler") +# define PCPP_DEPRECATED(msg) +# endif #endif #if !defined(DISABLE_WARNING_PUSH) || !defined(DISABLE_WARNING_POP) -#if defined(_MSC_VER) -#define DISABLE_WARNING_PUSH __pragma(warning(push)) -#define DISABLE_WARNING_POP __pragma(warning(pop)) -#define DISABLE_WARNING(warningNumber) __pragma(warning(disable : warningNumber)) +# if defined(_MSC_VER) +# define DISABLE_WARNING_PUSH __pragma(warning(push)) +# define DISABLE_WARNING_POP __pragma(warning(pop)) +# define DISABLE_WARNING(warningNumber) __pragma(warning(disable : warningNumber)) -#define DISABLE_WARNING_DEPRECATED DISABLE_WARNING(4996) -#elif defined(__GNUC__) || defined(__clang__) -#define DO_PRAGMA(X) _Pragma(#X) -#define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) -#define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) -#define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName) +# define DISABLE_WARNING_DEPRECATED DISABLE_WARNING(4996) +# elif defined(__GNUC__) || defined(__clang__) +# define DO_PRAGMA(X) _Pragma(#X) +# define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) +# define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) +# define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName) // clang-format off #define DISABLE_WARNING_DEPRECATED DISABLE_WARNING(-Wdeprecated-declarations) // clang-format on -#else -#pragma message("WARNING: Disabling of warnings is not implemented for this compiler") -#define DISABLE_WARNING_PUSH -#define DISABLE_WARNING_POP +# else +# pragma message("WARNING: Disabling of warnings is not implemented for this compiler") +# define DISABLE_WARNING_PUSH +# define DISABLE_WARNING_POP -#define DISABLE_WARNING_DEPRECATED -#endif +# define DISABLE_WARNING_DEPRECATED +# endif #endif diff --git a/Common++/header/IpUtils.h b/Common++/header/IpUtils.h index 5ddcdca6a8..de829340aa 100644 --- a/Common++/header/IpUtils.h +++ b/Common++/header/IpUtils.h @@ -2,20 +2,20 @@ #include #ifdef __linux__ -#include -#include +# include +# include #endif #if defined(__APPLE__) -#include -#include +# include +# include #endif #if defined(_WIN32) -#include +# include #endif #if defined(__FreeBSD__) -#include -#include -#include +# include +# include +# include #endif /// @file diff --git a/Common++/header/LRUList.h b/Common++/header/LRUList.h index 7cb84f96ed..7ddaf1948e 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -4,7 +4,7 @@ #include #if __cplusplus > 199711L || _MSC_VER >= 1800 -#include +# include #endif /// @file diff --git a/Common++/header/Logger.h b/Common++/header/Logger.h index 91866ee317..7dcb73908b 100644 --- a/Common++/header/Logger.h +++ b/Common++/header/Logger.h @@ -7,14 +7,14 @@ #include #ifndef LOG_MODULE -#define LOG_MODULE UndefinedLogModule +# define LOG_MODULE UndefinedLogModule #endif // Use __FILE_NAME__ to avoid leaking complete full path #ifdef __FILE_NAME__ -#define PCAPPP_FILENAME __FILE_NAME__ +# define PCAPPP_FILENAME __FILE_NAME__ #else -#define PCAPPP_FILENAME __FILE__ +# define PCAPPP_FILENAME __FILE__ #endif #define PCPP_LOG(level, message) \ diff --git a/Common++/header/TimespecTimeval.h b/Common++/header/TimespecTimeval.h index d469f112f7..52c291778d 100644 --- a/Common++/header/TimespecTimeval.h +++ b/Common++/header/TimespecTimeval.h @@ -3,17 +3,17 @@ #pragma once #ifndef TIMEVAL_TO_TIMESPEC -#define TIMEVAL_TO_TIMESPEC(tv, ts) \ - { \ - (ts)->tv_sec = (tv)->tv_sec; \ - (ts)->tv_nsec = (tv)->tv_usec * 1000; \ - } +# define TIMEVAL_TO_TIMESPEC(tv, ts) \ + { \ + (ts)->tv_sec = (tv)->tv_sec; \ + (ts)->tv_nsec = (tv)->tv_usec * 1000; \ + } #endif #ifndef TIMESPEC_TO_TIMEVAL -#define TIMESPEC_TO_TIMEVAL(tv, ts) \ - { \ - (tv)->tv_sec = (ts)->tv_sec; \ - (tv)->tv_usec = (ts)->tv_nsec / 1000; \ - } +# define TIMESPEC_TO_TIMEVAL(tv, ts) \ + { \ + (tv)->tv_sec = (ts)->tv_sec; \ + (tv)->tv_usec = (ts)->tv_nsec / 1000; \ + } #endif diff --git a/Common++/src/IpAddress.cpp b/Common++/src/IpAddress.cpp index 039d9e0fd9..0602466165 100644 --- a/Common++/src/IpAddress.cpp +++ b/Common++/src/IpAddress.cpp @@ -14,7 +14,7 @@ // for AF_INET, AF_INET6 #if !defined(_WIN32) -#include +# include #endif namespace pcpp diff --git a/Common++/src/IpUtils.cpp b/Common++/src/IpUtils.cpp index 349e02bf09..7cc9967ca3 100644 --- a/Common++/src/IpUtils.cpp +++ b/Common++/src/IpUtils.cpp @@ -6,13 +6,13 @@ #include #include #ifndef NS_INADDRSZ -#define NS_INADDRSZ 4 +# define NS_INADDRSZ 4 #endif #ifndef NS_IN6ADDRSZ -#define NS_IN6ADDRSZ 16 +# define NS_IN6ADDRSZ 16 #endif #ifndef NS_INT16SZ -#define NS_INT16SZ 2 +# define NS_INT16SZ 2 #endif namespace pcpp @@ -426,14 +426,14 @@ int inet_pton(int af, const char *src, void *dst) { switch (af) { -#ifdef AF_INET +# ifdef AF_INET case AF_INET: return (inet_pton4(src, (uint8_t *)dst)); -#endif -#ifdef AF_INET6 +# endif +# ifdef AF_INET6 case AF_INET6: return (inet_pton6(src, (uint8_t *)dst)); -#endif +# endif default: return (-1); } diff --git a/Common++/src/SystemUtils.cpp b/Common++/src/SystemUtils.cpp index 1f35753ae7..bb08f88d6a 100644 --- a/Common++/src/SystemUtils.cpp +++ b/Common++/src/SystemUtils.cpp @@ -2,7 +2,7 @@ #include "EndianPortable.h" #ifndef _MSC_VER -#include +# include #endif #include #include @@ -14,20 +14,20 @@ #include #include #if defined(__APPLE__) -#include -#include +# include +# include #endif #if defined(_WIN32) -#define POPEN _popen +# define POPEN _popen #else -#define POPEN popen +# define POPEN popen #endif #if defined(_WIN32) -#define PCLOSE _pclose +# define PCLOSE _pclose #else -#define PCLOSE pclose +# define PCLOSE pclose #endif #ifdef _MSC_VER @@ -211,7 +211,7 @@ namespace pcpp #if defined(_WIN32) -#define CLOCK_GETTIME_BILLION (1E9) +# define CLOCK_GETTIME_BILLION (1E9) static BOOL clock_gettime_first_time = 1; static LARGE_INTEGER clock_gettime_counts_per_sec; @@ -253,7 +253,7 @@ namespace pcpp #else // Linux -#include +# include timespec ts; int res = clock_gettime(CLOCK_REALTIME, &ts); From 593f0b4cc8e9376c85e8e45db239222213e00220 Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Wed, 19 Jun 2024 17:55:05 +0900 Subject: [PATCH 07/13] update --- .clang-format | 13 +- Common++/header/GeneralUtils.h | 8 +- Common++/header/IpAddress.h | 300 +++++++++++++++++--------- Common++/header/IpAddressUtils.h | 70 ++++-- Common++/header/IpUtils.h | 18 +- Common++/header/LRUList.h | 37 +++- Common++/header/Logger.h | 195 +++++++++-------- Common++/header/MacAddress.h | 38 ++-- Common++/header/OUILookup.h | 12 +- Common++/header/PcapPlusPlusVersion.h | 17 +- Common++/header/PointerVector.h | 78 +++++-- Common++/header/SystemUtils.h | 44 ++-- Common++/header/TablePrinter.h | 8 +- Common++/src/GeneralUtils.cpp | 12 +- Common++/src/IpAddress.cpp | 83 +++---- Common++/src/IpAddressUtils.cpp | 15 +- Common++/src/IpUtils.cpp | 50 ++--- Common++/src/Logger.cpp | 17 +- Common++/src/MacAddress.cpp | 4 +- Common++/src/OUILookup.cpp | 20 +- Common++/src/PcapPlusPlusVersion.cpp | 7 +- Common++/src/SystemUtils.cpp | 61 ++++-- Common++/src/TablePrinter.cpp | 9 +- 23 files changed, 697 insertions(+), 419 deletions(-) diff --git a/.clang-format b/.clang-format index 418faad0b9..05d878e550 100644 --- a/.clang-format +++ b/.clang-format @@ -1,10 +1,19 @@ --- BasedOnStyle: Microsoft -UseTab: Always +UseTab: ForIndentation BreakBeforeBraces: Allman -AllowShortFunctionsOnASingleLine: All +AllowShortFunctionsOnASingleLine: None NamespaceIndentation: All SortIncludes: false IndentPPDirectives: AfterHash IndentWidth: 4 +AllowShortBlocksOnASingleLine: Never +PointerAlignment: Left +AccessModifierOffset: -1 +AlignTrailingComments: true +AllowShortEnumsOnASingleLine: false +BreakStringLiterals: true +AlignArrayOfStructures: Left +BreakArrays: true +SpacesBeforeTrailingComments: 2 ... diff --git a/Common++/header/GeneralUtils.h b/Common++/header/GeneralUtils.h index eb8abd8bd4..9452cc2f41 100644 --- a/Common++/header/GeneralUtils.h +++ b/Common++/header/GeneralUtils.h @@ -23,7 +23,7 @@ namespace pcpp * value is -1 which means no string size limitation * @return A string of hex characters representing the byte array */ - std::string byteArrayToHexString(const uint8_t *byteArr, size_t byteArrSize, int stringSizeLimit = -1); + std::string byteArrayToHexString(const uint8_t* byteArr, size_t byteArrSize, int stringSizeLimit = -1); /** * Convert a string of hex characters into a byte array. For example: for the string "aa2b10" an array of values @@ -38,7 +38,7 @@ namespace pcpp * size will be the part of the array that contain data. If the input is an illegal hex string 0 will be returned. * Illegal hex string means odd number of characters or a string that contains non-hex characters */ - size_t hexStringToByteArray(const std::string &hexString, uint8_t *resultByteArr, size_t resultByteArrSize); + size_t hexStringToByteArray(const std::string& hexString, uint8_t* resultByteArr, size_t resultByteArrSize); /** * This is a cross platform version of memmem (https://man7.org/linux/man-pages/man3/memmem.3.html) which is not @@ -49,7 +49,7 @@ namespace pcpp * @param[in] needleLen Length of the needle buffer * @return A pointer to the beginning of the substring, or NULL if the substring is not found */ - char *cross_platform_memmem(const char *haystack, size_t haystackLen, const char *needle, size_t needleLen); + char* cross_platform_memmem(const char* haystack, size_t haystackLen, const char* needle, size_t needleLen); /** * Calculates alignment. @@ -77,4 +77,4 @@ namespace pcpp return static_cast::type>(value); } }; -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/header/IpAddress.h b/Common++/header/IpAddress.h index 33af35f335..f87bfac48b 100644 --- a/Common++/header/IpAddress.h +++ b/Common++/header/IpAddress.h @@ -30,7 +30,7 @@ namespace pcpp */ class IPv4Address { - public: + public: /** * A default constructor that creates an instance of the class with the zero-initialized address */ @@ -40,19 +40,27 @@ namespace pcpp * A constructor that creates an instance of the class out of 4-byte integer value. * @param[in] addrAsInt The address as 4-byte integer in network byte order */ - IPv4Address(const uint32_t addrAsInt) { memcpy(m_Bytes.data(), &addrAsInt, sizeof(addrAsInt)); } + IPv4Address(const uint32_t addrAsInt) + { + memcpy(m_Bytes.data(), &addrAsInt, sizeof(addrAsInt)); + } /** * A constructor that creates an instance of the class out of 4-byte array. * @param[in] bytes The address as 4-byte array in network byte order */ - IPv4Address(const uint8_t bytes[4]) { memcpy(m_Bytes.data(), bytes, 4 * sizeof(uint8_t)); } + IPv4Address(const uint8_t bytes[4]) + { + memcpy(m_Bytes.data(), bytes, 4 * sizeof(uint8_t)); + } /** * A constructor that creates an instance of the class out of a 4-byte standard array. * @param[in] bytes The address as 4-byte standard array in network byte order */ - IPv4Address(const std::array &bytes) : m_Bytes(bytes) {} + IPv4Address(const std::array& bytes) : m_Bytes(bytes) + { + } /** * A constructor that creates an instance of the class out of std::string value. @@ -60,7 +68,7 @@ namespace pcpp * @param[in] addrAsString The std::string representation of the address * @throws std::invalid_argument The provided string does not represent a valid IPv4 address. */ - IPv4Address(const std::string &addrAsString); + IPv4Address(const std::string& addrAsString); /** * @return A 4-byte integer in network byte order representing the IPv4 address @@ -70,12 +78,18 @@ namespace pcpp /** * @return A non-owning pointer to 4-byte C-style array representing the IPv4 address */ - const uint8_t *toBytes() const { return m_Bytes.data(); } + const uint8_t* toBytes() const + { + return m_Bytes.data(); + } /** * @return A reference to a 4-byte standard array representing the IPv4 address */ - const std::array &toByteArray() const { return m_Bytes; } + const std::array& toByteArray() const + { + return m_Bytes; + } /** * @return A string representation of the address @@ -92,21 +106,24 @@ namespace pcpp * @param[in] rhs The object to compare with * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPv4Address &rhs) const { return toInt() == rhs.toInt(); } + bool operator==(const IPv4Address& rhs) const + { + return toInt() == rhs.toInt(); + } /** * Overload of the less-than operator * @param[in] rhs The object to compare with * @return True if the address value is lower than the other address value, false otherwise */ - bool operator<(const IPv4Address &rhs) const + bool operator<(const IPv4Address& rhs) const { uint32_t intVal = toInt(); - std::reverse(reinterpret_cast(&intVal), reinterpret_cast(&intVal) + sizeof(intVal)); + std::reverse(reinterpret_cast(&intVal), reinterpret_cast(&intVal) + sizeof(intVal)); uint32_t rhsIntVal = rhs.toInt(); - std::reverse(reinterpret_cast(&rhsIntVal), - reinterpret_cast(&rhsIntVal) + sizeof(rhsIntVal)); + std::reverse(reinterpret_cast(&rhsIntVal), + reinterpret_cast(&rhsIntVal) + sizeof(rhsIntVal)); return intVal < rhsIntVal; } @@ -116,14 +133,17 @@ namespace pcpp * @param[in] rhs The object to compare with * @return True if the addresses are not equal, false otherwise */ - bool operator!=(const IPv4Address &rhs) const { return !(*this == rhs); } + bool operator!=(const IPv4Address& rhs) const + { + return !(*this == rhs); + } /** * Checks whether the address matches a network. * @param network An IPv4Network network * @return True if the address matches the network or false otherwise */ - bool matchNetwork(const IPv4Network &network) const; + bool matchNetwork(const IPv4Network& network) const; /** * Checks whether the address matches a network. @@ -136,14 +156,14 @@ namespace pcpp * - X.X.X.X/Y.Y.Y.Y where X.X.X.X is a valid IP address and Y.Y.Y.Y is a valid netmask * @return True if the address matches the network or false if it doesn't or if the network is invalid */ - bool matchNetwork(const std::string &network) const; + bool matchNetwork(const std::string& network) const; /** * A static method that checks whether a string represents a valid IPv4 address * @param[in] addrAsString The std::string representation of the address * @return True if the address is valid, false otherwise */ - static bool isValidIPv4Address(const std::string &addrAsString); + static bool isValidIPv4Address(const std::string& addrAsString); /** * A static value representing a zero value of IPv4 address, meaning address of value "0.0.0.0". @@ -159,9 +179,9 @@ namespace pcpp static const IPv4Address MulticastRangeLowerBound; static const IPv4Address MulticastRangeUpperBound; - private: + private: std::array m_Bytes = {0}; - }; // class IPv4Address + }; // class IPv4Address // Implementation of inline methods @@ -178,7 +198,7 @@ namespace pcpp */ class IPv6Address { - public: + public: /** * A default constructor that creates an instance of the class with the zero-initialized address. */ @@ -188,13 +208,18 @@ namespace pcpp * A constructor that creates an instance of the class out of 16-byte array. * @param[in] bytes The address as 16-byte array in network byte order */ - IPv6Address(const uint8_t bytes[16]) { memcpy(m_Bytes.data(), bytes, 16 * sizeof(uint8_t)); } + IPv6Address(const uint8_t bytes[16]) + { + memcpy(m_Bytes.data(), bytes, 16 * sizeof(uint8_t)); + } /** * A constructor that creates an instance of the class out of a 16-byte standard array. * @param[in] bytes The address as 16-byte standard array in network byte order */ - IPv6Address(const std::array &bytes) : m_Bytes(bytes) {} + IPv6Address(const std::array& bytes) : m_Bytes(bytes) + { + } /** * A constructor that creates an instance of the class out of std::string value. @@ -202,19 +227,25 @@ namespace pcpp * @param[in] addrAsString The std::string representation of the address * @throws std::invalid_argument The provided string does not represent a valid IPv6 address. */ - IPv6Address(const std::string &addrAsString); + IPv6Address(const std::string& addrAsString); /** * Returns a view of the IPv6 address as a 16-byte raw C-style array * @return A non-owning pointer to 16-byte array representing the IPv6 address */ - const uint8_t *toBytes() const { return m_Bytes.data(); } + const uint8_t* toBytes() const + { + return m_Bytes.data(); + } /** * Returns a view of the IPv6 address as a std::array of bytes * @return A reference to a 16-byte standard array representing the IPv6 address */ - const std::array &toByteArray() const { return m_Bytes; } + const std::array& toByteArray() const + { + return m_Bytes; + } /** * Returns a std::string representation of the address @@ -233,42 +264,54 @@ namespace pcpp * @param[in] rhs The object to compare with * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPv6Address &rhs) const { return memcmp(toBytes(), rhs.toBytes(), sizeof(m_Bytes)) == 0; } + bool operator==(const IPv6Address& rhs) const + { + return memcmp(toBytes(), rhs.toBytes(), sizeof(m_Bytes)) == 0; + } /** * Overload of the less-than operator * @param[in] rhs The object to compare with * @return True if the address value is lower than the other address value, false otherwise */ - bool operator<(const IPv6Address &rhs) const { return memcmp(toBytes(), rhs.toBytes(), sizeof(m_Bytes)) < 0; } + bool operator<(const IPv6Address& rhs) const + { + return memcmp(toBytes(), rhs.toBytes(), sizeof(m_Bytes)) < 0; + } /** * Overload of the not-equal-to operator * @param[in] rhs The object to compare with * @return True if the addresses are not equal, false otherwise */ - bool operator!=(const IPv6Address &rhs) const { return !(*this == rhs); } + bool operator!=(const IPv6Address& rhs) const + { + return !(*this == rhs); + } /** * Allocates a byte array and copies address value into it. Array deallocation is user responsibility * @param[in] arr A pointer to where array will be allocated * @param[out] length Returns the length in bytes of the array that was allocated */ - void copyTo(uint8_t **arr, size_t &length) const; + void copyTo(uint8_t** arr, size_t& length) const; /** * Gets a pointer to an already allocated byte array and copies the address value to it. * This method assumes array allocated size is at least 16 (the size of an IPv6 address) * @param[in] arr A pointer to the array which address will be copied to */ - void copyTo(uint8_t *arr) const { memcpy(arr, m_Bytes.data(), m_Bytes.size() * sizeof(uint8_t)); } + void copyTo(uint8_t* arr) const + { + memcpy(arr, m_Bytes.data(), m_Bytes.size() * sizeof(uint8_t)); + } /** * Checks whether the address matches a network. * @param network An IPv6Network network * @return True if the address matches the network or false otherwise */ - bool matchNetwork(const IPv6Network &network) const; + bool matchNetwork(const IPv6Network& network) const; /** * Checks whether the address matches a network. @@ -283,14 +326,14 @@ namespace pcpp * IPv6 netmask * @return True if the address matches the network or false if it doesn't or if the network is invalid */ - bool matchNetwork(const std::string &network) const; + bool matchNetwork(const std::string& network) const; /** * A static method that checks whether a string represents a valid IPv6 address * @param[in] addrAsString The std::string representation of the address * @return True if the address is valid, false otherwise */ - static bool isValidIPv6Address(const std::string &addrAsString); + static bool isValidIPv6Address(const std::string& addrAsString); /** * A static value representing a zero value of IPv6 address, meaning address of value @@ -305,9 +348,9 @@ namespace pcpp */ static const IPv6Address MulticastRangeLowerBound; - private: + private: std::array m_Bytes = {0}; - }; // class IPv6Address + }; // class IPv6Address /** * @class IPAddress @@ -315,7 +358,7 @@ namespace pcpp */ class IPAddress { - public: + public: /** * An enum representing the address type: IPv4 or IPv6 */ @@ -334,19 +377,25 @@ namespace pcpp /** * A default constructor that creates an instance of the class with unspecified IPv4 address */ - IPAddress() : m_Type(IPv4AddressType) {} + IPAddress() : m_Type(IPv4AddressType) + { + } /** * A constructor that creates an instance of the class out of IPv4Address. * @param[in] addr A const reference to instance of IPv4Address */ - IPAddress(const IPv4Address &addr) : m_Type(IPv4AddressType), m_IPv4(addr) {} + IPAddress(const IPv4Address& addr) : m_Type(IPv4AddressType), m_IPv4(addr) + { + } /** * A constructor that creates an instance of the class out of IPv6Address. * @param[in] addr A const reference to instance of IPv6Address */ - IPAddress(const IPv6Address &addr) : m_Type(IPv6AddressType), m_IPv6(addr) {} + IPAddress(const IPv6Address& addr) : m_Type(IPv6AddressType), m_IPv6(addr) + { + } /** * A constructor that creates an instance of the class out of std::string value @@ -354,43 +403,55 @@ namespace pcpp * @param[in] addrAsString The std::string representation of the address * @throws std::invalid_argument The provided string does not represent a valid IPv4 or IPv6 address. */ - IPAddress(const std::string &addrAsString); + IPAddress(const std::string& addrAsString); /** * Overload of an assignment operator. * @param[in] addr A const reference to instance of IPv4Address * @return A reference to the assignee */ - inline IPAddress &operator=(const IPv4Address &addr); + inline IPAddress& operator=(const IPv4Address& addr); /** * Overload of an assignment operator. * @param[in] addr A const reference to instance of IPv6Address * @return A reference to the assignee */ - inline IPAddress &operator=(const IPv6Address &addr); + inline IPAddress& operator=(const IPv6Address& addr); /** * Gets the address type: IPv4 or IPv6 * @return The address type */ - AddressType getType() const { return static_cast(m_Type); } + AddressType getType() const + { + return static_cast(m_Type); + } /** * Returns a std::string representation of the address * @return A string representation of the address */ - std::string toString() const { return (getType() == IPv4AddressType) ? m_IPv4.toString() : m_IPv6.toString(); } + std::string toString() const + { + return (getType() == IPv4AddressType) ? m_IPv4.toString() : m_IPv6.toString(); + } /** * @return Determine whether the object contains an IP version 4 address */ - bool isIPv4() const { return getType() == IPv4AddressType; } + bool isIPv4() const + { + return getType() == IPv4AddressType; + } /** * @return Determine whether the object contains an IP version 6 address */ - bool isIPv6() const { return getType() == IPv6AddressType; } + bool isIPv6() const + { + return getType() == IPv6AddressType; + } /** * Determine whether the address is a multicast address @@ -405,13 +466,19 @@ namespace pcpp * Get a reference to IPv4 address instance * @return The const reference to IPv4Address instance */ - const IPv4Address &getIPv4() const { return m_IPv4; } + const IPv4Address& getIPv4() const + { + return m_IPv4; + } /** * Get a reference to IPv6 address instance * @return The const reference to IPv6Address instance */ - const IPv6Address &getIPv6() const { return m_IPv6; } + const IPv6Address& getIPv6() const + { + return m_IPv6; + } /** * @return True if the address is zero, false otherwise @@ -426,23 +493,26 @@ namespace pcpp * @param[in] rhs The object to compare with * @return True if the addresses are equal, false otherwise */ - inline bool operator==(const IPAddress &rhs) const; + inline bool operator==(const IPAddress& rhs) const; /** * Overload of the less-than operator * @param[in] rhs The object to compare with * @return True if the address value is lower than the other address value, false otherwise */ - inline bool operator<(const IPAddress &rhs) const; + inline bool operator<(const IPAddress& rhs) const; /** * Overload of the not-equal-to operator * @param[in] rhs The object to compare with * @return True if the addresses are not equal, false otherwise */ - bool operator!=(const IPAddress &rhs) const { return !(*this == rhs); } + bool operator!=(const IPAddress& rhs) const + { + return !(*this == rhs); + } - private: + private: uint8_t m_Type; IPv4Address m_IPv4; IPv6Address m_IPv6; @@ -450,7 +520,7 @@ namespace pcpp // implementation of inline methods - bool IPAddress::operator==(const IPAddress &rhs) const + bool IPAddress::operator==(const IPAddress& rhs) const { if (isIPv4()) return rhs.isIPv4() ? (m_IPv4 == rhs.m_IPv4) : false; @@ -458,7 +528,7 @@ namespace pcpp return rhs.isIPv6() ? m_IPv6 == rhs.m_IPv6 : false; } - bool IPAddress::operator<(const IPAddress &rhs) const + bool IPAddress::operator<(const IPAddress& rhs) const { if (isIPv4()) { @@ -469,14 +539,14 @@ namespace pcpp return rhs.isIPv6() ? m_IPv6 < rhs.m_IPv6 : false; } - IPAddress &IPAddress::operator=(const IPv4Address &addr) + IPAddress& IPAddress::operator=(const IPv4Address& addr) { m_Type = IPv4AddressType; m_IPv4 = addr; return *this; } - IPAddress &IPAddress::operator=(const IPv6Address &addr) + IPAddress& IPAddress::operator=(const IPv6Address& addr) { m_Type = IPv6AddressType; m_IPv6 = addr; @@ -489,14 +559,16 @@ namespace pcpp */ class IPv4Network { - public: + public: /** * A constructor that creates an instance of the class out of an address and a full prefix length, * essentially making a network of consisting of only 1 address. * * @param address An address representing the network prefix. */ - explicit IPv4Network(const IPv4Address &address) : IPv4Network(address, 32u) {} + explicit IPv4Network(const IPv4Address& address) : IPv4Network(address, 32u) + { + } /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -506,7 +578,7 @@ namespace pcpp * @param prefixLen A number between 0 and 32 representing the prefix length. * @throws std::invalid_argument Prefix length is out of acceptable range. */ - IPv4Network(const IPv4Address &address, uint8_t prefixLen); + IPv4Network(const IPv4Address& address, uint8_t prefixLen); /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -518,7 +590,7 @@ namespace pcpp * starting with zeros that is valid is 0.0.0.0. * @throws std::invalid_argument The provided netmask is invalid. */ - IPv4Network(const IPv4Address &address, const std::string &netmask); + IPv4Network(const IPv4Address& address, const std::string& netmask); /** * A constructor that creates an instance of the class out of a string representing the network prefix and @@ -530,7 +602,7 @@ namespace pcpp * a valid netmask * @throws std::invalid_argument The provided string does not represent a valid address and netmask format. */ - IPv4Network(const std::string &addressAndNetmask); + IPv4Network(const std::string& addressAndNetmask); /** * @return The prefix length, for example: the prefix length of 10.10.10.10/255.0.0.0 is 8 @@ -540,12 +612,18 @@ namespace pcpp /** * @return The netmask, for example: the netmask of 10.10.10.10/8 is 255.0.0.0 */ - std::string getNetmask() const { return IPv4Address(m_Mask).toString(); } + std::string getNetmask() const + { + return IPv4Address(m_Mask).toString(); + } /** * @return The network prefix, for example: the network prefix of 10.10.10.10/16 is 10.10.0.0 */ - IPv4Address getNetworkPrefix() const { return IPv4Address(m_NetworkPrefix); } + IPv4Address getNetworkPrefix() const + { + return IPv4Address(m_NetworkPrefix); + } /** * @return The lowest non-reserved IPv4 address in this network, for example: the lowest address @@ -569,14 +647,14 @@ namespace pcpp * @param address An IPv4 address * @return True is the address belongs to the network, false otherwise or if the address isn't valid */ - bool includes(const IPv4Address &address) const; + bool includes(const IPv4Address& address) const; /** * @param network An IPv4 network * @return True is the input network is completely included within this network, false otherwise, for example: * 10.10.10.10/16 includes 10.10.10.10/24 but doesn't include 10.10.10.10/8 */ - bool includes(const IPv4Network &network) const; + bool includes(const IPv4Network& network) const; /** * @return A string representation of the network in a format of NETWORK_PREFIX/PREFIX_LEN, for example: @@ -584,13 +662,13 @@ namespace pcpp */ std::string toString() const; - private: + private: uint32_t m_NetworkPrefix; uint32_t m_Mask; - bool isValidNetmask(const IPv4Address &netmaskAddress); - void initFromAddressAndPrefixLength(const IPv4Address &address, uint8_t prefixLen); - void initFromAddressAndNetmask(const IPv4Address &address, const IPv4Address &netmaskAddress); + bool isValidNetmask(const IPv4Address& netmaskAddress); + void initFromAddressAndPrefixLength(const IPv4Address& address, uint8_t prefixLen); + void initFromAddressAndNetmask(const IPv4Address& address, const IPv4Address& netmaskAddress); }; /** @@ -599,14 +677,16 @@ namespace pcpp */ class IPv6Network { - public: + public: /** * A constructor that creates an instance of the class out of an address and a full prefix length, * essentially making a network of consisting of only 1 address. * * @param address An address representing the network prefix. */ - explicit IPv6Network(const IPv6Address &address) : IPv6Network(address, 128u) {} + explicit IPv6Network(const IPv6Address& address) : IPv6Network(address, 128u) + { + } /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -616,7 +696,7 @@ namespace pcpp * @param prefixLen A number between 0 and 128 representing the prefix length. * @throws std::invalid_argument Prefix length is out of acceptable range. */ - IPv6Network(const IPv6Address &address, uint8_t prefixLen); + IPv6Network(const IPv6Address& address, uint8_t prefixLen); /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -628,7 +708,7 @@ namespace pcpp * starting with zeros that is valid is all zeros (::). * @throws std::invalid_argument The provided netmask is invalid. */ - IPv6Network(const IPv6Address &address, const std::string &netmask); + IPv6Network(const IPv6Address& address, const std::string& netmask); /** * A constructor that creates an instance of the class out of a string representing the network prefix and @@ -640,7 +720,7 @@ namespace pcpp * and IPV6_NETMASK is a valid IPv6 netmask * @throws std::invalid_argument The provided string does not represent a valid address and netmask format. */ - IPv6Network(const std::string &addressAndNetmask); + IPv6Network(const std::string& addressAndNetmask); /** * @return The prefix length, for example: the prefix length of 3546::/ffff:: is 16 @@ -650,12 +730,18 @@ namespace pcpp /** * @return The netmask, for example: the netmask of 3546::/16 is ffff:: */ - std::string getNetmask() const { return IPv6Address(m_Mask).toString(); } + std::string getNetmask() const + { + return IPv6Address(m_Mask).toString(); + } /** * @return The network prefix, for example: the network prefix of 3546:f321::/16 is 3546:: */ - IPv6Address getNetworkPrefix() const { return IPv6Address(m_NetworkPrefix); } + IPv6Address getNetworkPrefix() const + { + return IPv6Address(m_NetworkPrefix); + } /** * @return The lowest non-reserved IPv6 address in this network, for example: the lowest address in 3546::/16 is @@ -679,14 +765,14 @@ namespace pcpp * @param address An IPv6 address * @return True is the address belongs to the network, false otherwise or if the address isn't valid */ - bool includes(const IPv6Address &address) const; + bool includes(const IPv6Address& address) const; /** * @param network An IPv6 network * @return True is the input network is completely included within this network, false otherwise, for example: * 3546::/64 includes 3546::/120 but doesn't include 3546::/16 */ - bool includes(const IPv6Network &network) const; + bool includes(const IPv6Network& network) const; /** * @return A string representation of the network in a format of NETWORK_PREFIX/PREFIX_LEN, for example: @@ -694,13 +780,13 @@ namespace pcpp */ std::string toString() const; - private: + private: uint8_t m_NetworkPrefix[16]; uint8_t m_Mask[16]; - bool isValidNetmask(const IPv6Address &netmaskAddress); - void initFromAddressAndPrefixLength(const IPv6Address &address, uint8_t prefixLen); - void initFromAddressAndNetmask(const IPv6Address &address, const IPv6Address &netmaskAddress); + bool isValidNetmask(const IPv6Address& netmaskAddress); + void initFromAddressAndPrefixLength(const IPv6Address& address, uint8_t prefixLen); + void initFromAddressAndNetmask(const IPv6Address& address, const IPv6Address& netmaskAddress); }; /** @@ -709,14 +795,16 @@ namespace pcpp */ class IPNetwork { - public: + public: /** * A constructor that creates an instance of the class out of an IP address and a full prefix length, * essentially making a network of consisting of only 1 address. * * @param address An address representing the network prefix. */ - explicit IPNetwork(const IPAddress &address) : IPNetwork(address, address.isIPv4() ? 32u : 128u) {} + explicit IPNetwork(const IPAddress& address) : IPNetwork(address, address.isIPv4() ? 32u : 128u) + { + } /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -727,7 +815,7 @@ namespace pcpp * 128 for IPv6 networks. * @throws std::invalid_argument Prefix length is out of acceptable range. */ - IPNetwork(const IPAddress &address, uint8_t prefixLen) + IPNetwork(const IPAddress& address, uint8_t prefixLen) { if (address.isIPv4()) { @@ -750,7 +838,7 @@ namespace pcpp * The only netmask starting with zeros that is valid is all zeros (:: or 0.0.0.0). * @throws std::invalid_argument The provided netmask is invalid. */ - IPNetwork(const IPAddress &address, const std::string &netmask) + IPNetwork(const IPAddress& address, const std::string& netmask) { if (address.isIPv4()) { @@ -772,13 +860,13 @@ namespace pcpp * is a valid netmask for this type of network (IPv4 or IPv6 network) * @throws std::invalid_argument The provided string does not represent a valid address and netmask format. */ - IPNetwork(const std::string &addressAndNetmask) + IPNetwork(const std::string& addressAndNetmask) { try { m_IPv4Network = std::unique_ptr(new IPv4Network(addressAndNetmask)); } - catch (const std::invalid_argument &) + catch (const std::invalid_argument&) { m_IPv6Network = std::unique_ptr(new IPv6Network(addressAndNetmask)); } @@ -788,7 +876,7 @@ namespace pcpp * A copy c'tor for this class * @param other The instance to copy from */ - IPNetwork(const IPNetwork &other) + IPNetwork(const IPNetwork& other) { if (other.m_IPv4Network) { @@ -806,7 +894,7 @@ namespace pcpp * @param[in] other An instance of IPNetwork to assign * @return A reference to the assignee */ - IPNetwork &operator=(const IPNetwork &other) + IPNetwork& operator=(const IPNetwork& other) { if (other.isIPv4Network()) { @@ -823,7 +911,7 @@ namespace pcpp * @param[in] other An instance of IPv4Network to assign * @return A reference to the assignee */ - IPNetwork &operator=(const IPv4Network &other) + IPNetwork& operator=(const IPv4Network& other) { if (m_IPv4Network) { @@ -845,7 +933,7 @@ namespace pcpp * @param[in] other An instance of IPv6Network to assign * @return A reference to the assignee */ - IPNetwork &operator=(const IPv6Network &other) + IPNetwork& operator=(const IPv6Network& other) { if (m_IPv4Network) { @@ -924,18 +1012,24 @@ namespace pcpp /** * @return True if this is an IPv4 network, false otherwise */ - bool isIPv4Network() const { return m_IPv4Network != nullptr; } + bool isIPv4Network() const + { + return m_IPv4Network != nullptr; + } /** * @return True if this is an IPv6 network, false otherwise */ - bool isIPv6Network() const { return m_IPv6Network != nullptr; } + bool isIPv6Network() const + { + return m_IPv6Network != nullptr; + } /** * @param address An IP address * @return True is the address belongs to the network, false otherwise or if the address isn't valid */ - bool includes(const IPAddress &address) const + bool includes(const IPAddress& address) const { if (m_IPv4Network != nullptr) { @@ -961,7 +1055,7 @@ namespace pcpp * @param network An IP network * @return True is the input network is completely included within this network, false otherwise */ - bool includes(const IPNetwork &network) const + bool includes(const IPNetwork& network) const { if (m_IPv4Network != nullptr) { @@ -992,43 +1086,43 @@ namespace pcpp return (m_IPv4Network != nullptr ? m_IPv4Network->toString() : m_IPv6Network->toString()); } - private: + private: std::unique_ptr m_IPv4Network; std::unique_ptr m_IPv6Network; }; -} // namespace pcpp +} // namespace pcpp -inline std::ostream &operator<<(std::ostream &os, const pcpp::IPv4Address &ipv4Address) +inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv4Address& ipv4Address) { os << ipv4Address.toString(); return os; } -inline std::ostream &operator<<(std::ostream &os, const pcpp::IPv6Address &ipv6Address) +inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv6Address& ipv6Address) { os << ipv6Address.toString(); return os; } -inline std::ostream &operator<<(std::ostream &os, const pcpp::IPAddress &ipAddress) +inline std::ostream& operator<<(std::ostream& os, const pcpp::IPAddress& ipAddress) { os << ipAddress.toString(); return os; } -inline std::ostream &operator<<(std::ostream &os, const pcpp::IPv4Network &network) +inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv4Network& network) { os << network.toString(); return os; } -inline std::ostream &operator<<(std::ostream &os, const pcpp::IPv6Network &network) +inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv6Network& network) { os << network.toString(); return os; } -inline std::ostream &operator<<(std::ostream &os, const pcpp::IPNetwork &network) +inline std::ostream& operator<<(std::ostream& os, const pcpp::IPNetwork& network) { os << network.toString(); return os; diff --git a/Common++/header/IpAddressUtils.h b/Common++/header/IpAddressUtils.h index c881779016..a7b6ac7041 100644 --- a/Common++/header/IpAddressUtils.h +++ b/Common++/header/IpAddressUtils.h @@ -21,83 +21,119 @@ namespace pcpp * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPv4Address &lhs, const in_addr &rhs); + bool operator==(const IPv4Address& lhs, const in_addr& rhs); /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const IPv4Address &lhs, const in_addr &rhs) { return !(lhs == rhs); } + inline bool operator!=(const IPv4Address& lhs, const in_addr& rhs) + { + return !(lhs == rhs); + } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - inline bool operator==(const in_addr &lhs, const IPv4Address &rhs) { return rhs == lhs; } + inline bool operator==(const in_addr& lhs, const IPv4Address& rhs) + { + return rhs == lhs; + } /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const in_addr &lhs, const IPv4Address &rhs) { return !(lhs == rhs); } + inline bool operator!=(const in_addr& lhs, const IPv4Address& rhs) + { + return !(lhs == rhs); + } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPv6Address &lhs, const in6_addr &rhs); + bool operator==(const IPv6Address& lhs, const in6_addr& rhs); /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const IPv6Address &lhs, const in6_addr &rhs) { return !(lhs == rhs); } + inline bool operator!=(const IPv6Address& lhs, const in6_addr& rhs) + { + return !(lhs == rhs); + } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - inline bool operator==(const in6_addr &lhs, const IPv6Address &rhs) { return rhs == lhs; } + inline bool operator==(const in6_addr& lhs, const IPv6Address& rhs) + { + return rhs == lhs; + } /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const in6_addr &lhs, const IPv6Address &rhs) { return !(lhs == rhs); } + inline bool operator!=(const in6_addr& lhs, const IPv6Address& rhs) + { + return !(lhs == rhs); + } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPAddress &lhs, const in_addr &rhs); + bool operator==(const IPAddress& lhs, const in_addr& rhs); /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const IPAddress &lhs, const in_addr &rhs) { return !(lhs == rhs); } + inline bool operator!=(const IPAddress& lhs, const in_addr& rhs) + { + return !(lhs == rhs); + } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - inline bool operator==(const in_addr &lhs, const IPAddress &rhs) { return rhs == lhs; } + inline bool operator==(const in_addr& lhs, const IPAddress& rhs) + { + return rhs == lhs; + } /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const in_addr &lhs, const IPAddress &rhs) { return !(lhs == rhs); } + inline bool operator!=(const in_addr& lhs, const IPAddress& rhs) + { + return !(lhs == rhs); + } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - bool operator==(const IPAddress &lhs, const in6_addr &rhs); + bool operator==(const IPAddress& lhs, const in6_addr& rhs); /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const IPAddress &lhs, const in6_addr &rhs) { return !(lhs == rhs); } + inline bool operator!=(const IPAddress& lhs, const in6_addr& rhs) + { + return !(lhs == rhs); + } /** * Overload of the equal-to operator * @return True if the addresses are equal, false otherwise */ - inline bool operator==(const in6_addr &lhs, const IPAddress &rhs) { return rhs == lhs; } + inline bool operator==(const in6_addr& lhs, const IPAddress& rhs) + { + return rhs == lhs; + } /** * Overload of the not-equal-to operator * @return True if the addresses differ, false otherwise */ - inline bool operator!=(const in6_addr &lhs, const IPAddress &rhs) { return !(lhs == rhs); } -} // namespace pcpp + inline bool operator!=(const in6_addr& lhs, const IPAddress& rhs) + { + return !(lhs == rhs); + } +} // namespace pcpp diff --git a/Common++/header/IpUtils.h b/Common++/header/IpUtils.h index de829340aa..319e73cfee 100644 --- a/Common++/header/IpUtils.h +++ b/Common++/header/IpUtils.h @@ -33,7 +33,7 @@ * @param[in] size 'dst' Maximum size * @return pointer to presentation format address ('dst'), or NULL (see errno). */ -const char *inet_ntop(int af, const void *src, char *dst, size_t size); +const char* inet_ntop(int af, const void* src, char* dst, size_t size); /** * Convert from presentation format (which usually means ASCII printable) @@ -46,7 +46,7 @@ const char *inet_ntop(int af, const void *src, char *dst, size_t size); * 0 if the address wasn't valid ('dst' is untouched in this case); * -1 if some other error occurred ('dst' is untouched in this case, too) */ -int inet_pton(int af, const char *src, void *dst); +int inet_pton(int af, const char* src, void* dst); #endif /** @@ -63,14 +63,14 @@ namespace pcpp * @return Address in in_addr format * @throws std::invalid_argument Sockaddr family is not AF_INET or sockaddr is nullptr. */ - in_addr *sockaddr2in_addr(sockaddr *sa); + in_addr* sockaddr2in_addr(sockaddr* sa); /** * Attempt to extract IPv4 address from sockaddr * @param[in] sa - input sockaddr * @return Pointer to address in in_addr format or nullptr if extraction fails. */ - in_addr *try_sockaddr2in_addr(sockaddr *sa); + in_addr* try_sockaddr2in_addr(sockaddr* sa); /** * Extract IPv6 address from sockaddr @@ -78,14 +78,14 @@ namespace pcpp * @return Address in in6_addr format * @throws std::invalid_argument Sockaddr family is not AF_INET6 or sockaddr is nullptr. */ - in6_addr *sockaddr2in6_addr(sockaddr *sa); + in6_addr* sockaddr2in6_addr(sockaddr* sa); /** * Attempt to extract IPv6 address from sockaddr * @param[in] sa - input sockaddr * @return Pointer to address in in6_addr format or nullptr if extraction fails. */ - in6_addr *try_sockaddr2in6_addr(sockaddr *sa); + in6_addr* try_sockaddr2in6_addr(sockaddr* sa); /** * Converts a sockaddr format address to its string representation @@ -95,7 +95,7 @@ namespace pcpp * @throws std::invalid_argument Sockaddr family is not AF_INET or AF_INET6, sockaddr is nullptr or the result * str buffer is insufficient. */ - void sockaddr2string(sockaddr const *sa, char *resultString, size_t resultBufLen); + void sockaddr2string(sockaddr const* sa, char* resultString, size_t resultBufLen); /** * Convert a in_addr format address to 32bit representation @@ -103,5 +103,5 @@ namespace pcpp * @return Address in 32bit format */ uint32_t in_addr2int(in_addr inAddr); - } // namespace internal -} // namespace pcpp + } // namespace internal +} // namespace pcpp diff --git a/Common++/header/LRUList.h b/Common++/header/LRUList.h index 7ddaf1948e..27172114c8 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -25,7 +25,7 @@ namespace pcpp */ template class LRUList { - public: + public: typedef typename std::list::iterator ListIterator; typedef typename std::unordered_map::iterator MapIterator; @@ -33,7 +33,10 @@ namespace pcpp * A c'tor for this class * @param[in] maxSize The max size this list can go */ - explicit LRUList(size_t maxSize) { m_MaxSize = maxSize; } + explicit LRUList(size_t maxSize) + { + m_MaxSize = maxSize; + } /** * Puts an element in the list. This element will be inserted (or advanced if it already exists) to the head of @@ -46,7 +49,7 @@ namespace pcpp * and deletedValue is not NULL the value of deleted element is copied into the place the deletedValue points * to. */ - int put(const T &element, T *deletedValue = NULL) + int put(const T& element, T* deletedValue = NULL) { m_CacheItemsList.push_front(element); @@ -54,7 +57,7 @@ namespace pcpp // iterator to the element that prevented the insertion std::pair pair = m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin())); - if (pair.second == false) // already exists + if (pair.second == false) // already exists { m_CacheItemsList.erase(pair.first->second); pair.first->second = m_CacheItemsList.begin(); @@ -83,19 +86,25 @@ namespace pcpp * Get the most recently used element (the one at the beginning of the list) * @return The most recently used element */ - const T &getMRUElement() const { return m_CacheItemsList.front(); } + const T& getMRUElement() const + { + return m_CacheItemsList.front(); + } /** * Get the least recently used element (the one at the end of the list) * @return The least recently used element */ - const T &getLRUElement() const { return m_CacheItemsList.back(); } + const T& getLRUElement() const + { + return m_CacheItemsList.back(); + } /** * Erase an element from the list. If element isn't found in the list nothing happens * @param[in] element The element to erase */ - void eraseElement(const T &element) + void eraseElement(const T& element) { MapIterator iter = m_CacheItemsMap.find(element); if (iter == m_CacheItemsMap.end()) @@ -108,17 +117,23 @@ namespace pcpp /** * @return The max size of this list as determined in the c'tor */ - size_t getMaxSize() const { return m_MaxSize; } + size_t getMaxSize() const + { + return m_MaxSize; + } /** * @return The number of elements currently in this list */ - size_t getSize() const { return m_CacheItemsMap.size(); } + size_t getSize() const + { + return m_CacheItemsMap.size(); + } - private: + private: std::list m_CacheItemsList; std::unordered_map m_CacheItemsMap; size_t m_MaxSize; }; -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/header/Logger.h b/Common++/header/Logger.h index 7dcb73908b..145a85a13d 100644 --- a/Common++/header/Logger.h +++ b/Common++/header/Logger.h @@ -20,7 +20,7 @@ #define PCPP_LOG(level, message) \ do \ { \ - std::ostringstream *sstream = pcpp::Logger::getInstance().internalCreateLogStream(); \ + std::ostringstream* sstream = pcpp::Logger::getInstance().internalCreateLogStream(); \ (*sstream) << message; \ pcpp::Logger::getInstance().internalPrintLogMessage(sstream, level, PCAPPP_FILENAME, __FUNCTION__, __LINE__); \ } while (0) @@ -55,64 +55,64 @@ namespace pcpp enum LogModule { UndefinedLogModule, - CommonLogModuleIpUtils, ///< IP Utils module (Common++) - CommonLogModuleTablePrinter, ///< Table printer module (Common++) - CommonLogModuleGenericUtils, ///< Generic Utils (Common++) - PacketLogModuleRawPacket, ///< RawPacket module (Packet++) - PacketLogModulePacket, ///< Packet module (Packet++) - PacketLogModuleLayer, ///< Layer module (Packet++) - PacketLogModuleAsn1Codec, ///< Asn1Codec module (Packet++) - PacketLogModuleArpLayer, ///< ArpLayer module (Packet++) - PacketLogModuleEthLayer, ///< EthLayer module (Packet++) - PacketLogModuleIPv4Layer, ///< IPv4Layer module (Packet++) - PacketLogModuleIPv6Layer, ///< IPv6Layer module (Packet++) - PacketLogModulePayloadLayer, ///< PayloadLayer module (Packet++) - PacketLogModuleTcpLayer, ///< TcpLayer module (Packet++) - PacketLogModuleUdpLayer, ///< UdpLayer module (Packet++) - PacketLogModuleVlanLayer, ///< VlanLayer module (Packet++) - PacketLogModuleHttpLayer, ///< HttpLayer module (Packet++) - PacketLogModulePPPoELayer, ///< PPPoELayer module (Packet++) - PacketLogModuleDnsLayer, ///< DnsLayer module (Packet++) - PacketLogModuleMplsLayer, ///< MplsLayer module (Packet++) - PacketLogModuleIcmpLayer, ///< IcmpLayer module (Packet++) - PacketLogModuleIcmpV6Layer, ///< IcmpV6Layer module (Packet++) - PacketLogModuleGreLayer, ///< GreLayer module (Packet++) - PacketLogModuleSSLLayer, ///< SSLLayer module (Packet++) - PacketLogModuleSllLayer, ///< SllLayer module (Packet++) - PacketLogModuleNflogLayer, ///< NflogLayer module (Packet++) - PacketLogModuleDhcpLayer, ///< DhcpLayer module (Packet++) - PacketLogModuleDhcpV6Layer, ///< DhcpV6Layer module (Packet++) - PacketLogModuleIgmpLayer, ///< IgmpLayer module (Packet++) - PacketLogModuleSipLayer, ///< SipLayer module (Packet++) - PacketLogModuleSdpLayer, ///< SdpLayer module (Packet++) - PacketLogModuleRadiusLayer, ///< RadiusLayer module (Packet++) - PacketLogModuleGtpLayer, ///< GtpLayer module (Packet++) - PacketLogModuleBgpLayer, ///< GtpLayer module (Packet++) - PacketLogModuleSSHLayer, ///< SSHLayer module (Packet++) - PacketLogModuleVrrpLayer, ///< Vrrp Record module (Packet++) - PacketLogModuleTcpReassembly, ///< TcpReassembly module (Packet++) - PacketLogModuleIPReassembly, ///< IPReassembly module (Packet++) - PacketLogModuleIPSecLayer, ///< IPSecLayers module (Packet++) - PacketLogModuleNtpLayer, ///< NtpLayer module (Packet++) - PacketLogModuleTelnetLayer, ///< TelnetLayer module (Packet++) - PacketLogModuleStpLayer, ///< StpLayer module (Packet++) - PacketLogModuleLLCLayer, ///< LLCLayer module (Packet++) - PacketLogModuleNdpLayer, ///< NdpLayer module (Packet++) - PacketLogModuleFtpLayer, ///< FtpLayer module (Packet++) - PacketLogModuleSomeIpLayer, ///< SomeIpLayer module (Packet++) - PacketLogModuleSomeIpSdLayer, ///< SomeIpSdLayer module (Packet++) - PacketLogModuleWakeOnLanLayer, ///< WakeOnLanLayer module (Packet++) - PacketLogModuleSmtpLayer, ///< SmtpLayer module (Packet++) - PcapLogModuleWinPcapLiveDevice, ///< WinPcapLiveDevice module (Pcap++) - PcapLogModuleRemoteDevice, ///< WinPcapRemoteDevice module (Pcap++) - PcapLogModuleLiveDevice, ///< PcapLiveDevice module (Pcap++) - PcapLogModuleFileDevice, ///< FileDevice module (Pcap++) - PcapLogModulePfRingDevice, ///< PfRingDevice module (Pcap++) - PcapLogModuleMBufRawPacket, ///< MBufRawPacket module (Pcap++) - PcapLogModuleDpdkDevice, ///< DpdkDevice module (Pcap++) - PcapLogModuleKniDevice, ///< KniDevice module (Pcap++) - PcapLogModuleXdpDevice, ///< XdpDevice module (Pcap++) - NetworkUtils, ///< NetworkUtils module (Pcap++) + CommonLogModuleIpUtils, ///< IP Utils module (Common++) + CommonLogModuleTablePrinter, ///< Table printer module (Common++) + CommonLogModuleGenericUtils, ///< Generic Utils (Common++) + PacketLogModuleRawPacket, ///< RawPacket module (Packet++) + PacketLogModulePacket, ///< Packet module (Packet++) + PacketLogModuleLayer, ///< Layer module (Packet++) + PacketLogModuleAsn1Codec, ///< Asn1Codec module (Packet++) + PacketLogModuleArpLayer, ///< ArpLayer module (Packet++) + PacketLogModuleEthLayer, ///< EthLayer module (Packet++) + PacketLogModuleIPv4Layer, ///< IPv4Layer module (Packet++) + PacketLogModuleIPv6Layer, ///< IPv6Layer module (Packet++) + PacketLogModulePayloadLayer, ///< PayloadLayer module (Packet++) + PacketLogModuleTcpLayer, ///< TcpLayer module (Packet++) + PacketLogModuleUdpLayer, ///< UdpLayer module (Packet++) + PacketLogModuleVlanLayer, ///< VlanLayer module (Packet++) + PacketLogModuleHttpLayer, ///< HttpLayer module (Packet++) + PacketLogModulePPPoELayer, ///< PPPoELayer module (Packet++) + PacketLogModuleDnsLayer, ///< DnsLayer module (Packet++) + PacketLogModuleMplsLayer, ///< MplsLayer module (Packet++) + PacketLogModuleIcmpLayer, ///< IcmpLayer module (Packet++) + PacketLogModuleIcmpV6Layer, ///< IcmpV6Layer module (Packet++) + PacketLogModuleGreLayer, ///< GreLayer module (Packet++) + PacketLogModuleSSLLayer, ///< SSLLayer module (Packet++) + PacketLogModuleSllLayer, ///< SllLayer module (Packet++) + PacketLogModuleNflogLayer, ///< NflogLayer module (Packet++) + PacketLogModuleDhcpLayer, ///< DhcpLayer module (Packet++) + PacketLogModuleDhcpV6Layer, ///< DhcpV6Layer module (Packet++) + PacketLogModuleIgmpLayer, ///< IgmpLayer module (Packet++) + PacketLogModuleSipLayer, ///< SipLayer module (Packet++) + PacketLogModuleSdpLayer, ///< SdpLayer module (Packet++) + PacketLogModuleRadiusLayer, ///< RadiusLayer module (Packet++) + PacketLogModuleGtpLayer, ///< GtpLayer module (Packet++) + PacketLogModuleBgpLayer, ///< GtpLayer module (Packet++) + PacketLogModuleSSHLayer, ///< SSHLayer module (Packet++) + PacketLogModuleVrrpLayer, ///< Vrrp Record module (Packet++) + PacketLogModuleTcpReassembly, ///< TcpReassembly module (Packet++) + PacketLogModuleIPReassembly, ///< IPReassembly module (Packet++) + PacketLogModuleIPSecLayer, ///< IPSecLayers module (Packet++) + PacketLogModuleNtpLayer, ///< NtpLayer module (Packet++) + PacketLogModuleTelnetLayer, ///< TelnetLayer module (Packet++) + PacketLogModuleStpLayer, ///< StpLayer module (Packet++) + PacketLogModuleLLCLayer, ///< LLCLayer module (Packet++) + PacketLogModuleNdpLayer, ///< NdpLayer module (Packet++) + PacketLogModuleFtpLayer, ///< FtpLayer module (Packet++) + PacketLogModuleSomeIpLayer, ///< SomeIpLayer module (Packet++) + PacketLogModuleSomeIpSdLayer, ///< SomeIpSdLayer module (Packet++) + PacketLogModuleWakeOnLanLayer, ///< WakeOnLanLayer module (Packet++) + PacketLogModuleSmtpLayer, ///< SmtpLayer module (Packet++) + PcapLogModuleWinPcapLiveDevice, ///< WinPcapLiveDevice module (Pcap++) + PcapLogModuleRemoteDevice, ///< WinPcapRemoteDevice module (Pcap++) + PcapLogModuleLiveDevice, ///< PcapLiveDevice module (Pcap++) + PcapLogModuleFileDevice, ///< FileDevice module (Pcap++) + PcapLogModulePfRingDevice, ///< PfRingDevice module (Pcap++) + PcapLogModuleMBufRawPacket, ///< MBufRawPacket module (Pcap++) + PcapLogModuleDpdkDevice, ///< DpdkDevice module (Pcap++) + PcapLogModuleKniDevice, ///< KniDevice module (Pcap++) + PcapLogModuleXdpDevice, ///< XdpDevice module (Pcap++) + NetworkUtils, ///< NetworkUtils module (Pcap++) NumOfLogModules }; @@ -137,16 +137,16 @@ namespace pcpp */ class Logger { - public: + public: /** * An enum representing the log level. Currently 3 log levels are supported: Error, Info and Debug. Info is the * default log level */ enum LogLevel { - Error, ///< Error log level - Info, ///< Info log level - Debug ///< Debug log level + Error, ///< Error log level + Info, ///< Info log level + Debug ///< Debug log level }; /** @@ -158,8 +158,8 @@ namespace pcpp * @param[in] method The method in PcapPlusPlus code the log message is coming from * @param[in] line The line in PcapPlusPlus code the log message is coming from */ - typedef void (*LogPrinter)(LogLevel logLevel, const std::string &logMessage, const std::string &file, - const std::string &method, const int line); + typedef void (*LogPrinter)(LogLevel logLevel, const std::string& logMessage, const std::string& file, + const std::string& method, const int line); /** * A static method for converting the log level enum to a string. @@ -173,21 +173,30 @@ namespace pcpp * @param[in] module PcapPlusPlus module * @return The log level set for this module */ - LogLevel getLogLevel(LogModule module) { return m_LogModulesArray[module]; } + LogLevel getLogLevel(LogModule module) + { + return m_LogModulesArray[module]; + } /** * Set the log level for a certain PcapPlusPlus module * @param[in] module PcapPlusPlus module * @param[in] level The log level to set the module to */ - void setLogLevel(LogModule module, LogLevel level) { m_LogModulesArray[module] = level; } + void setLogLevel(LogModule module, LogLevel level) + { + m_LogModulesArray[module] = level; + } /** * Check whether a certain module is set to debug log level * @param[in] module PcapPlusPlus module * @return True if this module log level is "debug". False otherwise */ - bool isDebugEnabled(LogModule module) const { return m_LogModulesArray[module] == Debug; } + bool isDebugEnabled(LogModule module) const + { + return m_LogModulesArray[module] == Debug; + } /** * Set all PcapPlusPlus modules to a certain log level @@ -203,70 +212,88 @@ namespace pcpp * Set a custom log printer. * @param[in] printer A log printer function that will be called for every log message */ - void setLogPrinter(LogPrinter printer) { m_LogPrinter = printer; } + void setLogPrinter(LogPrinter printer) + { + m_LogPrinter = printer; + } /** * Set the log printer back to the default printer */ - void resetLogPrinter() { m_LogPrinter = &defaultLogPrinter; } + void resetLogPrinter() + { + m_LogPrinter = &defaultLogPrinter; + } /** * @return Get the last error message */ - std::string getLastError() { return m_LastError; } + std::string getLastError() + { + return m_LastError; + } /** * Suppress logs in all PcapPlusPlus modules */ - void suppressLogs() { m_LogsEnabled = false; } + void suppressLogs() + { + m_LogsEnabled = false; + } /** * Enable logs in all PcapPlusPlus modules */ - void enableLogs() { m_LogsEnabled = true; } + void enableLogs() + { + m_LogsEnabled = true; + } /** * Get an indication if logs are currently enabled. * @return True if logs are currently enabled, false otherwise */ - bool logsEnabled() const { return m_LogsEnabled; } + bool logsEnabled() const + { + return m_LogsEnabled; + } - template Logger &operator<<(const T &msg) + template Logger& operator<<(const T& msg) { (*m_LogStream) << msg; return *this; } - std::ostringstream *internalCreateLogStream(); + std::ostringstream* internalCreateLogStream(); /** * An internal method to print log messages. Shouldn't be used externally. */ - void internalPrintLogMessage(std::ostringstream *logStream, Logger::LogLevel logLevel, const char *file, - const char *method, int line); + void internalPrintLogMessage(std::ostringstream* logStream, Logger::LogLevel logLevel, const char* file, + const char* method, int line); /** * Get access to Logger singleton * @todo: make this singleton thread-safe/ * @return a pointer to the Logger singleton **/ - static Logger &getInstance() + static Logger& getInstance() { static Logger instance; return instance; } - private: + private: bool m_LogsEnabled; Logger::LogLevel m_LogModulesArray[NumOfLogModules]; LogPrinter m_LogPrinter; std::string m_LastError; - std::ostringstream *m_LogStream; + std::ostringstream* m_LogStream; // private c'tor - this class is a singleton Logger(); - static void defaultLogPrinter(LogLevel logLevel, const std::string &logMessage, const std::string &file, - const std::string &method, const int line); + static void defaultLogPrinter(LogLevel logLevel, const std::string& logMessage, const std::string& file, + const std::string& method, const int line); }; -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/header/MacAddress.h b/Common++/header/MacAddress.h index 4270501105..9a849d3df2 100644 --- a/Common++/header/MacAddress.h +++ b/Common++/header/MacAddress.h @@ -23,7 +23,7 @@ namespace pcpp */ class MacAddress { - public: + public: /** * Default constructor for this class. * Initializes the address as 00:00:00:00:00:00. @@ -36,14 +36,17 @@ namespace pcpp * If the byte array is invalid, the constructor throws an exception. * @param[in] addr A pointer to the byte array containing 6 bytes representing the MAC address */ - explicit MacAddress(const uint8_t *addr) { memcpy(m_Address, addr, sizeof(m_Address)); } + explicit MacAddress(const uint8_t* addr) + { + memcpy(m_Address, addr, sizeof(m_Address)); + } /** * A constructor that creates an instance of the class out of a std::string. * If the string doesn't represent a valid MAC address, the constructor throws an exception. * @param[in] addr the string representing the MAC address in format "00:00:00:00:00:00" */ - explicit MacAddress(const std::string &addr); + explicit MacAddress(const std::string& addr); /** * A template constructor that creates an instance of the class out of a string convertible to std::string. @@ -51,7 +54,7 @@ namespace pcpp * @param[in] addr the string representing the MAC address in format "00:00:00:00:00:00" */ template ::value>::type> - MacAddress(const T &addr) : MacAddress(static_cast(addr)){}; + MacAddress(const T& addr) : MacAddress(static_cast(addr)){}; /** * A constructor that creates an instance of 6 bytes representing the MAC address @@ -93,7 +96,7 @@ namespace pcpp * @param[in] other The object to compare with * @return True if addresses are equal, false otherwise */ - bool operator==(const MacAddress &other) const + bool operator==(const MacAddress& other) const { return memcmp(m_Address, other.m_Address, sizeof(m_Address)) == 0; } @@ -103,7 +106,10 @@ namespace pcpp * @param[in] other The object to compare with * @return True if addresses are not equal, false otherwise */ - bool operator!=(const MacAddress &other) const { return !operator==(other); } + bool operator!=(const MacAddress& other) const + { + return !operator==(other); + } /** * Overload of the assignment operator. @@ -111,7 +117,7 @@ namespace pcpp * @param[in] octets An initializer list containing the values of type uint8_t representing the MAC address, the * length of the list must be equal to 6 */ - MacAddress &operator=(std::initializer_list octets) + MacAddress& operator=(std::initializer_list octets) { if (octets.size() != sizeof(m_Address)) { @@ -126,7 +132,10 @@ namespace pcpp * Returns the pointer to raw data * @return The pointer to raw data */ - const uint8_t *getRawData() const { return m_Address; } + const uint8_t* getRawData() const + { + return m_Address; + } /** * Returns a std::string representation of the address @@ -139,7 +148,7 @@ namespace pcpp * responsibility * @param[in] arr A pointer to where array will be allocated */ - void copyTo(uint8_t **arr) const + void copyTo(uint8_t** arr) const { *arr = new uint8_t[sizeof(m_Address)]; memcpy(*arr, m_Address, sizeof(m_Address)); @@ -150,19 +159,22 @@ namespace pcpp * This method assumes array allocated size is at least 6 (the size of a MAC address) * @param[in] arr A pointer to the array which address will be copied to */ - void copyTo(uint8_t *arr) const { memcpy(arr, m_Address, sizeof(m_Address)); } + void copyTo(uint8_t* arr) const + { + memcpy(arr, m_Address, sizeof(m_Address)); + } /** * A static value representing a zero value of MAC address, meaning address of value "00:00:00:00:00:00" */ static MacAddress Zero; - private: + private: uint8_t m_Address[6] = {0}; }; -} // namespace pcpp +} // namespace pcpp -inline std::ostream &operator<<(std::ostream &os, const pcpp::MacAddress &macAddress) +inline std::ostream& operator<<(std::ostream& os, const pcpp::MacAddress& macAddress) { os << macAddress.toString(); return os; diff --git a/Common++/header/OUILookup.h b/Common++/header/OUILookup.h index 7c5bc7af6a..50f49b1c1d 100644 --- a/Common++/header/OUILookup.h +++ b/Common++/header/OUILookup.h @@ -23,7 +23,7 @@ namespace pcpp */ class OUILookup { - private: + private: /** * MAC addresses with mask values. For example for a MAC address "XX:XX:XX:XX:X0:00/36" the first element will * be 36, and the second element will be unsigned integer equivalent of "XX:XX:XX:XX:X0:00" and vendor name. @@ -50,22 +50,22 @@ namespace pcpp /// Internal vendor list for MAC addresses OUIVendorMap vendorMap; - template int64_t internalParser(T &jsonData); + template int64_t internalParser(T& jsonData); - public: + public: /** * Initialise internal OUI database from a JSON file * @param[in] path Path to OUI database. The database itself is located at * 3rdParty/OUILookup/PCPP_OUIDatabase.json * @return Returns the number of total vendors, negative on errors */ - int64_t initOUIDatabaseFromJson(const std::string &path = ""); + int64_t initOUIDatabaseFromJson(const std::string& path = ""); /** * Returns the vendor of the MAC address. OUI database should be initialized with initOUIDatabaseFromJson() * @param[in] addr MAC address to search * @return Vendor name */ - std::string getVendorName(const pcpp::MacAddress &addr); + std::string getVendorName(const pcpp::MacAddress& addr); }; -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/header/PcapPlusPlusVersion.h b/Common++/header/PcapPlusPlusVersion.h index 58848dd3d5..22edfc4a97 100644 --- a/Common++/header/PcapPlusPlusVersion.h +++ b/Common++/header/PcapPlusPlusVersion.h @@ -20,18 +20,27 @@ namespace pcpp * GitHub) the version will end with a '+'. For example: '23.09+' means non-official release but '23.09' means * official release */ - inline std::string getPcapPlusPlusVersion() { return PCAPPLUSPLUS_VERSION; } + inline std::string getPcapPlusPlusVersion() + { + return PCAPPLUSPLUS_VERSION; + } /** * @return PcapPlusPlus long version string which includes the version and info whether it's an official or * non-official release. For example: "v23.09+ (non-official release)" or "v23.09 (official release)" */ - inline std::string getPcapPlusPlusVersionFull() { return PCAPPLUSPLUS_VERSION_FULL; } + inline std::string getPcapPlusPlusVersionFull() + { + return PCAPPLUSPLUS_VERSION_FULL; + } /** * @return The build date and time in a format of "Mmm dd yyyy hh:mm:ss" */ - inline std::string getBuildDateTime() { return std::string(__DATE__) + " " + std::string(__TIME__); } + inline std::string getBuildDateTime() + { + return std::string(__DATE__) + " " + std::string(__TIME__); + } /** * @return The Git commit (revision) the binaries are built from @@ -49,4 +58,4 @@ namespace pcpp */ std::string getGitInfo(); -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/header/PointerVector.h b/Common++/header/PointerVector.h index 7e3159d404..1bd12273df 100644 --- a/Common++/header/PointerVector.h +++ b/Common++/header/PointerVector.h @@ -22,21 +22,23 @@ namespace pcpp */ template class PointerVector { - public: + public: /** * Iterator object that is used for iterating all elements in the vector */ - typedef typename std::vector::iterator VectorIterator; + typedef typename std::vector::iterator VectorIterator; /** * Const iterator object that is used for iterating all elements in a constant vector */ - typedef typename std::vector::const_iterator ConstVectorIterator; + typedef typename std::vector::const_iterator ConstVectorIterator; /** * A constructor that create an empty instance of this object */ - PointerVector() {} + PointerVector() + { + } /** * A destructor for this class. The destructor frees all elements that are binded to the vector @@ -54,25 +56,25 @@ namespace pcpp * meaning the new vector will contain pointers to copied elements, not pointers to the elements of the original * vector */ - PointerVector(const PointerVector &other) + PointerVector(const PointerVector& other) { try { for (const auto iter : other) { - T *objCopy = new T(*iter); + T* objCopy = new T(*iter); try { m_Vector.push_back(objCopy); } - catch (const std::exception &) + catch (const std::exception&) { delete objCopy; throw; } } } - catch (const std::exception &) + catch (const std::exception&) { for (auto obj : m_Vector) { @@ -98,31 +100,46 @@ namespace pcpp /** * Add a new (pointer to an) element to the vector */ - void pushBack(T *element) { m_Vector.push_back(element); } + void pushBack(T* element) + { + m_Vector.push_back(element); + } /** * Get the first element of the vector * @return An iterator object pointing to the first element of the vector */ - VectorIterator begin() { return m_Vector.begin(); } + VectorIterator begin() + { + return m_Vector.begin(); + } /** * Get the first element of a constant vector * @return A const iterator object pointing to the first element of the vector */ - ConstVectorIterator begin() const { return m_Vector.begin(); } + ConstVectorIterator begin() const + { + return m_Vector.begin(); + } /** * Get the last element of the vector * @return An iterator object pointing to the last element of the vector */ - VectorIterator end() { return m_Vector.end(); } + VectorIterator end() + { + return m_Vector.end(); + } /** * Get the last element of a constant vector * @return A const iterator object pointing to the last element of the vector */ - ConstVectorIterator end() const { return m_Vector.end(); } + ConstVectorIterator end() const + { + return m_Vector.end(); + } // inline size_t size() { return m_Vector.size(); } @@ -130,18 +147,27 @@ namespace pcpp * Get number of elements in the vector * @return The number of elements in the vector */ - size_t size() const { return m_Vector.size(); } + size_t size() const + { + return m_Vector.size(); + } /** * Returns a pointer of the first element in the vector * @return A pointer of the first element in the vector */ - T *front() { return m_Vector.front(); } + T* front() + { + return m_Vector.front(); + } /** * @return A pointer to the last element in the vector */ - T *back() { return m_Vector.back(); } + T* back() + { + return m_Vector.back(); + } /** * Removes from the vector a single element (position). Once the element is erased, it's also freed @@ -161,9 +187,9 @@ namespace pcpp * @return A pointer to the element which is no longer managed by the vector. It's user responsibility to free * it */ - T *getAndRemoveFromVector(VectorIterator &position) + T* getAndRemoveFromVector(VectorIterator& position) { - T *result = (*position); + T* result = (*position); VectorIterator tempPos = position; tempPos = m_Vector.erase(tempPos); position = tempPos; @@ -175,17 +201,23 @@ namespace pcpp * @param[in] index The index to retrieve the element from * @return The element at the specified position in the vector */ - T *at(int index) { return m_Vector.at(index); } + T* at(int index) + { + return m_Vector.at(index); + } /** * Return a const pointer to the element in a certain index * @param[in] index The index to retrieve the element from * @return The element at the specified position in the vector */ - const T *at(int index) const { return m_Vector.at(index); } + const T* at(int index) const + { + return m_Vector.at(index); + } - private: - std::vector m_Vector; + private: + std::vector m_Vector; }; -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/header/SystemUtils.h b/Common++/header/SystemUtils.h index 8435fbf90c..4f83c35819 100644 --- a/Common++/header/SystemUtils.h +++ b/Common++/header/SystemUtils.h @@ -9,7 +9,7 @@ #define MAX_NUM_OF_CORES 32 #ifdef _MSC_VER -int gettimeofday(struct timeval *tp, struct timezone *tzp); +int gettimeofday(struct timeval* tp, struct timezone* tzp); #endif /** @@ -42,7 +42,10 @@ namespace pcpp * Overload of the comparison operator * @return true if 2 addresses are equal. False otherwise */ - bool operator==(const SystemCore &other) const { return Id == other.Id; } + bool operator==(const SystemCore& other) const + { + return Id == other.Id; + } }; /** @@ -205,21 +208,21 @@ namespace pcpp * @param[in] cores A vector of SystemCore instances * @return A core mask representing these cores */ - CoreMask createCoreMaskFromCoreVector(const std::vector &cores); + CoreMask createCoreMaskFromCoreVector(const std::vector& cores); /** * Create a core mask from a vector of core IDs * @param[in] coreIds A vector of core IDs * @return A core mask representing these cores */ - CoreMask createCoreMaskFromCoreIds(const std::vector &coreIds); + CoreMask createCoreMaskFromCoreIds(const std::vector& coreIds); /** * Convert a core mask into a vector of its appropriate system cores * @param[in] coreMask The input core mask * @param[out] resultVec The vector that will contain the system cores */ - void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector &resultVec); + void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector& resultVec); /** * Execute a shell command and return its output @@ -227,14 +230,14 @@ namespace pcpp * @return The output of the command (both stdout and stderr) * @throws std::runtime_error Error executing the command. */ - std::string executeShellCommand(const std::string &command); + std::string executeShellCommand(const std::string& command); /** * Check if a directory exists * @param[in] dirPath Full path of the directory to search * @return True if directory exists, false otherwise */ - bool directoryExists(const std::string &dirPath); + bool directoryExists(const std::string& dirPath); /** * Retrieve a system-wide real-time accurate clock. It's actually a multi-platform version of clock_gettime() which @@ -243,7 +246,7 @@ namespace pcpp * @param[out] nsec The nanosecond portion of the time * @return 0 for success, or -1 for failure */ - int clockGetTime(long &sec, long &nsec); + int clockGetTime(long& sec, long& nsec); /** * A multi-platform version of the popular sleep method. This method simply runs the right sleep method, according @@ -295,17 +298,17 @@ namespace pcpp */ class AppName { - private: + private: static std::string m_AppName; - public: + public: /** * Static init method which should be called once at the beginning of the main method. * @param[in] argc The argc param from main() * @param[in] argv The argv param from main() */ // cppcheck-suppress constParameter - static void init(int argc, char *argv[]) + static void init(int argc, char* argv[]) { if (argc == 0) { @@ -340,7 +343,10 @@ namespace pcpp /** * @return The app name as extracted from the current running executable */ - static const std::string &get() { return m_AppName; } + static const std::string& get() + { + return m_AppName; + } }; /** @@ -350,19 +356,19 @@ namespace pcpp */ class ApplicationEventHandler { - public: + public: /** * @typedef EventHandlerCallback * The callback to be invoked when the event occurs * @param[in] cookie A pointer the the cookie provided by the user in ApplicationEventHandler c'tor */ - typedef void (*EventHandlerCallback)(void *cookie); + typedef void (*EventHandlerCallback)(void* cookie); /** * As ApplicationEventHandler is a singleton, this is the static getter to retrieve its instance * @return The singleton instance of ApplicationEventHandler */ - static ApplicationEventHandler &getInstance() + static ApplicationEventHandler& getInstance() { static ApplicationEventHandler instance; return instance; @@ -375,11 +381,11 @@ namespace pcpp * EventHandlerCallback callback. This cookie is very useful for transferring objects that give context to the * event callback */ - void onApplicationInterrupted(EventHandlerCallback handler, void *cookie); + void onApplicationInterrupted(EventHandlerCallback handler, void* cookie); - private: + private: EventHandlerCallback m_ApplicationInterruptedHandler; - void *m_ApplicationInterruptedCookie; + void* m_ApplicationInterruptedCookie; // private c'tor ApplicationEventHandler(); @@ -391,4 +397,4 @@ namespace pcpp #endif }; -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/header/TablePrinter.h b/Common++/header/TablePrinter.h index ab4dcf8f37..5f1887f187 100644 --- a/Common++/header/TablePrinter.h +++ b/Common++/header/TablePrinter.h @@ -15,7 +15,7 @@ namespace pcpp */ class TablePrinter { - public: + public: /** * C'tor - get column names and column widths * @param[in] columnNames A vector of strings containing column names @@ -37,7 +37,7 @@ namespace pcpp * @return True if row was printed successfully or false otherwise (in any case of error an appropriate message * will be printed to log) */ - bool printRow(const std::string &values, char delimiter); + bool printRow(const std::string& values, char delimiter); /** * Print a single row @@ -58,7 +58,7 @@ namespace pcpp */ void closeTable(); - private: + private: std::vector m_ColumnNames; std::vector m_ColumnWidths; bool m_FirstRow; @@ -70,4 +70,4 @@ namespace pcpp void printHeadline(); }; -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/src/GeneralUtils.cpp b/Common++/src/GeneralUtils.cpp index 13de3c5da4..51c6c50c07 100644 --- a/Common++/src/GeneralUtils.cpp +++ b/Common++/src/GeneralUtils.cpp @@ -10,7 +10,7 @@ namespace pcpp { - std::string byteArrayToHexString(const uint8_t *byteArr, size_t byteArrSize, int stringSizeLimit) + std::string byteArrayToHexString(const uint8_t* byteArr, size_t byteArrSize, int stringSizeLimit) { if (stringSizeLimit <= 0) stringSizeLimit = byteArrSize; @@ -39,7 +39,7 @@ namespace pcpp return -1; } - size_t hexStringToByteArray(const std::string &hexString, uint8_t *resultByteArr, size_t resultByteArrSize) + size_t hexStringToByteArray(const std::string& hexString, uint8_t* resultByteArr, size_t resultByteArrSize) { if (hexString.size() % 2 != 0) { @@ -68,12 +68,12 @@ namespace pcpp return hexString.length() / 2; } - char *cross_platform_memmem(const char *haystack, size_t haystackLen, const char *needle, size_t needleLen) + char* cross_platform_memmem(const char* haystack, size_t haystackLen, const char* needle, size_t needleLen) { - char *ptr = (char *)haystack; + char* ptr = (char*)haystack; while (needleLen <= (haystackLen - (ptr - haystack))) { - if (nullptr != (ptr = (char *)memchr(ptr, (int)(*needle), haystackLen - (ptr - haystack)))) + if (nullptr != (ptr = (char*)memchr(ptr, (int)(*needle), haystackLen - (ptr - haystack)))) { // check if there is room to do a memcmp if (needleLen > (haystackLen - (ptr - haystack))) @@ -93,4 +93,4 @@ namespace pcpp return nullptr; } -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/src/IpAddress.cpp b/Common++/src/IpAddress.cpp index 0602466165..f48d5673eb 100644 --- a/Common++/src/IpAddress.cpp +++ b/Common++/src/IpAddress.cpp @@ -47,7 +47,7 @@ namespace pcpp (operator<(MulticastRangeUpperBound) || operator==(MulticastRangeUpperBound)); } - IPv4Address::IPv4Address(const std::string &addrAsString) + IPv4Address::IPv4Address(const std::string& addrAsString) { if (inet_pton(AF_INET, addrAsString.data(), m_Bytes.data()) <= 0) { @@ -55,23 +55,26 @@ namespace pcpp } } - bool IPv4Address::matchNetwork(const IPv4Network &network) const { return network.includes(*this); } + bool IPv4Address::matchNetwork(const IPv4Network& network) const + { + return network.includes(*this); + } - bool IPv4Address::matchNetwork(const std::string &network) const + bool IPv4Address::matchNetwork(const std::string& network) const { try { auto ipv4Network = IPv4Network(network); return ipv4Network.includes(*this); } - catch (const std::invalid_argument &e) + catch (const std::invalid_argument& e) { PCPP_LOG_ERROR(e.what()); return false; } } - bool IPv4Address::isValidIPv4Address(const std::string &addrAsString) + bool IPv4Address::isValidIPv4Address(const std::string& addrAsString) { struct sockaddr_in sa_in; return inet_pton(AF_INET, addrAsString.data(), &(sa_in.sin_addr)) > 0; @@ -91,9 +94,12 @@ namespace pcpp return std::string(); } - bool IPv6Address::isMulticast() const { return !operator<(MulticastRangeLowerBound); } + bool IPv6Address::isMulticast() const + { + return !operator<(MulticastRangeLowerBound); + } - IPv6Address::IPv6Address(const std::string &addrAsString) + IPv6Address::IPv6Address(const std::string& addrAsString) { if (inet_pton(AF_INET6, addrAsString.data(), m_Bytes.data()) <= 0) { @@ -101,7 +107,7 @@ namespace pcpp } } - void IPv6Address::copyTo(uint8_t **arr, size_t &length) const + void IPv6Address::copyTo(uint8_t** arr, size_t& length) const { const size_t addrLen = m_Bytes.size() * sizeof(uint8_t); length = addrLen; @@ -109,23 +115,26 @@ namespace pcpp memcpy(*arr, m_Bytes.data(), addrLen); } - bool IPv6Address::matchNetwork(const IPv6Network &network) const { return network.includes(*this); } + bool IPv6Address::matchNetwork(const IPv6Network& network) const + { + return network.includes(*this); + } - bool IPv6Address::matchNetwork(const std::string &network) const + bool IPv6Address::matchNetwork(const std::string& network) const { try { auto ipv6Network = IPv6Network(network); return ipv6Network.includes(*this); } - catch (const std::invalid_argument &e) + catch (const std::invalid_argument& e) { PCPP_LOG_ERROR(e.what()); return false; } } - bool IPv6Address::isValidIPv6Address(const std::string &addrAsString) + bool IPv6Address::isValidIPv6Address(const std::string& addrAsString) { struct sockaddr_in6 sa_in6; return inet_pton(AF_INET6, addrAsString.data(), &(sa_in6.sin6_addr)) > 0; @@ -135,7 +144,7 @@ namespace pcpp // IPAddress // ~~~~~~~~~ - IPAddress::IPAddress(const std::string &addrAsString) + IPAddress::IPAddress(const std::string& addrAsString) { if (IPv4Address::isValidIPv4Address(addrAsString)) { @@ -157,7 +166,7 @@ namespace pcpp // IPv4Network // ~~~~~~~~~~~ - bool IPv4Network::isValidNetmask(const IPv4Address &maskAddress) + bool IPv4Network::isValidNetmask(const IPv4Address& maskAddress) { if (maskAddress == IPv4Address::Zero) { @@ -178,19 +187,19 @@ namespace pcpp } } - void IPv4Network::initFromAddressAndPrefixLength(const IPv4Address &address, uint8_t prefixLen) + void IPv4Network::initFromAddressAndPrefixLength(const IPv4Address& address, uint8_t prefixLen) { m_Mask = be32toh(0xffffffff ^ (prefixLen < 32 ? 0xffffffff >> prefixLen : 0)); m_NetworkPrefix = address.toInt() & m_Mask; } - void IPv4Network::initFromAddressAndNetmask(const IPv4Address &address, const IPv4Address &netmaskAddress) + void IPv4Network::initFromAddressAndNetmask(const IPv4Address& address, const IPv4Address& netmaskAddress) { m_Mask = netmaskAddress.toInt(); m_NetworkPrefix = address.toInt() & m_Mask; } - IPv4Network::IPv4Network(const IPv4Address &address, uint8_t prefixLen) + IPv4Network::IPv4Network(const IPv4Address& address, uint8_t prefixLen) { if (prefixLen > 32) { @@ -200,14 +209,14 @@ namespace pcpp initFromAddressAndPrefixLength(address, prefixLen); } - IPv4Network::IPv4Network(const IPv4Address &address, const std::string &netmask) + IPv4Network::IPv4Network(const IPv4Address& address, const std::string& netmask) { IPv4Address netmaskAddr; try { netmaskAddr = IPv4Address(netmask); } - catch (const std::exception &) + catch (const std::exception&) { throw std::invalid_argument("Netmask is not valid IPv4 format: " + netmask); } @@ -218,7 +227,7 @@ namespace pcpp initFromAddressAndNetmask(address, netmaskAddr); } - IPv4Network::IPv4Network(const std::string &addressAndNetmask) + IPv4Network::IPv4Network(const std::string& addressAndNetmask) { std::stringstream stream(addressAndNetmask); std::string networkPrefixStr, netmaskStr; @@ -236,7 +245,7 @@ namespace pcpp { networkPrefix = IPv4Address(networkPrefixStr); } - catch (const std::invalid_argument &) + catch (const std::invalid_argument&) { throw std::invalid_argument("The input doesn't contain a valid IPv4 network prefix: " + networkPrefixStr); } @@ -258,7 +267,7 @@ namespace pcpp { netmaskAddr = IPv4Address(netmaskStr); } - catch (const std::invalid_argument &) + catch (const std::invalid_argument&) { throw std::invalid_argument("Netmask is not valid IPv4 format: " + netmaskStr); } @@ -295,12 +304,12 @@ namespace pcpp return 1ULL << bitset.count(); } - bool IPv4Network::includes(const IPv4Address &address) const + bool IPv4Network::includes(const IPv4Address& address) const { return (address.toInt() & m_Mask) == m_NetworkPrefix; } - bool IPv4Network::includes(const IPv4Network &network) const + bool IPv4Network::includes(const IPv4Network& network) const { uint32_t lowestAddress = network.m_NetworkPrefix; uint32_t highestAddress = network.m_NetworkPrefix | ~network.m_Mask; @@ -320,14 +329,14 @@ namespace pcpp #define IPV6_ADDR_SIZE 16 - bool IPv6Network::isValidNetmask(const IPv6Address &netmask) + bool IPv6Network::isValidNetmask(const IPv6Address& netmask) { if (netmask == IPv6Address::Zero) { return true; } - const uint8_t *addressAsBytes = netmask.toBytes(); + const uint8_t* addressAsBytes = netmask.toBytes(); int expectingValue = 1; for (auto byteIndex = 0; byteIndex < IPV6_ADDR_SIZE; byteIndex++) { @@ -354,7 +363,7 @@ namespace pcpp return true; } - void IPv6Network::initFromAddressAndPrefixLength(const IPv6Address &address, uint8_t prefixLen) + void IPv6Network::initFromAddressAndPrefixLength(const IPv6Address& address, uint8_t prefixLen) { memset(m_Mask, 0, IPV6_ADDR_SIZE); int remainingPrefixLen = prefixLen; @@ -384,7 +393,7 @@ namespace pcpp } } - void IPv6Network::initFromAddressAndNetmask(const IPv6Address &address, const IPv6Address &netmaskAddr) + void IPv6Network::initFromAddressAndNetmask(const IPv6Address& address, const IPv6Address& netmaskAddr) { netmaskAddr.copyTo(m_Mask); @@ -396,7 +405,7 @@ namespace pcpp } } - IPv6Network::IPv6Network(const IPv6Address &address, uint8_t prefixLen) + IPv6Network::IPv6Network(const IPv6Address& address, uint8_t prefixLen) { if (prefixLen > 128) { @@ -406,14 +415,14 @@ namespace pcpp initFromAddressAndPrefixLength(address, prefixLen); } - IPv6Network::IPv6Network(const IPv6Address &address, const std::string &netmask) + IPv6Network::IPv6Network(const IPv6Address& address, const std::string& netmask) { IPv6Address netmaskAddr; try { netmaskAddr = IPv6Address(netmask); } - catch (const std::exception &) + catch (const std::exception&) { throw std::invalid_argument("Netmask is not valid IPv6 format: " + netmask); } @@ -424,7 +433,7 @@ namespace pcpp initFromAddressAndNetmask(address, netmaskAddr); } - IPv6Network::IPv6Network(const std::string &addressAndNetmask) + IPv6Network::IPv6Network(const std::string& addressAndNetmask) { std::stringstream stream(addressAndNetmask); std::string networkPrefixStr, netmaskStr; @@ -442,7 +451,7 @@ namespace pcpp { networkPrefix = IPv6Address(networkPrefixStr); } - catch (const std::invalid_argument &) + catch (const std::invalid_argument&) { throw std::invalid_argument("The input doesn't contain a valid IPv6 network prefix: " + networkPrefixStr); } @@ -463,7 +472,7 @@ namespace pcpp { netmaskAddr = IPv6Address(netmaskStr); } - catch (const std::exception &) + catch (const std::exception&) { throw std::invalid_argument("Netmask is not valid IPv6 format: " + netmaskStr); } @@ -527,7 +536,7 @@ namespace pcpp return 1ULL << numOfBitset; } - bool IPv6Network::includes(const IPv6Address &address) const + bool IPv6Network::includes(const IPv6Address& address) const { uint8_t maskedBytes[IPV6_ADDR_SIZE]; address.copyTo(maskedBytes); @@ -539,7 +548,7 @@ namespace pcpp return memcmp(m_NetworkPrefix, maskedBytes, IPV6_ADDR_SIZE) == 0; } - bool IPv6Network::includes(const IPv6Network &network) const + bool IPv6Network::includes(const IPv6Network& network) const { return includes(network.getLowestAddress()) && includes(network.getHighestAddress()); } @@ -551,4 +560,4 @@ namespace pcpp return stream.str(); } -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/src/IpAddressUtils.cpp b/Common++/src/IpAddressUtils.cpp index 396d09f898..a65941cbf5 100644 --- a/Common++/src/IpAddressUtils.cpp +++ b/Common++/src/IpAddressUtils.cpp @@ -1,18 +1,21 @@ #include "IpAddressUtils.h" #include "IpAddress.h" -#include "IpUtils.h" // Just needing in_addr and in6_addr. +#include "IpUtils.h" // Just needing in_addr and in6_addr. namespace pcpp { - bool operator==(const IPv4Address &lhs, const in_addr &rhs) { return lhs.toInt() == rhs.s_addr; } + bool operator==(const IPv4Address& lhs, const in_addr& rhs) + { + return lhs.toInt() == rhs.s_addr; + } - bool operator==(const IPv6Address &lhs, const in6_addr &rhs) + bool operator==(const IPv6Address& lhs, const in6_addr& rhs) { return memcmp(lhs.toBytes(), &rhs, sizeof(struct in6_addr)) == 0; } - bool operator==(const IPAddress &lhs, const in_addr &rhs) + bool operator==(const IPAddress& lhs, const in_addr& rhs) { if (lhs.isIPv4()) { @@ -21,7 +24,7 @@ namespace pcpp return false; } - bool operator==(const IPAddress &lhs, const in6_addr &rhs) + bool operator==(const IPAddress& lhs, const in6_addr& rhs) { if (lhs.isIPv6()) { @@ -29,4 +32,4 @@ namespace pcpp } return false; } -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/src/IpUtils.cpp b/Common++/src/IpUtils.cpp index 7cc9967ca3..86e3815d53 100644 --- a/Common++/src/IpUtils.cpp +++ b/Common++/src/IpUtils.cpp @@ -19,7 +19,7 @@ namespace pcpp { namespace internal { - in_addr *sockaddr2in_addr(sockaddr *sa) + in_addr* sockaddr2in_addr(sockaddr* sa) { if (sa == nullptr) throw std::invalid_argument("sockaddr is nullptr"); @@ -27,23 +27,23 @@ namespace pcpp if (sa->sa_family != AF_INET) throw std::invalid_argument("sockaddr family is not AF_INET."); - return &(reinterpret_cast(sa)->sin_addr); + return &(reinterpret_cast(sa)->sin_addr); } - in_addr *try_sockaddr2in_addr(sockaddr *sa) + in_addr* try_sockaddr2in_addr(sockaddr* sa) { try { return sockaddr2in_addr(sa); } - catch (const std::invalid_argument &e) + catch (const std::invalid_argument& e) { PCPP_LOG_DEBUG("Extraction failed: " << e.what() << " Returning nullptr."); return nullptr; } } - in6_addr *sockaddr2in6_addr(sockaddr *sa) + in6_addr* sockaddr2in6_addr(sockaddr* sa) { if (sa == nullptr) throw std::invalid_argument("sockaddr is nullptr"); @@ -51,23 +51,23 @@ namespace pcpp if (sa->sa_family != AF_INET6) throw std::invalid_argument("sockaddr family is not AF_INET6."); - return &(reinterpret_cast(sa)->sin6_addr); + return &(reinterpret_cast(sa)->sin6_addr); } - in6_addr *try_sockaddr2in6_addr(sockaddr *sa) + in6_addr* try_sockaddr2in6_addr(sockaddr* sa) { try { return sockaddr2in6_addr(sa); } - catch (const std::invalid_argument &e) + catch (const std::invalid_argument& e) { PCPP_LOG_DEBUG("Extraction failed: " << e.what() << " Returning nullptr."); return nullptr; } } - void sockaddr2string(sockaddr const *sa, char *resultString, size_t resultBufLen) + void sockaddr2string(sockaddr const* sa, char* resultString, size_t resultBufLen) { if (sa == nullptr) throw std::invalid_argument("sockaddr is nullptr"); @@ -80,7 +80,7 @@ namespace pcpp if (resultBufLen < INET_ADDRSTRLEN) throw std::invalid_argument("Insufficient buffer"); - if (inet_ntop(AF_INET, &(reinterpret_cast(sa)->sin_addr), resultString, + if (inet_ntop(AF_INET, &(reinterpret_cast(sa)->sin_addr), resultString, resultBufLen) == nullptr) { throw std::runtime_error("Unknown error during conversion"); @@ -93,7 +93,7 @@ namespace pcpp if (resultBufLen < INET6_ADDRSTRLEN) throw std::invalid_argument("Insufficient buffer"); - if (inet_ntop(AF_INET6, &(reinterpret_cast(sa)->sin6_addr), resultString, + if (inet_ntop(AF_INET6, &(reinterpret_cast(sa)->sin6_addr), resultString, resultBufLen) == nullptr) { throw std::runtime_error("Unknown error during conversion"); @@ -113,8 +113,8 @@ namespace pcpp return inAddr.s_addr; #endif } - } // namespace internal -} // namespace pcpp + } // namespace internal +} // namespace pcpp // Only MinGW32 doesn't have these functions (not MinGW-w64 nor Visual C++) #if defined(_WIN32) && !defined(_MSC_VER) && (!defined(__MINGW64_VERSION_MAJOR) || (__MINGW64_VERSION_MAJOR < 8)) @@ -129,7 +129,7 @@ namespace pcpp * author: * Paul Vixie, 1996. */ -static const char *inet_ntop4(const uint8_t *src, char *dst, size_t size) +static const char* inet_ntop4(const uint8_t* src, char* dst, size_t size) { static const char fmt[] = "%u.%u.%u.%u"; char tmp[sizeof "255.255.255.255"]; @@ -150,7 +150,7 @@ static const char *inet_ntop4(const uint8_t *src, char *dst, size_t size) * author: * Paul Vixie, 1996. */ -static const char *inet_ntop6(const uint8_t *src, char *dst, size_t size) +static const char* inet_ntop6(const uint8_t* src, char* dst, size_t size) { /* * Note that int32_t and int16_t need only be "at least" large enough @@ -258,7 +258,7 @@ static const char *inet_ntop6(const uint8_t *src, char *dst, size_t size) * author: * Paul Vixie, 1996. */ -static int inet_pton4(const char *src, uint8_t *dst) +static int inet_pton4(const char* src, uint8_t* dst) { static const char digits[] = "0123456789"; int saw_digit, octets, ch; @@ -269,7 +269,7 @@ static int inet_pton4(const char *src, uint8_t *dst) *(tp = tmp) = 0; while ((ch = *src++) != '\0') { - const char *pch; + const char* pch; if ((pch = strchr(digits, ch)) != NULL) { @@ -314,11 +314,11 @@ static int inet_pton4(const char *src, uint8_t *dst) * author: * Paul Vixie, 1996. */ -static int inet_pton6(const char *src, uint8_t *dst) +static int inet_pton6(const char* src, uint8_t* dst) { static const char xdigits_l[] = "0123456789abcdef", xdigits_u[] = "0123456789ABCDEF"; u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; - const char *curtok; + const char* curtok; int ch, saw_xdigit; u_int val; @@ -408,31 +408,31 @@ static int inet_pton6(const char *src, uint8_t *dst) return (1); } -const char *inet_ntop(int af, const void *src, char *dst, size_t size) +const char* inet_ntop(int af, const void* src, char* dst, size_t size) { switch (af) { case AF_INET: - return (inet_ntop4((const uint8_t *)src, dst, size)); + return (inet_ntop4((const uint8_t*)src, dst, size)); case AF_INET6: - return (inet_ntop6((const uint8_t *)src, dst, size)); + return (inet_ntop6((const uint8_t*)src, dst, size)); default: return (NULL); } /* NOTREACHED */ } -int inet_pton(int af, const char *src, void *dst) +int inet_pton(int af, const char* src, void* dst) { switch (af) { # ifdef AF_INET case AF_INET: - return (inet_pton4(src, (uint8_t *)dst)); + return (inet_pton4(src, (uint8_t*)dst)); # endif # ifdef AF_INET6 case AF_INET6: - return (inet_pton6(src, (uint8_t *)dst)); + return (inet_pton6(src, (uint8_t*)dst)); # endif default: return (-1); diff --git a/Common++/src/Logger.cpp b/Common++/src/Logger.cpp index b584095c16..0bd8d3a14c 100644 --- a/Common++/src/Logger.cpp +++ b/Common++/src/Logger.cpp @@ -1,5 +1,5 @@ -#include #include "Logger.h" +#include namespace pcpp { @@ -24,8 +24,8 @@ namespace pcpp } } - void Logger::defaultLogPrinter(LogLevel logLevel, const std::string &logMessage, const std::string &file, - const std::string &method, const int line) + void Logger::defaultLogPrinter(LogLevel logLevel, const std::string& logMessage, const std::string& file, + const std::string& method, const int line) { std::ostringstream sstream; sstream << file << ": " << method << ":" << line; @@ -33,10 +33,13 @@ namespace pcpp << sstream.str() << "] " << logMessage << std::endl; } - std::ostringstream *Logger::internalCreateLogStream() { return new std::ostringstream(); } + std::ostringstream* Logger::internalCreateLogStream() + { + return new std::ostringstream(); + } - void Logger::internalPrintLogMessage(std::ostringstream *logStream, Logger::LogLevel logLevel, const char *file, - const char *method, int line) + void Logger::internalPrintLogMessage(std::ostringstream* logStream, Logger::LogLevel logLevel, const char* file, + const char* method, int line) { std::string logMessage = logStream->str(); delete logStream; @@ -50,4 +53,4 @@ namespace pcpp } } -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/src/MacAddress.cpp b/Common++/src/MacAddress.cpp index cf5e653b4f..e3570b3437 100644 --- a/Common++/src/MacAddress.cpp +++ b/Common++/src/MacAddress.cpp @@ -15,7 +15,7 @@ namespace pcpp return std::string(str); } - MacAddress::MacAddress(const std::string &address) + MacAddress::MacAddress(const std::string& address) { constexpr size_t validMacAddressLength = 17; unsigned int values[6]; @@ -31,4 +31,4 @@ namespace pcpp } } -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/src/OUILookup.cpp b/Common++/src/OUILookup.cpp index 09a919e1f4..b2b24d145b 100644 --- a/Common++/src/OUILookup.cpp +++ b/Common++/src/OUILookup.cpp @@ -8,14 +8,14 @@ namespace pcpp { - template int64_t OUILookup::internalParser(T &jsonData) + template int64_t OUILookup::internalParser(T& jsonData) { // Clear all entries before adding vendorMap.clear(); int64_t ctrRead = 0; nlohmann::json parsedJson = nlohmann::json::parse(jsonData); - for (const auto &line : parsedJson.items()) + for (const auto& line : parsedJson.items()) { if (!(line.value().is_object())) continue; @@ -27,7 +27,7 @@ namespace pcpp if (val.contains("maskedFilters") && val["maskedFilters"].is_array()) { // Iterate through masked filters - for (const auto &entry : val["maskedFilters"]) + for (const auto& entry : val["maskedFilters"]) { if (!entry.is_object()) continue; @@ -39,7 +39,7 @@ namespace pcpp vLocalMaskedFilter.push_back({maskValue, {}}); // Parse masked filter - for (const auto &subentry : subVal["vendors"].items()) + for (const auto& subentry : subVal["vendors"].items()) { if (subentry.value().is_string()) { @@ -52,7 +52,9 @@ namespace pcpp } } - vendorMap.insert({std::stoull(line.key()), {val["vendor"], vLocalMaskedFilter}}); + vendorMap.insert({ + std::stoull(line.key()), {val["vendor"], vLocalMaskedFilter} + }); ++ctrRead; } @@ -60,7 +62,7 @@ namespace pcpp return ctrRead; } - int64_t OUILookup::initOUIDatabaseFromJson(const std::string &path) + int64_t OUILookup::initOUIDatabaseFromJson(const std::string& path) { std::ifstream dataFile; @@ -76,7 +78,7 @@ namespace pcpp return internalParser(dataFile); } - std::string OUILookup::getVendorName(const pcpp::MacAddress &addr) + std::string OUILookup::getVendorName(const pcpp::MacAddress& addr) { if (vendorMap.empty()) PCPP_LOG_DEBUG("Vendor map is empty"); @@ -93,7 +95,7 @@ namespace pcpp if (itr == vendorMap.end()) return "Unknown"; - for (const auto &entry : itr->second.maskedFilter) + for (const auto& entry : itr->second.maskedFilter) { uint64_t maskValue = ~((1 << (48 - entry.mask)) - 1); uint64_t bufferAddr = macAddr & maskValue; @@ -106,4 +108,4 @@ namespace pcpp return itr->second.vendorName; } -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/src/PcapPlusPlusVersion.cpp b/Common++/src/PcapPlusPlusVersion.cpp index 0c861f2572..16f0ca3b95 100644 --- a/Common++/src/PcapPlusPlusVersion.cpp +++ b/Common++/src/PcapPlusPlusVersion.cpp @@ -19,6 +19,9 @@ namespace pcpp return "unavailable"; } - std::string getGitInfo() { return "Git branch '" + getGitBranch() + "', commit '" + getGitCommit() + "'"; } + std::string getGitInfo() + { + return "Git branch '" + getGitBranch() + "', commit '" + getGitCommit() + "'"; + } -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/src/SystemUtils.cpp b/Common++/src/SystemUtils.cpp index bb08f88d6a..b92c163c47 100644 --- a/Common++/src/SystemUtils.cpp +++ b/Common++/src/SystemUtils.cpp @@ -4,12 +4,12 @@ #ifndef _MSC_VER # include #endif -#include -#include #include #include +#include #include #include +#include #include #include #include @@ -31,7 +31,7 @@ #endif #ifdef _MSC_VER -int gettimeofday(struct timeval *tp, struct timezone *tzp) +int gettimeofday(struct timeval* tp, struct timezone* tzp) { // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL); @@ -61,9 +61,12 @@ namespace */ struct PcloseDeleter { - void operator()(FILE *ptr) const { PCLOSE(ptr); } + void operator()(FILE* ptr) const + { + PCLOSE(ptr); + } }; -} // namespace +} // namespace /// @endcond @@ -104,8 +107,8 @@ namespace pcpp const SystemCore SystemCores::Core31 = {0x80000000, 31}; const SystemCore SystemCores::IdToSystemCore[MAX_NUM_OF_CORES] = { - SystemCores::Core0, SystemCores::Core1, SystemCores::Core2, SystemCores::Core3, SystemCores::Core4, - SystemCores::Core5, SystemCores::Core6, SystemCores::Core7, SystemCores::Core8, SystemCores::Core9, + SystemCores::Core0, SystemCores::Core1, SystemCores::Core2, SystemCores::Core3, SystemCores::Core4, + SystemCores::Core5, SystemCores::Core6, SystemCores::Core7, SystemCores::Core8, SystemCores::Core9, SystemCores::Core10, SystemCores::Core11, SystemCores::Core12, SystemCores::Core13, SystemCores::Core14, SystemCores::Core15, SystemCores::Core16, SystemCores::Core17, SystemCores::Core18, SystemCores::Core19, SystemCores::Core20, SystemCores::Core21, SystemCores::Core22, SystemCores::Core23, SystemCores::Core24, @@ -135,10 +138,10 @@ namespace pcpp return result; } - CoreMask createCoreMaskFromCoreVector(const std::vector &cores) + CoreMask createCoreMaskFromCoreVector(const std::vector& cores) { CoreMask result = 0; - for (const auto &core : cores) + for (const auto& core : cores) { // cppcheck-suppress useStlAlgorithm result |= core.Mask; @@ -147,10 +150,10 @@ namespace pcpp return result; } - CoreMask createCoreMaskFromCoreIds(const std::vector &coreIds) + CoreMask createCoreMaskFromCoreIds(const std::vector& coreIds) { CoreMask result = 0; - for (const auto &coreId : coreIds) + for (const auto& coreId : coreIds) { // cppcheck-suppress useStlAlgorithm result |= SystemCores::IdToSystemCore[coreId].Mask; @@ -159,7 +162,7 @@ namespace pcpp return result; } - void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector &resultVec) + void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector& resultVec) { int i = 0; while (coreMask != 0) @@ -174,7 +177,7 @@ namespace pcpp } } - std::string executeShellCommand(const std::string &command) + std::string executeShellCommand(const std::string& command) { std::unique_ptr pipe = std::unique_ptr(POPEN(command.c_str(), "r")); if (!pipe) @@ -187,12 +190,12 @@ namespace pcpp while (!feof(pipe.get())) { if (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) - result += buffer.data(); // Using the C-string overload of string append. + result += buffer.data(); // Using the C-string overload of string append. } return result; } - bool directoryExists(const std::string &dirPath) + bool directoryExists(const std::string& dirPath) { struct stat info; @@ -204,7 +207,7 @@ namespace pcpp return false; } - int clockGetTime(long &sec, long &nsec) + int clockGetTime(long& sec, long& nsec) { sec = 0; nsec = 0; @@ -251,7 +254,7 @@ namespace pcpp return 0; -#else // Linux +#else // Linux # include @@ -285,13 +288,25 @@ namespace pcpp #endif } - uint16_t hostToNet16(uint16_t host) { return htobe16(host); } + uint16_t hostToNet16(uint16_t host) + { + return htobe16(host); + } - uint16_t netToHost16(uint16_t net) { return be16toh(net); } + uint16_t netToHost16(uint16_t net) + { + return be16toh(net); + } - uint32_t hostToNet32(uint32_t host) { return htobe32(host); } + uint32_t hostToNet32(uint32_t host) + { + return htobe32(host); + } - uint32_t netToHost32(uint32_t net) { return be32toh(net); } + uint32_t netToHost32(uint32_t net) + { + return be32toh(net); + } std::string AppName::m_AppName; @@ -350,7 +365,7 @@ namespace pcpp { } - void ApplicationEventHandler::onApplicationInterrupted(EventHandlerCallback handler, void *cookie) + void ApplicationEventHandler::onApplicationInterrupted(EventHandlerCallback handler, void* cookie) { m_ApplicationInterruptedHandler = handler; m_ApplicationInterruptedCookie = cookie; @@ -366,4 +381,4 @@ namespace pcpp #endif } -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/src/TablePrinter.cpp b/Common++/src/TablePrinter.cpp index 74d5397dfa..b4e74be52f 100644 --- a/Common++/src/TablePrinter.cpp +++ b/Common++/src/TablePrinter.cpp @@ -24,7 +24,10 @@ namespace pcpp } } - TablePrinter::~TablePrinter() { closeTable(); } + TablePrinter::~TablePrinter() + { + closeTable(); + } bool TablePrinter::printRow(std::vector values) { @@ -65,7 +68,7 @@ namespace pcpp return true; } - bool TablePrinter::printRow(const std::string &values, char delimiter) + bool TablePrinter::printRow(const std::string& values, char delimiter) { std::string singleValue; std::istringstream valueStream(values); @@ -127,4 +130,4 @@ namespace pcpp printSeparator(); } -} // namespace pcpp +} // namespace pcpp From 2bb033a1d749d0ad1aea5ea36cbbf9195b99968b Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Wed, 19 Jun 2024 17:57:44 +0900 Subject: [PATCH 08/13] rerun the clang-format --- Common++/header/DeprecationUtils.h | 2 +- Common++/header/GeneralUtils.h | 2 +- Common++/header/IpAddress.h | 18 +++++++++--------- Common++/header/IpUtils.h | 8 ++++---- Common++/header/LRUList.h | 4 ++-- Common++/header/Logger.h | 4 ++-- Common++/header/MacAddress.h | 10 +++++----- Common++/header/PointerVector.h | 2 +- Common++/src/IpAddress.cpp | 6 +++--- Common++/src/IpUtils.cpp | 4 ++-- Common++/src/Logger.cpp | 8 ++++---- Common++/src/MacAddress.cpp | 6 +++--- Common++/src/OUILookup.cpp | 10 +++++----- Common++/src/SystemUtils.cpp | 26 +++++++++++++------------- Common++/src/TablePrinter.cpp | 6 +++--- 15 files changed, 58 insertions(+), 58 deletions(-) diff --git a/Common++/header/DeprecationUtils.h b/Common++/header/DeprecationUtils.h index ab91c87c86..2d600d88d6 100644 --- a/Common++/header/DeprecationUtils.h +++ b/Common++/header/DeprecationUtils.h @@ -27,7 +27,7 @@ # define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName) // clang-format off -#define DISABLE_WARNING_DEPRECATED DISABLE_WARNING(-Wdeprecated-declarations) +# define DISABLE_WARNING_DEPRECATED DISABLE_WARNING(-Wdeprecated-declarations) // clang-format on # else # pragma message("WARNING: Disabling of warnings is not implemented for this compiler") diff --git a/Common++/header/GeneralUtils.h b/Common++/header/GeneralUtils.h index 9452cc2f41..8dd1e83b85 100644 --- a/Common++/header/GeneralUtils.h +++ b/Common++/header/GeneralUtils.h @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include /// @file diff --git a/Common++/header/IpAddress.h b/Common++/header/IpAddress.h index f87bfac48b..16d7668b2c 100644 --- a/Common++/header/IpAddress.h +++ b/Common++/header/IpAddress.h @@ -1,12 +1,12 @@ #pragma once -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include /// @file @@ -123,7 +123,7 @@ namespace pcpp uint32_t rhsIntVal = rhs.toInt(); std::reverse(reinterpret_cast(&rhsIntVal), - reinterpret_cast(&rhsIntVal) + sizeof(rhsIntVal)); + reinterpret_cast(&rhsIntVal) + sizeof(rhsIntVal)); return intVal < rhsIntVal; } @@ -975,7 +975,7 @@ namespace pcpp IPAddress getNetworkPrefix() const { return (m_IPv4Network != nullptr ? IPAddress(m_IPv4Network->getNetworkPrefix()) - : IPAddress(m_IPv6Network->getNetworkPrefix())); + : IPAddress(m_IPv6Network->getNetworkPrefix())); } /** @@ -985,7 +985,7 @@ namespace pcpp IPAddress getLowestAddress() const { return (m_IPv4Network != nullptr ? IPAddress(m_IPv4Network->getLowestAddress()) - : IPAddress(m_IPv6Network->getLowestAddress())); + : IPAddress(m_IPv6Network->getLowestAddress())); } /** @@ -995,7 +995,7 @@ namespace pcpp IPAddress getHighestAddress() const { return (m_IPv4Network != nullptr ? IPAddress(m_IPv4Network->getHighestAddress()) - : IPAddress(m_IPv6Network->getHighestAddress())); + : IPAddress(m_IPv6Network->getHighestAddress())); } /** @@ -1006,7 +1006,7 @@ namespace pcpp uint64_t getTotalAddressCount() const { return (m_IPv4Network != nullptr ? m_IPv4Network->getTotalAddressCount() - : m_IPv6Network->getTotalAddressCount()); + : m_IPv6Network->getTotalAddressCount()); } /** diff --git a/Common++/header/IpUtils.h b/Common++/header/IpUtils.h index 319e73cfee..826808b7ab 100644 --- a/Common++/header/IpUtils.h +++ b/Common++/header/IpUtils.h @@ -2,20 +2,20 @@ #include #ifdef __linux__ -# include # include +# include #endif #if defined(__APPLE__) -# include # include +# include #endif #if defined(_WIN32) # include #endif #if defined(__FreeBSD__) -# include -# include # include +# include +# include #endif /// @file diff --git a/Common++/header/LRUList.h b/Common++/header/LRUList.h index 27172114c8..89eea59e28 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #if __cplusplus > 199711L || _MSC_VER >= 1800 # include @@ -56,7 +56,7 @@ namespace pcpp // Inserting a new element. If an element with an equivalent key already exists the method returns an // iterator to the element that prevented the insertion std::pair pair = - m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin())); + m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin())); if (pair.second == false) // already exists { m_CacheItemsList.erase(pair.first->second); diff --git a/Common++/header/Logger.h b/Common++/header/Logger.h index 145a85a13d..3208fa6f6f 100644 --- a/Common++/header/Logger.h +++ b/Common++/header/Logger.h @@ -1,10 +1,10 @@ #pragma once -#include +#include #include #include +#include #include -#include #ifndef LOG_MODULE # define LOG_MODULE UndefinedLogModule diff --git a/Common++/header/MacAddress.h b/Common++/header/MacAddress.h index 9a849d3df2..15b51192cf 100644 --- a/Common++/header/MacAddress.h +++ b/Common++/header/MacAddress.h @@ -1,12 +1,12 @@ #pragma once -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include /// @file @@ -66,7 +66,7 @@ namespace pcpp * @param[in] sixthOctet Represent the sixth octet in the address */ inline MacAddress(uint8_t firstOctet, uint8_t secondOctet, uint8_t thirdOctet, uint8_t fourthOctet, - uint8_t fifthOctet, uint8_t sixthOctet) + uint8_t fifthOctet, uint8_t sixthOctet) { m_Address[0] = firstOctet; m_Address[1] = secondOctet; diff --git a/Common++/header/PointerVector.h b/Common++/header/PointerVector.h index 1bd12273df..29b5cc03df 100644 --- a/Common++/header/PointerVector.h +++ b/Common++/header/PointerVector.h @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #include /// @file diff --git a/Common++/src/IpAddress.cpp b/Common++/src/IpAddress.cpp index f48d5673eb..2c2f439361 100644 --- a/Common++/src/IpAddress.cpp +++ b/Common++/src/IpAddress.cpp @@ -44,7 +44,7 @@ namespace pcpp bool IPv4Address::isMulticast() const { return !operator<(MulticastRangeLowerBound) && - (operator<(MulticastRangeUpperBound) || operator==(MulticastRangeUpperBound)); + (operator<(MulticastRangeUpperBound) || operator==(MulticastRangeUpperBound)); } IPv4Address::IPv4Address(const std::string& addrAsString) @@ -237,7 +237,7 @@ namespace pcpp if (netmaskStr.empty()) { throw std::invalid_argument( - "The input should be in the format of
/ or
/"); + "The input should be in the format of
/ or
/"); } IPv4Address networkPrefix; @@ -443,7 +443,7 @@ namespace pcpp if (netmaskStr.empty()) { throw std::invalid_argument( - "The input should be in the format of
/ or
/"); + "The input should be in the format of
/ or
/"); } IPv6Address networkPrefix; diff --git a/Common++/src/IpUtils.cpp b/Common++/src/IpUtils.cpp index 86e3815d53..c6530a43e8 100644 --- a/Common++/src/IpUtils.cpp +++ b/Common++/src/IpUtils.cpp @@ -81,7 +81,7 @@ namespace pcpp throw std::invalid_argument("Insufficient buffer"); if (inet_ntop(AF_INET, &(reinterpret_cast(sa)->sin_addr), resultString, - resultBufLen) == nullptr) + resultBufLen) == nullptr) { throw std::runtime_error("Unknown error during conversion"); } @@ -94,7 +94,7 @@ namespace pcpp throw std::invalid_argument("Insufficient buffer"); if (inet_ntop(AF_INET6, &(reinterpret_cast(sa)->sin6_addr), resultString, - resultBufLen) == nullptr) + resultBufLen) == nullptr) { throw std::runtime_error("Unknown error during conversion"); } diff --git a/Common++/src/Logger.cpp b/Common++/src/Logger.cpp index 0bd8d3a14c..cbedaba566 100644 --- a/Common++/src/Logger.cpp +++ b/Common++/src/Logger.cpp @@ -1,5 +1,5 @@ -#include "Logger.h" #include +#include "Logger.h" namespace pcpp { @@ -25,12 +25,12 @@ namespace pcpp } void Logger::defaultLogPrinter(LogLevel logLevel, const std::string& logMessage, const std::string& file, - const std::string& method, const int line) + const std::string& method, const int line) { std::ostringstream sstream; sstream << file << ": " << method << ":" << line; std::cout << std::left << "[" << std::setw(5) << Logger::logLevelAsString(logLevel) << ": " << std::setw(45) - << sstream.str() << "] " << logMessage << std::endl; + << sstream.str() << "] " << logMessage << std::endl; } std::ostringstream* Logger::internalCreateLogStream() @@ -39,7 +39,7 @@ namespace pcpp } void Logger::internalPrintLogMessage(std::ostringstream* logStream, Logger::LogLevel logLevel, const char* file, - const char* method, int line) + const char* method, int line) { std::string logMessage = logStream->str(); delete logStream; diff --git a/Common++/src/MacAddress.cpp b/Common++/src/MacAddress.cpp index e3570b3437..f9fcc9bcc1 100644 --- a/Common++/src/MacAddress.cpp +++ b/Common++/src/MacAddress.cpp @@ -11,7 +11,7 @@ namespace pcpp { char str[19]; snprintf(str, sizeof str, "%02x:%02x:%02x:%02x:%02x:%02x", m_Address[0], m_Address[1], m_Address[2], - m_Address[3], m_Address[4], m_Address[5]); + m_Address[3], m_Address[4], m_Address[5]); return std::string(str); } @@ -20,8 +20,8 @@ namespace pcpp constexpr size_t validMacAddressLength = 17; unsigned int values[6]; if (address.size() != validMacAddressLength || - sscanf(address.c_str(), "%x:%x:%x:%x:%x:%x", &values[0], &values[1], &values[2], &values[3], &values[4], - &values[5]) != 6) + sscanf(address.c_str(), "%x:%x:%x:%x:%x:%x", &values[0], &values[1], &values[2], &values[3], &values[4], + &values[5]) != 6) { throw std::invalid_argument("Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); } diff --git a/Common++/src/OUILookup.cpp b/Common++/src/OUILookup.cpp index b2b24d145b..a76e50b478 100644 --- a/Common++/src/OUILookup.cpp +++ b/Common++/src/OUILookup.cpp @@ -33,7 +33,7 @@ namespace pcpp continue; auto subVal = entry.get(); if (subVal.contains("mask") && subVal.contains("vendors") && subVal["mask"].is_number_integer() && - subVal["vendors"].is_object()) + subVal["vendors"].is_object()) { int maskValue = subVal["mask"].get(); vLocalMaskedFilter.push_back({maskValue, {}}); @@ -44,7 +44,7 @@ namespace pcpp if (subentry.value().is_string()) { vLocalMaskedFilter.back().vendorMap.insert( - {std::stoull(subentry.key()), subentry.value()}); + {std::stoull(subentry.key()), subentry.value()}); ++ctrRead; } } @@ -53,7 +53,7 @@ namespace pcpp } vendorMap.insert({ - std::stoull(line.key()), {val["vendor"], vLocalMaskedFilter} + std::stoull(line.key()), {val["vendor"], vLocalMaskedFilter} }); ++ctrRead; } @@ -88,8 +88,8 @@ namespace pcpp addr.copyTo(buffArray); uint64_t macAddr = (((uint64_t)((buffArray)[5]) << 0) + ((uint64_t)((buffArray)[4]) << 8) + - ((uint64_t)((buffArray)[3]) << 16) + ((uint64_t)((buffArray)[2]) << 24) + - ((uint64_t)((buffArray)[1]) << 32) + ((uint64_t)((buffArray)[0]) << 40)); + ((uint64_t)((buffArray)[3]) << 16) + ((uint64_t)((buffArray)[2]) << 24) + + ((uint64_t)((buffArray)[1]) << 32) + ((uint64_t)((buffArray)[0]) << 40)); auto itr = vendorMap.find(macAddr >> 24); if (itr == vendorMap.end()) diff --git a/Common++/src/SystemUtils.cpp b/Common++/src/SystemUtils.cpp index b92c163c47..1d46218729 100644 --- a/Common++/src/SystemUtils.cpp +++ b/Common++/src/SystemUtils.cpp @@ -4,12 +4,12 @@ #ifndef _MSC_VER # include #endif +#include +#include #include #include -#include #include #include -#include #include #include #include @@ -107,13 +107,13 @@ namespace pcpp const SystemCore SystemCores::Core31 = {0x80000000, 31}; const SystemCore SystemCores::IdToSystemCore[MAX_NUM_OF_CORES] = { - SystemCores::Core0, SystemCores::Core1, SystemCores::Core2, SystemCores::Core3, SystemCores::Core4, - SystemCores::Core5, SystemCores::Core6, SystemCores::Core7, SystemCores::Core8, SystemCores::Core9, - SystemCores::Core10, SystemCores::Core11, SystemCores::Core12, SystemCores::Core13, SystemCores::Core14, - SystemCores::Core15, SystemCores::Core16, SystemCores::Core17, SystemCores::Core18, SystemCores::Core19, - SystemCores::Core20, SystemCores::Core21, SystemCores::Core22, SystemCores::Core23, SystemCores::Core24, - SystemCores::Core25, SystemCores::Core26, SystemCores::Core27, SystemCores::Core28, SystemCores::Core29, - SystemCores::Core30, SystemCores::Core31}; + SystemCores::Core0, SystemCores::Core1, SystemCores::Core2, SystemCores::Core3, SystemCores::Core4, + SystemCores::Core5, SystemCores::Core6, SystemCores::Core7, SystemCores::Core8, SystemCores::Core9, + SystemCores::Core10, SystemCores::Core11, SystemCores::Core12, SystemCores::Core13, SystemCores::Core14, + SystemCores::Core15, SystemCores::Core16, SystemCores::Core17, SystemCores::Core18, SystemCores::Core19, + SystemCores::Core20, SystemCores::Core21, SystemCores::Core22, SystemCores::Core23, SystemCores::Core24, + SystemCores::Core25, SystemCores::Core26, SystemCores::Core27, SystemCores::Core28, SystemCores::Core29, + SystemCores::Core30, SystemCores::Core31}; int getNumOfCores() { @@ -238,7 +238,7 @@ namespace pcpp sec = count.QuadPart / clock_gettime_counts_per_sec.QuadPart; nsec = ((count.QuadPart % clock_gettime_counts_per_sec.QuadPart) * CLOCK_GETTIME_BILLION) / - clock_gettime_counts_per_sec.QuadPart; + clock_gettime_counts_per_sec.QuadPart; return 0; @@ -320,7 +320,7 @@ namespace pcpp { if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL) ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler( - ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); + ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); return TRUE; } @@ -346,7 +346,7 @@ namespace pcpp if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != nullptr) ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler( - ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); + ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler = nullptr; @@ -361,7 +361,7 @@ namespace pcpp #endif ApplicationEventHandler::ApplicationEventHandler() - : m_ApplicationInterruptedHandler(nullptr), m_ApplicationInterruptedCookie(nullptr) + : m_ApplicationInterruptedHandler(nullptr), m_ApplicationInterruptedCookie(nullptr) { } diff --git a/Common++/src/TablePrinter.cpp b/Common++/src/TablePrinter.cpp index b4e74be52f..8c424cd000 100644 --- a/Common++/src/TablePrinter.cpp +++ b/Common++/src/TablePrinter.cpp @@ -13,13 +13,13 @@ namespace pcpp { TablePrinter::TablePrinter(std::vector columnNames, std::vector columnWidths) - : m_ColumnNames(std::move(columnNames)), m_ColumnWidths(std::move(columnWidths)), m_FirstRow(true), - m_TableClosed(false) + : m_ColumnNames(std::move(columnNames)), m_ColumnWidths(std::move(columnWidths)), m_FirstRow(true), + m_TableClosed(false) { if (m_ColumnWidths.size() != m_ColumnNames.size()) { PCPP_LOG_ERROR("Cannot create table: number of column names provided is different than number of column " - "widths provided"); + "widths provided"); m_TableClosed = true; } } From 1f3ef6b86ff2460c35f0398ed0ac85e454d040ba Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Wed, 19 Jun 2024 18:01:41 +0900 Subject: [PATCH 09/13] tune --- .clang-format | 3 ++- Common++/header/IpAddress.h | 24 ++++++++++++------------ Common++/header/LRUList.h | 6 +++--- Common++/header/Logger.h | 4 ++-- Common++/header/MacAddress.h | 4 ++-- Common++/header/OUILookup.h | 4 ++-- Common++/header/PointerVector.h | 4 ++-- Common++/header/SystemUtils.h | 8 ++++---- Common++/header/TablePrinter.h | 4 ++-- 9 files changed, 31 insertions(+), 30 deletions(-) diff --git a/.clang-format b/.clang-format index 05d878e550..6538185c89 100644 --- a/.clang-format +++ b/.clang-format @@ -9,11 +9,12 @@ IndentPPDirectives: AfterHash IndentWidth: 4 AllowShortBlocksOnASingleLine: Never PointerAlignment: Left -AccessModifierOffset: -1 +AccessModifierOffset: -4 AlignTrailingComments: true AllowShortEnumsOnASingleLine: false BreakStringLiterals: true AlignArrayOfStructures: Left BreakArrays: true SpacesBeforeTrailingComments: 2 +IndentAccessModifiers: false ... diff --git a/Common++/header/IpAddress.h b/Common++/header/IpAddress.h index 16d7668b2c..bed86a6df0 100644 --- a/Common++/header/IpAddress.h +++ b/Common++/header/IpAddress.h @@ -30,7 +30,7 @@ namespace pcpp */ class IPv4Address { - public: + public: /** * A default constructor that creates an instance of the class with the zero-initialized address */ @@ -179,7 +179,7 @@ namespace pcpp static const IPv4Address MulticastRangeLowerBound; static const IPv4Address MulticastRangeUpperBound; - private: + private: std::array m_Bytes = {0}; }; // class IPv4Address @@ -198,7 +198,7 @@ namespace pcpp */ class IPv6Address { - public: + public: /** * A default constructor that creates an instance of the class with the zero-initialized address. */ @@ -348,7 +348,7 @@ namespace pcpp */ static const IPv6Address MulticastRangeLowerBound; - private: + private: std::array m_Bytes = {0}; }; // class IPv6Address @@ -358,7 +358,7 @@ namespace pcpp */ class IPAddress { - public: + public: /** * An enum representing the address type: IPv4 or IPv6 */ @@ -512,7 +512,7 @@ namespace pcpp return !(*this == rhs); } - private: + private: uint8_t m_Type; IPv4Address m_IPv4; IPv6Address m_IPv6; @@ -559,7 +559,7 @@ namespace pcpp */ class IPv4Network { - public: + public: /** * A constructor that creates an instance of the class out of an address and a full prefix length, * essentially making a network of consisting of only 1 address. @@ -662,7 +662,7 @@ namespace pcpp */ std::string toString() const; - private: + private: uint32_t m_NetworkPrefix; uint32_t m_Mask; @@ -677,7 +677,7 @@ namespace pcpp */ class IPv6Network { - public: + public: /** * A constructor that creates an instance of the class out of an address and a full prefix length, * essentially making a network of consisting of only 1 address. @@ -780,7 +780,7 @@ namespace pcpp */ std::string toString() const; - private: + private: uint8_t m_NetworkPrefix[16]; uint8_t m_Mask[16]; @@ -795,7 +795,7 @@ namespace pcpp */ class IPNetwork { - public: + public: /** * A constructor that creates an instance of the class out of an IP address and a full prefix length, * essentially making a network of consisting of only 1 address. @@ -1086,7 +1086,7 @@ namespace pcpp return (m_IPv4Network != nullptr ? m_IPv4Network->toString() : m_IPv6Network->toString()); } - private: + private: std::unique_ptr m_IPv4Network; std::unique_ptr m_IPv6Network; }; diff --git a/Common++/header/LRUList.h b/Common++/header/LRUList.h index 89eea59e28..081fd2434b 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -1,7 +1,7 @@ #pragma once -#include #include +#include #if __cplusplus > 199711L || _MSC_VER >= 1800 # include @@ -25,7 +25,7 @@ namespace pcpp */ template class LRUList { - public: + public: typedef typename std::list::iterator ListIterator; typedef typename std::unordered_map::iterator MapIterator; @@ -130,7 +130,7 @@ namespace pcpp return m_CacheItemsMap.size(); } - private: + private: std::list m_CacheItemsList; std::unordered_map m_CacheItemsMap; size_t m_MaxSize; diff --git a/Common++/header/Logger.h b/Common++/header/Logger.h index 3208fa6f6f..6973cf530d 100644 --- a/Common++/header/Logger.h +++ b/Common++/header/Logger.h @@ -137,7 +137,7 @@ namespace pcpp */ class Logger { - public: + public: /** * An enum representing the log level. Currently 3 log levels are supported: Error, Info and Debug. Info is the * default log level @@ -283,7 +283,7 @@ namespace pcpp return instance; } - private: + private: bool m_LogsEnabled; Logger::LogLevel m_LogModulesArray[NumOfLogModules]; LogPrinter m_LogPrinter; diff --git a/Common++/header/MacAddress.h b/Common++/header/MacAddress.h index 15b51192cf..894f8cd9b3 100644 --- a/Common++/header/MacAddress.h +++ b/Common++/header/MacAddress.h @@ -23,7 +23,7 @@ namespace pcpp */ class MacAddress { - public: + public: /** * Default constructor for this class. * Initializes the address as 00:00:00:00:00:00. @@ -169,7 +169,7 @@ namespace pcpp */ static MacAddress Zero; - private: + private: uint8_t m_Address[6] = {0}; }; } // namespace pcpp diff --git a/Common++/header/OUILookup.h b/Common++/header/OUILookup.h index 50f49b1c1d..fb49ac236d 100644 --- a/Common++/header/OUILookup.h +++ b/Common++/header/OUILookup.h @@ -23,7 +23,7 @@ namespace pcpp */ class OUILookup { - private: + private: /** * MAC addresses with mask values. For example for a MAC address "XX:XX:XX:XX:X0:00/36" the first element will * be 36, and the second element will be unsigned integer equivalent of "XX:XX:XX:XX:X0:00" and vendor name. @@ -52,7 +52,7 @@ namespace pcpp template int64_t internalParser(T& jsonData); - public: + public: /** * Initialise internal OUI database from a JSON file * @param[in] path Path to OUI database. The database itself is located at diff --git a/Common++/header/PointerVector.h b/Common++/header/PointerVector.h index 29b5cc03df..7c9751990c 100644 --- a/Common++/header/PointerVector.h +++ b/Common++/header/PointerVector.h @@ -22,7 +22,7 @@ namespace pcpp */ template class PointerVector { - public: + public: /** * Iterator object that is used for iterating all elements in the vector */ @@ -216,7 +216,7 @@ namespace pcpp return m_Vector.at(index); } - private: + private: std::vector m_Vector; }; diff --git a/Common++/header/SystemUtils.h b/Common++/header/SystemUtils.h index 4f83c35819..c68ab8f777 100644 --- a/Common++/header/SystemUtils.h +++ b/Common++/header/SystemUtils.h @@ -298,10 +298,10 @@ namespace pcpp */ class AppName { - private: + private: static std::string m_AppName; - public: + public: /** * Static init method which should be called once at the beginning of the main method. * @param[in] argc The argc param from main() @@ -356,7 +356,7 @@ namespace pcpp */ class ApplicationEventHandler { - public: + public: /** * @typedef EventHandlerCallback * The callback to be invoked when the event occurs @@ -383,7 +383,7 @@ namespace pcpp */ void onApplicationInterrupted(EventHandlerCallback handler, void* cookie); - private: + private: EventHandlerCallback m_ApplicationInterruptedHandler; void* m_ApplicationInterruptedCookie; diff --git a/Common++/header/TablePrinter.h b/Common++/header/TablePrinter.h index 5f1887f187..d34ec0df51 100644 --- a/Common++/header/TablePrinter.h +++ b/Common++/header/TablePrinter.h @@ -15,7 +15,7 @@ namespace pcpp */ class TablePrinter { - public: + public: /** * C'tor - get column names and column widths * @param[in] columnNames A vector of strings containing column names @@ -58,7 +58,7 @@ namespace pcpp */ void closeTable(); - private: + private: std::vector m_ColumnNames; std::vector m_ColumnWidths; bool m_FirstRow; From 7c369d0367adbcdf705e948d05018dd3e8dff253 Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Wed, 19 Jun 2024 18:04:07 +0900 Subject: [PATCH 10/13] Cpp11BracedListStyle: false --- .clang-format | 1 + Common++/header/IpAddress.h | 4 +- Common++/header/MacAddress.h | 2 +- Common++/src/OUILookup.cpp | 6 +-- Common++/src/SystemUtils.cpp | 79 ++++++++++++++++++------------------ 5 files changed, 47 insertions(+), 45 deletions(-) diff --git a/.clang-format b/.clang-format index 6538185c89..207fd29f85 100644 --- a/.clang-format +++ b/.clang-format @@ -17,4 +17,5 @@ AlignArrayOfStructures: Left BreakArrays: true SpacesBeforeTrailingComments: 2 IndentAccessModifiers: false +Cpp11BracedListStyle: false ... diff --git a/Common++/header/IpAddress.h b/Common++/header/IpAddress.h index bed86a6df0..3b2fb9da76 100644 --- a/Common++/header/IpAddress.h +++ b/Common++/header/IpAddress.h @@ -180,7 +180,7 @@ namespace pcpp static const IPv4Address MulticastRangeUpperBound; private: - std::array m_Bytes = {0}; + std::array m_Bytes = { 0 }; }; // class IPv4Address // Implementation of inline methods @@ -349,7 +349,7 @@ namespace pcpp static const IPv6Address MulticastRangeLowerBound; private: - std::array m_Bytes = {0}; + std::array m_Bytes = { 0 }; }; // class IPv6Address /** diff --git a/Common++/header/MacAddress.h b/Common++/header/MacAddress.h index 894f8cd9b3..4dc86b7710 100644 --- a/Common++/header/MacAddress.h +++ b/Common++/header/MacAddress.h @@ -170,7 +170,7 @@ namespace pcpp static MacAddress Zero; private: - uint8_t m_Address[6] = {0}; + uint8_t m_Address[6] = { 0 }; }; } // namespace pcpp diff --git a/Common++/src/OUILookup.cpp b/Common++/src/OUILookup.cpp index a76e50b478..d116ee8388 100644 --- a/Common++/src/OUILookup.cpp +++ b/Common++/src/OUILookup.cpp @@ -36,7 +36,7 @@ namespace pcpp subVal["vendors"].is_object()) { int maskValue = subVal["mask"].get(); - vLocalMaskedFilter.push_back({maskValue, {}}); + vLocalMaskedFilter.push_back({ maskValue, {} }); // Parse masked filter for (const auto& subentry : subVal["vendors"].items()) @@ -44,7 +44,7 @@ namespace pcpp if (subentry.value().is_string()) { vLocalMaskedFilter.back().vendorMap.insert( - {std::stoull(subentry.key()), subentry.value()}); + { std::stoull(subentry.key()), subentry.value() }); ++ctrRead; } } @@ -53,7 +53,7 @@ namespace pcpp } vendorMap.insert({ - std::stoull(line.key()), {val["vendor"], vLocalMaskedFilter} + std::stoull(line.key()), { val["vendor"], vLocalMaskedFilter } }); ++ctrRead; } diff --git a/Common++/src/SystemUtils.cpp b/Common++/src/SystemUtils.cpp index 1d46218729..2074b234e2 100644 --- a/Common++/src/SystemUtils.cpp +++ b/Common++/src/SystemUtils.cpp @@ -73,47 +73,48 @@ namespace namespace pcpp { - const SystemCore SystemCores::Core0 = {0x01, 0}; - const SystemCore SystemCores::Core1 = {0x02, 1}; - const SystemCore SystemCores::Core2 = {0x04, 2}; - const SystemCore SystemCores::Core3 = {0x08, 3}; - const SystemCore SystemCores::Core4 = {0x10, 4}; - const SystemCore SystemCores::Core5 = {0x20, 5}; - const SystemCore SystemCores::Core6 = {0x40, 6}; - const SystemCore SystemCores::Core7 = {0x80, 7}; - const SystemCore SystemCores::Core8 = {0x100, 8}; - const SystemCore SystemCores::Core9 = {0x200, 9}; - const SystemCore SystemCores::Core10 = {0x400, 10}; - const SystemCore SystemCores::Core11 = {0x800, 11}; - const SystemCore SystemCores::Core12 = {0x1000, 12}; - const SystemCore SystemCores::Core13 = {0x2000, 13}; - const SystemCore SystemCores::Core14 = {0x4000, 14}; - const SystemCore SystemCores::Core15 = {0x8000, 15}; - const SystemCore SystemCores::Core16 = {0x10000, 16}; - const SystemCore SystemCores::Core17 = {0x20000, 17}; - const SystemCore SystemCores::Core18 = {0x40000, 18}; - const SystemCore SystemCores::Core19 = {0x80000, 19}; - const SystemCore SystemCores::Core20 = {0x100000, 20}; - const SystemCore SystemCores::Core21 = {0x200000, 21}; - const SystemCore SystemCores::Core22 = {0x400000, 22}; - const SystemCore SystemCores::Core23 = {0x800000, 23}; - const SystemCore SystemCores::Core24 = {0x1000000, 24}; - const SystemCore SystemCores::Core25 = {0x2000000, 25}; - const SystemCore SystemCores::Core26 = {0x4000000, 26}; - const SystemCore SystemCores::Core27 = {0x8000000, 27}; - const SystemCore SystemCores::Core28 = {0x10000000, 28}; - const SystemCore SystemCores::Core29 = {0x20000000, 29}; - const SystemCore SystemCores::Core30 = {0x40000000, 30}; - const SystemCore SystemCores::Core31 = {0x80000000, 31}; + const SystemCore SystemCores::Core0 = { 0x01, 0 }; + const SystemCore SystemCores::Core1 = { 0x02, 1 }; + const SystemCore SystemCores::Core2 = { 0x04, 2 }; + const SystemCore SystemCores::Core3 = { 0x08, 3 }; + const SystemCore SystemCores::Core4 = { 0x10, 4 }; + const SystemCore SystemCores::Core5 = { 0x20, 5 }; + const SystemCore SystemCores::Core6 = { 0x40, 6 }; + const SystemCore SystemCores::Core7 = { 0x80, 7 }; + const SystemCore SystemCores::Core8 = { 0x100, 8 }; + const SystemCore SystemCores::Core9 = { 0x200, 9 }; + const SystemCore SystemCores::Core10 = { 0x400, 10 }; + const SystemCore SystemCores::Core11 = { 0x800, 11 }; + const SystemCore SystemCores::Core12 = { 0x1000, 12 }; + const SystemCore SystemCores::Core13 = { 0x2000, 13 }; + const SystemCore SystemCores::Core14 = { 0x4000, 14 }; + const SystemCore SystemCores::Core15 = { 0x8000, 15 }; + const SystemCore SystemCores::Core16 = { 0x10000, 16 }; + const SystemCore SystemCores::Core17 = { 0x20000, 17 }; + const SystemCore SystemCores::Core18 = { 0x40000, 18 }; + const SystemCore SystemCores::Core19 = { 0x80000, 19 }; + const SystemCore SystemCores::Core20 = { 0x100000, 20 }; + const SystemCore SystemCores::Core21 = { 0x200000, 21 }; + const SystemCore SystemCores::Core22 = { 0x400000, 22 }; + const SystemCore SystemCores::Core23 = { 0x800000, 23 }; + const SystemCore SystemCores::Core24 = { 0x1000000, 24 }; + const SystemCore SystemCores::Core25 = { 0x2000000, 25 }; + const SystemCore SystemCores::Core26 = { 0x4000000, 26 }; + const SystemCore SystemCores::Core27 = { 0x8000000, 27 }; + const SystemCore SystemCores::Core28 = { 0x10000000, 28 }; + const SystemCore SystemCores::Core29 = { 0x20000000, 29 }; + const SystemCore SystemCores::Core30 = { 0x40000000, 30 }; + const SystemCore SystemCores::Core31 = { 0x80000000, 31 }; const SystemCore SystemCores::IdToSystemCore[MAX_NUM_OF_CORES] = { - SystemCores::Core0, SystemCores::Core1, SystemCores::Core2, SystemCores::Core3, SystemCores::Core4, - SystemCores::Core5, SystemCores::Core6, SystemCores::Core7, SystemCores::Core8, SystemCores::Core9, - SystemCores::Core10, SystemCores::Core11, SystemCores::Core12, SystemCores::Core13, SystemCores::Core14, - SystemCores::Core15, SystemCores::Core16, SystemCores::Core17, SystemCores::Core18, SystemCores::Core19, - SystemCores::Core20, SystemCores::Core21, SystemCores::Core22, SystemCores::Core23, SystemCores::Core24, - SystemCores::Core25, SystemCores::Core26, SystemCores::Core27, SystemCores::Core28, SystemCores::Core29, - SystemCores::Core30, SystemCores::Core31}; + SystemCores::Core0, SystemCores::Core1, SystemCores::Core2, SystemCores::Core3, SystemCores::Core4, + SystemCores::Core5, SystemCores::Core6, SystemCores::Core7, SystemCores::Core8, SystemCores::Core9, + SystemCores::Core10, SystemCores::Core11, SystemCores::Core12, SystemCores::Core13, SystemCores::Core14, + SystemCores::Core15, SystemCores::Core16, SystemCores::Core17, SystemCores::Core18, SystemCores::Core19, + SystemCores::Core20, SystemCores::Core21, SystemCores::Core22, SystemCores::Core23, SystemCores::Core24, + SystemCores::Core25, SystemCores::Core26, SystemCores::Core27, SystemCores::Core28, SystemCores::Core29, + SystemCores::Core30, SystemCores::Core31 + }; int getNumOfCores() { From 870534729f37ed114364d77bff45ffa9b1a1c203 Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Thu, 20 Jun 2024 17:20:09 +0900 Subject: [PATCH 11/13] fix ; --- Common++/header/MacAddress.h | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/Common++/header/MacAddress.h b/Common++/header/MacAddress.h index 4dc86b7710..c8adcc3043 100644 --- a/Common++/header/MacAddress.h +++ b/Common++/header/MacAddress.h @@ -1,12 +1,12 @@ #pragma once -#include -#include -#include -#include #include +#include #include #include +#include +#include +#include /// @file @@ -54,7 +54,9 @@ namespace pcpp * @param[in] addr the string representing the MAC address in format "00:00:00:00:00:00" */ template ::value>::type> - MacAddress(const T& addr) : MacAddress(static_cast(addr)){}; + MacAddress(const T& addr) : MacAddress(static_cast(addr)) + { + } /** * A constructor that creates an instance of 6 bytes representing the MAC address From f79b93e53baa036494f1d72dff952f758bfd7a1c Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Thu, 20 Jun 2024 17:25:08 +0900 Subject: [PATCH 12/13] change to use `AlignWithSpaces` --- .clang-format | 2 +- Common++/header/LRUList.h | 2 +- Common++/src/IpAddress.cpp | 4 ++-- Common++/src/Logger.cpp | 2 +- Common++/src/OUILookup.cpp | 4 ++-- Common++/src/SystemUtils.cpp | 6 +++--- Common++/src/TablePrinter.cpp | 4 ++-- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.clang-format b/.clang-format index 207fd29f85..86445568c7 100644 --- a/.clang-format +++ b/.clang-format @@ -1,6 +1,6 @@ --- BasedOnStyle: Microsoft -UseTab: ForIndentation +UseTab: AlignWithSpaces BreakBeforeBraces: Allman AllowShortFunctionsOnASingleLine: None NamespaceIndentation: All diff --git a/Common++/header/LRUList.h b/Common++/header/LRUList.h index 081fd2434b..cf0ebe7702 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -56,7 +56,7 @@ namespace pcpp // Inserting a new element. If an element with an equivalent key already exists the method returns an // iterator to the element that prevented the insertion std::pair pair = - m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin())); + m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin())); if (pair.second == false) // already exists { m_CacheItemsList.erase(pair.first->second); diff --git a/Common++/src/IpAddress.cpp b/Common++/src/IpAddress.cpp index 2c2f439361..366aeb8a3b 100644 --- a/Common++/src/IpAddress.cpp +++ b/Common++/src/IpAddress.cpp @@ -237,7 +237,7 @@ namespace pcpp if (netmaskStr.empty()) { throw std::invalid_argument( - "The input should be in the format of
/ or
/"); + "The input should be in the format of
/ or
/"); } IPv4Address networkPrefix; @@ -443,7 +443,7 @@ namespace pcpp if (netmaskStr.empty()) { throw std::invalid_argument( - "The input should be in the format of
/ or
/"); + "The input should be in the format of
/ or
/"); } IPv6Address networkPrefix; diff --git a/Common++/src/Logger.cpp b/Common++/src/Logger.cpp index cbedaba566..462b279b0e 100644 --- a/Common++/src/Logger.cpp +++ b/Common++/src/Logger.cpp @@ -30,7 +30,7 @@ namespace pcpp std::ostringstream sstream; sstream << file << ": " << method << ":" << line; std::cout << std::left << "[" << std::setw(5) << Logger::logLevelAsString(logLevel) << ": " << std::setw(45) - << sstream.str() << "] " << logMessage << std::endl; + << sstream.str() << "] " << logMessage << std::endl; } std::ostringstream* Logger::internalCreateLogStream() diff --git a/Common++/src/OUILookup.cpp b/Common++/src/OUILookup.cpp index d116ee8388..e6af2b3575 100644 --- a/Common++/src/OUILookup.cpp +++ b/Common++/src/OUILookup.cpp @@ -44,7 +44,7 @@ namespace pcpp if (subentry.value().is_string()) { vLocalMaskedFilter.back().vendorMap.insert( - { std::stoull(subentry.key()), subentry.value() }); + { std::stoull(subentry.key()), subentry.value() }); ++ctrRead; } } @@ -53,7 +53,7 @@ namespace pcpp } vendorMap.insert({ - std::stoull(line.key()), { val["vendor"], vLocalMaskedFilter } + std::stoull(line.key()), { val["vendor"], vLocalMaskedFilter } }); ++ctrRead; } diff --git a/Common++/src/SystemUtils.cpp b/Common++/src/SystemUtils.cpp index 2074b234e2..06bb8bd7a5 100644 --- a/Common++/src/SystemUtils.cpp +++ b/Common++/src/SystemUtils.cpp @@ -321,7 +321,7 @@ namespace pcpp { if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != NULL) ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler( - ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); + ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); return TRUE; } @@ -347,7 +347,7 @@ namespace pcpp if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != nullptr) ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler( - ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); + ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler = nullptr; @@ -362,7 +362,7 @@ namespace pcpp #endif ApplicationEventHandler::ApplicationEventHandler() - : m_ApplicationInterruptedHandler(nullptr), m_ApplicationInterruptedCookie(nullptr) + : m_ApplicationInterruptedHandler(nullptr), m_ApplicationInterruptedCookie(nullptr) { } diff --git a/Common++/src/TablePrinter.cpp b/Common++/src/TablePrinter.cpp index 8c424cd000..f31928acb4 100644 --- a/Common++/src/TablePrinter.cpp +++ b/Common++/src/TablePrinter.cpp @@ -13,8 +13,8 @@ namespace pcpp { TablePrinter::TablePrinter(std::vector columnNames, std::vector columnWidths) - : m_ColumnNames(std::move(columnNames)), m_ColumnWidths(std::move(columnWidths)), m_FirstRow(true), - m_TableClosed(false) + : m_ColumnNames(std::move(columnNames)), m_ColumnWidths(std::move(columnWidths)), m_FirstRow(true), + m_TableClosed(false) { if (m_ColumnWidths.size() != m_ColumnNames.size()) { From 9da0f9176810f0b007699a2f05ec49e99240a9d5 Mon Sep 17 00:00:00 2001 From: "anchi.liu" Date: Thu, 20 Jun 2024 18:51:49 +0900 Subject: [PATCH 13/13] BreakBeforeBraces: Custom --- .clang-format | 5 ++++- Common++/header/IpAddress.h | 24 ++++++++---------------- Common++/header/MacAddress.h | 3 +-- Common++/header/PointerVector.h | 3 +-- Common++/src/SystemUtils.cpp | 3 +-- 5 files changed, 15 insertions(+), 23 deletions(-) diff --git a/.clang-format b/.clang-format index 86445568c7..9750e9567d 100644 --- a/.clang-format +++ b/.clang-format @@ -1,7 +1,6 @@ --- BasedOnStyle: Microsoft UseTab: AlignWithSpaces -BreakBeforeBraces: Allman AllowShortFunctionsOnASingleLine: None NamespaceIndentation: All SortIncludes: false @@ -18,4 +17,8 @@ BreakArrays: true SpacesBeforeTrailingComments: 2 IndentAccessModifiers: false Cpp11BracedListStyle: false +BreakBeforeBraces: Custom +BraceWrapping: + SplitEmptyFunction: false + AfterCaseLabel: true ... diff --git a/Common++/header/IpAddress.h b/Common++/header/IpAddress.h index 3b2fb9da76..243dae0ef9 100644 --- a/Common++/header/IpAddress.h +++ b/Common++/header/IpAddress.h @@ -59,8 +59,7 @@ namespace pcpp * @param[in] bytes The address as 4-byte standard array in network byte order */ IPv4Address(const std::array& bytes) : m_Bytes(bytes) - { - } + {} /** * A constructor that creates an instance of the class out of std::string value. @@ -218,8 +217,7 @@ namespace pcpp * @param[in] bytes The address as 16-byte standard array in network byte order */ IPv6Address(const std::array& bytes) : m_Bytes(bytes) - { - } + {} /** * A constructor that creates an instance of the class out of std::string value. @@ -378,24 +376,21 @@ namespace pcpp * A default constructor that creates an instance of the class with unspecified IPv4 address */ IPAddress() : m_Type(IPv4AddressType) - { - } + {} /** * A constructor that creates an instance of the class out of IPv4Address. * @param[in] addr A const reference to instance of IPv4Address */ IPAddress(const IPv4Address& addr) : m_Type(IPv4AddressType), m_IPv4(addr) - { - } + {} /** * A constructor that creates an instance of the class out of IPv6Address. * @param[in] addr A const reference to instance of IPv6Address */ IPAddress(const IPv6Address& addr) : m_Type(IPv6AddressType), m_IPv6(addr) - { - } + {} /** * A constructor that creates an instance of the class out of std::string value @@ -567,8 +562,7 @@ namespace pcpp * @param address An address representing the network prefix. */ explicit IPv4Network(const IPv4Address& address) : IPv4Network(address, 32u) - { - } + {} /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -685,8 +679,7 @@ namespace pcpp * @param address An address representing the network prefix. */ explicit IPv6Network(const IPv6Address& address) : IPv6Network(address, 128u) - { - } + {} /** * A constructor that creates an instance of the class out of an address representing the network prefix @@ -803,8 +796,7 @@ namespace pcpp * @param address An address representing the network prefix. */ explicit IPNetwork(const IPAddress& address) : IPNetwork(address, address.isIPv4() ? 32u : 128u) - { - } + {} /** * A constructor that creates an instance of the class out of an address representing the network prefix diff --git a/Common++/header/MacAddress.h b/Common++/header/MacAddress.h index c8adcc3043..29333aa02d 100644 --- a/Common++/header/MacAddress.h +++ b/Common++/header/MacAddress.h @@ -55,8 +55,7 @@ namespace pcpp */ template ::value>::type> MacAddress(const T& addr) : MacAddress(static_cast(addr)) - { - } + {} /** * A constructor that creates an instance of 6 bytes representing the MAC address diff --git a/Common++/header/PointerVector.h b/Common++/header/PointerVector.h index 7c9751990c..ef0c26f012 100644 --- a/Common++/header/PointerVector.h +++ b/Common++/header/PointerVector.h @@ -37,8 +37,7 @@ namespace pcpp * A constructor that create an empty instance of this object */ PointerVector() - { - } + {} /** * A destructor for this class. The destructor frees all elements that are binded to the vector diff --git a/Common++/src/SystemUtils.cpp b/Common++/src/SystemUtils.cpp index 06bb8bd7a5..c3ffbd109a 100644 --- a/Common++/src/SystemUtils.cpp +++ b/Common++/src/SystemUtils.cpp @@ -363,8 +363,7 @@ namespace pcpp ApplicationEventHandler::ApplicationEventHandler() : m_ApplicationInterruptedHandler(nullptr), m_ApplicationInterruptedCookie(nullptr) - { - } + {} void ApplicationEventHandler::onApplicationInterrupted(EventHandlerCallback handler, void* cookie) {