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..9750e9567d 100644 --- a/.clang-format +++ b/.clang-format @@ -1,7 +1,24 @@ --- BasedOnStyle: Microsoft -UseTab: Always -AllowShortFunctionsOnASingleLine: All +UseTab: AlignWithSpaces +AllowShortFunctionsOnASingleLine: None NamespaceIndentation: All - +SortIncludes: false +IndentPPDirectives: AfterHash +IndentWidth: 4 +AllowShortBlocksOnASingleLine: Never +PointerAlignment: Left +AccessModifierOffset: -4 +AlignTrailingComments: true +AllowShortEnumsOnASingleLine: false +BreakStringLiterals: true +AlignArrayOfStructures: Left +BreakArrays: true +SpacesBeforeTrailingComments: 2 +IndentAccessModifiers: false +Cpp11BracedListStyle: false +BreakBeforeBraces: Custom +BraceWrapping: + SplitEmptyFunction: false + AfterCaseLabel: true ... diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index ccfd2ce65a..f3044812e2 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -29,7 +29,7 @@ jobs: - name: Install dependencies run: | apk update && apk add cppcheck python3-dev - python3 -m pip install cmake-format + python3 -m pip install cmake-format 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: diff --git a/Common++/header/DeprecationUtils.h b/Common++/header/DeprecationUtils.h index afdc20cb18..2d600d88d6 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..8dd1e83b85 100644 --- a/Common++/header/GeneralUtils.h +++ b/Common++/header/GeneralUtils.h @@ -17,10 +17,10 @@ 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); @@ -31,18 +31,18 @@ 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); /** - * 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 @@ -55,9 +55,8 @@ namespace pcpp * 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..243dae0ef9 100644 --- a/Common++/header/IpAddress.h +++ b/Common++/header/IpAddress.h @@ -10,7 +10,6 @@ /// @file - /** * \namespace pcpp * \brief The main namespace for the PcapPlusPlus lib @@ -41,19 +40,26 @@ 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. @@ -71,12 +77,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 @@ -93,7 +105,10 @@ 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 @@ -106,7 +121,8 @@ namespace pcpp 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,7 +132,10 @@ 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. @@ -160,9 +179,8 @@ namespace pcpp static const IPv4Address MulticastRangeUpperBound; private: - std::array m_Bytes = {0}; - }; // class IPv4Address - + std::array m_Bytes = { 0 }; + }; // class IPv4Address // Implementation of inline methods @@ -189,13 +207,17 @@ 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. @@ -209,13 +231,19 @@ namespace pcpp * 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,22 +262,30 @@ 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 @@ -263,7 +299,10 @@ namespace pcpp * 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. @@ -295,7 +334,8 @@ namespace pcpp 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; @@ -307,9 +347,8 @@ namespace pcpp static const IPv6Address MulticastRangeLowerBound; private: - std::array m_Bytes = {0}; - }; // class IPv6Address - + std::array m_Bytes = { 0 }; + }; // class IPv6Address /** * @class IPAddress @@ -336,19 +375,22 @@ 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 @@ -376,46 +418,70 @@ namespace pcpp * 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 * @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 @@ -436,7 +502,10 @@ namespace pcpp * @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: uint8_t m_Type; @@ -444,7 +513,6 @@ namespace pcpp IPv6Address m_IPv6; }; - // implementation of inline methods bool IPAddress::operator==(const IPAddress& rhs) const @@ -457,7 +525,7 @@ namespace pcpp 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 @@ -480,7 +548,6 @@ namespace pcpp return *this; } - /** * @class IPv4Network * A class representing IPv4 network definition @@ -494,7 +561,8 @@ namespace pcpp * * @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 @@ -538,12 +606,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 @@ -591,7 +665,6 @@ namespace pcpp void initFromAddressAndNetmask(const IPv4Address& address, const IPv4Address& netmaskAddress); }; - /** * @class IPv6Network * A class representing IPv6 network definition @@ -605,7 +678,8 @@ namespace pcpp * * @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 @@ -649,17 +723,23 @@ 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 - * 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; /** @@ -702,7 +782,6 @@ namespace pcpp void initFromAddressAndNetmask(const IPv6Address& address, const IPv6Address& netmaskAddress); }; - /** * @class IPNetwork * A class representing version independent IP network definition, both IPv4 and IPv6 are included @@ -716,14 +795,16 @@ namespace pcpp * * @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) @@ -871,8 +952,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 +963,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 +986,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,7 +997,8 @@ 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()); } /** @@ -996,7 +1082,7 @@ namespace pcpp 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) { diff --git a/Common++/header/IpAddressUtils.h b/Common++/header/IpAddressUtils.h index f561a634a7..a7b6ac7041 100644 --- a/Common++/header/IpAddressUtils.h +++ b/Common++/header/IpAddressUtils.h @@ -26,17 +26,26 @@ namespace pcpp * 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 @@ -47,17 +56,26 @@ namespace pcpp * 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 @@ -68,17 +86,26 @@ namespace pcpp * 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 @@ -89,15 +116,24 @@ namespace pcpp * 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..826808b7ab 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 @@ -49,7 +49,6 @@ const char* inet_ntop(int af, const void* src, char* dst, size_t size); int inet_pton(int af, const char* src, void* dst); #endif - /** * \namespace pcpp * \brief The main namespace for the PcapPlusPlus lib @@ -93,7 +92,8 @@ namespace pcpp * @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); @@ -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 89eb1c9470..cf0ebe7702 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -1,10 +1,10 @@ #pragma once -#include #include +#include #if __cplusplus > 199711L || _MSC_VER >= 1800 -#include +# include #endif /// @file @@ -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: - typedef typename std::list::iterator ListIterator; typedef typename std::unordered_map::iterator MapIterator; @@ -41,22 +39,25 @@ namespace pcpp } /** - * 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) { 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())); - if (pair.second == false) // already exists + // 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); pair.first->second = m_CacheItemsList.begin(); @@ -116,12 +117,18 @@ 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: std::list m_CacheItemsList; @@ -129,4 +136,4 @@ namespace pcpp size_t m_MaxSize; }; -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/header/Logger.h b/Common++/header/Logger.h index ad73716274..6973cf530d 100644 --- a/Common++/header/Logger.h +++ b/Common++/header/Logger.h @@ -7,34 +7,37 @@ #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) 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++) - 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 }; @@ -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. * @@ -135,13 +139,14 @@ namespace pcpp { 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 + Error, ///< Error 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. @@ -167,84 +173,116 @@ 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 * @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 instance; return instance; } + private: bool m_LogsEnabled; Logger::LogLevel m_LogModulesArray[NumOfLogModules]; @@ -255,6 +293,7 @@ namespace pcpp // 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 854e03ffe1..29333aa02d 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 @@ -36,12 +36,15 @@ 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); @@ -50,9 +53,9 @@ namespace pcpp * 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 +66,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 +85,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 +97,30 @@ 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) { - 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 +133,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 @@ -131,7 +145,8 @@ 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 @@ -145,7 +160,10 @@ 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" @@ -153,9 +171,9 @@ namespace pcpp static MacAddress Zero; private: - uint8_t m_Address[6] = {0}; + uint8_t m_Address[6] = { 0 }; }; -} // namespace pcpp +} // namespace pcpp inline std::ostream& operator<<(std::ostream& os, const pcpp::MacAddress& macAddress) { diff --git a/Common++/header/OUILookup.h b/Common++/header/OUILookup.h index ddc84e0d71..fb49ac236d 100644 --- a/Common++/header/OUILookup.h +++ b/Common++/header/OUILookup.h @@ -15,14 +15,15 @@ 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 { - 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. @@ -49,23 +50,22 @@ namespace pcpp /// Internal vendor list for MAC addresses OUIVendorMap vendorMap; - template - int64_t internalParser(T &jsonData); - - public: + 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 = ""); + 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 ceb813ba39..22edfc4a97 100644 --- a/Common++/header/PcapPlusPlusVersion.h +++ b/Common++/header/PcapPlusPlusVersion.h @@ -10,27 +10,37 @@ */ 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; } + 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; } + 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 @@ -48,4 +58,4 @@ namespace pcpp */ std::string getGitInfo(); -} +} // namespace pcpp diff --git a/Common++/header/PointerVector.h b/Common++/header/PointerVector.h index d73d60238f..ef0c26f012 100644 --- a/Common++/header/PointerVector.h +++ b/Common++/header/PointerVector.h @@ -15,12 +15,12 @@ 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: /** @@ -36,7 +36,8 @@ namespace pcpp /** * 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,7 +52,8 @@ 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) { @@ -97,56 +99,80 @@ 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(); } + // inline size_t size() { return m_Vector.size(); } /** * 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 * @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,7 +183,8 @@ 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) { @@ -192,4 +219,4 @@ namespace pcpp std::vector m_Vector; }; -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/header/SystemUtils.h b/Common++/header/SystemUtils.h index ad03d1dec8..c68ab8f777 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,13 @@ 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,22 +203,19 @@ namespace pcpp */ CoreMask getCoreMaskForAllMachineCores(); - /** * Create a core mask from a vector of system cores * @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 @@ -237,11 +237,11 @@ namespace pcpp * @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 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 @@ -249,15 +249,15 @@ namespace pcpp 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,8 +292,9 @@ 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 { @@ -333,7 +334,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,13 +343,16 @@ 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 { @@ -372,8 +377,9 @@ 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); @@ -391,4 +397,4 @@ namespace pcpp #endif }; -} // namespace pcpp +} // namespace pcpp diff --git a/Common++/header/TablePrinter.h b/Common++/header/TablePrinter.h index d4011ce54d..d34ec0df51 100644 --- a/Common++/header/TablePrinter.h +++ b/Common++/header/TablePrinter.h @@ -53,8 +53,8 @@ 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(); @@ -70,4 +70,4 @@ namespace pcpp void printHeadline(); }; -} +} // namespace pcpp diff --git a/Common++/header/TimespecTimeval.h b/Common++/header/TimespecTimeval.h index 7a496c150e..52c291778d 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..51c6c50c07 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..366aeb8a3b 100644 --- a/Common++/src/IpAddress.cpp +++ b/Common++/src/IpAddress.cpp @@ -14,10 +14,9 @@ // for AF_INET, AF_INET6 #if !defined(_WIN32) -#include +# include #endif - namespace pcpp { @@ -32,7 +31,6 @@ namespace pcpp // IPv4Address // ~~~~~~~~~~~ - std::string IPv4Address::toString() const { char addrBuffer[INET_ADDRSTRLEN]; @@ -43,10 +41,10 @@ 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) @@ -57,13 +55,11 @@ namespace pcpp } } - bool IPv4Address::matchNetwork(const IPv4Network& network) const { return network.includes(*this); } - bool IPv4Address::matchNetwork(const std::string& network) const { try @@ -84,12 +80,10 @@ namespace pcpp return inet_pton(AF_INET, addrAsString.data(), &(sa_in.sin_addr)) > 0; } - // ~~~~~~~~~~~ // IPv6Address // ~~~~~~~~~~~ - std::string IPv6Address::toString() const { char addrBuffer[INET6_ADDRSTRLEN]; @@ -100,22 +94,19 @@ namespace pcpp return std::string(); } - bool IPv6Address::isMulticast() const { return !operator<(MulticastRangeLowerBound); } - 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 { const size_t addrLen = m_Bytes.size() * sizeof(uint8_t); @@ -124,13 +115,11 @@ namespace pcpp memcpy(*arr, m_Bytes.data(), addrLen); } - - bool IPv6Address::matchNetwork(const IPv6Network &network) const + bool IPv6Address::matchNetwork(const IPv6Network& network) const { return network.includes(*this); } - bool IPv6Address::matchNetwork(const std::string& network) const { try @@ -151,12 +140,10 @@ namespace pcpp return inet_pton(AF_INET6, addrAsString.data(), &(sa_in6.sin6_addr)) > 0; } - // ~~~~~~~~~ // IPAddress // ~~~~~~~~~ - IPAddress::IPAddress(const std::string& addrAsString) { if (IPv4Address::isValidIPv4Address(addrAsString)) @@ -175,12 +162,10 @@ namespace pcpp } } - // ~~~~~~~~~~~ // IPv4Network // ~~~~~~~~~~~ - bool IPv4Network::isValidNetmask(const IPv4Address& maskAddress) { if (maskAddress == IPv4Address::Zero) @@ -202,21 +187,18 @@ namespace pcpp } } - 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) { m_Mask = netmaskAddress.toInt(); m_NetworkPrefix = address.toInt() & m_Mask; } - IPv4Network::IPv4Network(const IPv4Address& address, uint8_t prefixLen) { if (prefixLen > 32) @@ -227,7 +209,6 @@ namespace pcpp initFromAddressAndPrefixLength(address, prefixLen); } - IPv4Network::IPv4Network(const IPv4Address& address, const std::string& netmask) { IPv4Address netmaskAddr; @@ -235,7 +216,7 @@ namespace pcpp { netmaskAddr = IPv4Address(netmask); } - catch(const std::exception&) + catch (const std::exception&) { throw std::invalid_argument("Netmask is not valid IPv4 format: " + netmask); } @@ -246,7 +227,6 @@ namespace pcpp initFromAddressAndNetmask(address, netmaskAddr); } - IPv4Network::IPv4Network(const std::string& addressAndNetmask) { std::stringstream stream(addressAndNetmask); @@ -256,7 +236,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; @@ -298,42 +279,36 @@ 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 { return (address.toInt() & m_Mask) == m_NetworkPrefix; } - bool IPv4Network::includes(const IPv4Network& network) const { uint32_t lowestAddress = network.m_NetworkPrefix; @@ -341,7 +316,6 @@ namespace pcpp return ((lowestAddress & m_Mask) == m_NetworkPrefix && (highestAddress & m_Mask) == m_NetworkPrefix); } - std::string IPv4Network::toString() const { std::ostringstream stream; @@ -349,23 +323,20 @@ namespace pcpp return stream.str(); } - // ~~~~~~~~~~~ // IPv6Network // ~~~~~~~~~~~ - #define IPV6_ADDR_SIZE 16 - bool IPv6Network::isValidNetmask(const IPv6Address& netmask) { - if(netmask == IPv6Address::Zero) + 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++) { @@ -382,7 +353,8 @@ namespace pcpp return false; } expectingValue = 0; - } else if (expectingValue == 0 && curByte != 0) + } + else if (expectingValue == 0 && curByte != 0) { return false; } @@ -391,8 +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; @@ -422,8 +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); @@ -435,8 +405,7 @@ namespace pcpp } } - - IPv6Network::IPv6Network(const IPv6Address &address, uint8_t prefixLen) + IPv6Network::IPv6Network(const IPv6Address& address, uint8_t prefixLen) { if (prefixLen > 128) { @@ -446,15 +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); } @@ -465,8 +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; @@ -475,14 +442,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 +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); } @@ -515,7 +484,6 @@ namespace pcpp } } - uint8_t IPv6Network::getPrefixLen() const { uint8_t result = 0; @@ -527,7 +495,6 @@ namespace pcpp return result; } - IPv6Address IPv6Network::getLowestAddress() const { if (getPrefixLen() == 128) @@ -541,7 +508,6 @@ namespace pcpp return lowestAddress; } - IPv6Address IPv6Network::getHighestAddress() const { uint8_t result[IPV6_ADDR_SIZE]; @@ -554,7 +520,6 @@ namespace pcpp return result; } - uint64_t IPv6Network::getTotalAddressCount() const { int numOfBitset = 0; @@ -571,7 +536,6 @@ namespace pcpp return 1ULL << numOfBitset; } - bool IPv6Network::includes(const IPv6Address& address) const { uint8_t maskedBytes[IPV6_ADDR_SIZE]; @@ -584,13 +548,11 @@ namespace pcpp return memcmp(m_NetworkPrefix, maskedBytes, IPV6_ADDR_SIZE) == 0; } - bool IPv6Network::includes(const IPv6Network& network) const { return includes(network.getLowestAddress()) && includes(network.getHighestAddress()); } - std::string IPv6Network::toString() const { std::ostringstream stream; @@ -598,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 c72c944cb5..a65941cbf5 100644 --- a/Common++/src/IpAddressUtils.cpp +++ b/Common++/src/IpAddressUtils.cpp @@ -1,7 +1,7 @@ #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 { @@ -32,4 +32,4 @@ namespace pcpp } return false; } -} +} // namespace pcpp diff --git a/Common++/src/IpUtils.cpp b/Common++/src/IpUtils.cpp index 04337eae30..c6530a43e8 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 @@ -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,14 +107,14 @@ 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 + } // 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)) @@ -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; @@ -269,7 +269,7 @@ 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) { @@ -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,13 +314,11 @@ 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; + const char* curtok; int ch, saw_xdigit; u_int val; @@ -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,7 +408,6 @@ inet_pton6(const char* src, uint8_t* dst) return (1); } - const char* inet_ntop(int af, const void* src, char* dst, size_t size) { switch (af) @@ -428,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/Logger.cpp b/Common++/src/Logger.cpp index f78641caff..462b279b0e 100644 --- a/Common++/src/Logger.cpp +++ b/Common++/src/Logger.cpp @@ -4,55 +4,53 @@ 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) + std::ostringstream* Logger::internalCreateLogStream() { - m_LastError = logMessage; + return new std::ostringstream(); } - if (m_LogsEnabled) + + 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 +} // namespace pcpp diff --git a/Common++/src/MacAddress.cpp b/Common++/src/MacAddress.cpp index bc61c41861..f9fcc9bcc1 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 +} // namespace pcpp diff --git a/Common++/src/OUILookup.cpp b/Common++/src/OUILookup.cpp index 0d5f5fc4e4..e6af2b3575 100644 --- a/Common++/src/OUILookup.cpp +++ b/Common++/src/OUILookup.cpp @@ -8,103 +8,104 @@ 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 +} // namespace pcpp diff --git a/Common++/src/PcapPlusPlusVersion.cpp b/Common++/src/PcapPlusPlusVersion.cpp index 4038147395..16f0ca3b95 100644 --- a/Common++/src/PcapPlusPlusVersion.cpp +++ b/Common++/src/PcapPlusPlusVersion.cpp @@ -3,25 +3,25 @@ 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..c3ffbd109a 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,31 +14,31 @@ #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 -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,350 +61,324 @@ namespace */ struct PcloseDeleter { - void operator()(FILE* ptr) const { PCLOSE(ptr); } + void operator()(FILE* ptr) const + { + PCLOSE(ptr); + } }; -} // namespace +} // namespace /// @endcond 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) +# define CLOCK_GETTIME_BILLION (1E9) - static BOOL clock_gettime_first_time = 1; - static LARGE_INTEGER clock_gettime_counts_per_sec; + static BOOL clock_gettime_first_time = 1; + static LARGE_INTEGER clock_gettime_counts_per_sec; - LARGE_INTEGER count ; + LARGE_INTEGER count; - if (clock_gettime_first_time) - { - clock_gettime_first_time = 0; - - 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 +#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) - { - case SIGINT: + void ApplicationEventHandler::handlerRoutine(int signum) { - // 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 +} // namespace pcpp diff --git a/Common++/src/TablePrinter.cpp b/Common++/src/TablePrinter.cpp index 153801def2..f31928acb4 100644 --- a/Common++/src/TablePrinter.cpp +++ b/Common++/src/TablePrinter.cpp @@ -12,121 +12,122 @@ 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(); -} -bool TablePrinter::printRow(std::vector values) -{ - // if table is already closed return false - if (m_TableClosed) + TablePrinter::~TablePrinter() { - PCPP_LOG_ERROR("Table is closed"); - return false; + closeTable(); } - if (values.size() != m_ColumnWidths.size()) + bool TablePrinter::printRow(std::vector values) { - 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