From 7e9c12ff779db3841f4ace2116494df344ee3660 Mon Sep 17 00:00:00 2001 From: egecetin Date: Sat, 9 Nov 2024 11:04:13 +0300 Subject: [PATCH] clang-tidy fixes for Common++ --- .clang-format | 1 + .clang-tidy | 25 +++++++++++++ Common++/header/GeneralUtils.h | 2 +- Common++/header/IpAddress.h | 58 ++++++++++++++---------------- Common++/header/IpUtils.h | 4 +-- Common++/header/LRUList.h | 22 ++++++------ Common++/header/Logger.h | 17 ++++----- Common++/header/MacAddress.h | 4 +-- Common++/header/OUILookup.h | 2 +- Common++/header/PointerVector.h | 17 +++++---- Common++/header/SystemUtils.h | 11 +++--- Common++/src/GeneralUtils.cpp | 23 +++++++++--- Common++/src/IpAddress.cpp | 64 ++++++++++++++++++--------------- Common++/src/IpUtils.cpp | 20 +++++++++-- Common++/src/Logger.cpp | 7 ++-- Common++/src/OUILookup.cpp | 26 ++++++++++---- Common++/src/SystemUtils.cpp | 33 +++++++++++------ Common++/src/TablePrinter.cpp | 10 ++++-- 18 files changed, 218 insertions(+), 128 deletions(-) create mode 100644 .clang-tidy diff --git a/.clang-format b/.clang-format index d8067eaade..6a60aeb32b 100644 --- a/.clang-format +++ b/.clang-format @@ -21,4 +21,5 @@ BreakBeforeBraces: Custom BraceWrapping: SplitEmptyFunction: false AfterCaseLabel: true +QualifierAlignment: Left ... diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000000..1859149b46 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,25 @@ +Checks: 'cert-*, +clang-analyzer-*, +concurrency-*, +cppcoreguidelines-*, +misc-*, +modernize-*, +performance-*, +portability-*, +readability-*, +-clang-analyzer-optin.cplusplus.VirtualCall, +-cppcoreguidelines-avoid-do-while, +-cppcoreguidelines-avoid-magic-numbers, +-cppcoreguidelines-owning-memory, +-cppcoreguidelines-pro-bounds-array-to-pointer-decay, +-cppcoreguidelines-pro-bounds-pointer-arithmetic, +-cppcoreguidelines-pro-type-reinterpret-cast, +-cppcoreguidelines-pro-type-const-cast, +-cppcoreguidelines-pro-type-vararg, +-modernize-use-trailing-return-type, +-misc-header-include-cycle, +-misc-include-cleaner, +-misc-no-recursion, +-misc-use-anonymous-namespace, +-readability-function-cognitive-complexity, +-readability-magic-numbers' diff --git a/Common++/header/GeneralUtils.h b/Common++/header/GeneralUtils.h index acb4d93589..f9da6b09b9 100644 --- a/Common++/header/GeneralUtils.h +++ b/Common++/header/GeneralUtils.h @@ -1,7 +1,7 @@ #pragma once #include -#include +#include #include /// @file diff --git a/Common++/header/IpAddress.h b/Common++/header/IpAddress.h index 243dae0ef9..8a27ebd00b 100644 --- a/Common++/header/IpAddress.h +++ b/Common++/header/IpAddress.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include +#include #include #include #include @@ -186,7 +186,7 @@ namespace pcpp uint32_t IPv4Address::toInt() const { - uint32_t addr; + uint32_t addr = 0; memcpy(&addr, m_Bytes.data(), m_Bytes.size() * sizeof(uint8_t)); return addr; } @@ -518,7 +518,9 @@ namespace pcpp bool IPAddress::operator==(const IPAddress& rhs) const { if (isIPv4()) + { return rhs.isIPv4() ? (m_IPv4 == rhs.m_IPv4) : false; + } return rhs.isIPv6() ? m_IPv6 == rhs.m_IPv6 : false; } @@ -561,7 +563,7 @@ 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) {} /** @@ -657,10 +659,10 @@ namespace pcpp std::string toString() const; private: - uint32_t m_NetworkPrefix; - uint32_t m_Mask; + uint32_t m_NetworkPrefix{}; + uint32_t m_Mask{}; - bool isValidNetmask(const IPv4Address& netmaskAddress); + static bool isValidNetmask(const IPv4Address& netmaskAddress); void initFromAddressAndPrefixLength(const IPv4Address& address, uint8_t prefixLen); void initFromAddressAndNetmask(const IPv4Address& address, const IPv4Address& netmaskAddress); }; @@ -678,7 +680,7 @@ 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) {} /** @@ -733,7 +735,7 @@ namespace pcpp */ IPv6Address getNetworkPrefix() const { - return IPv6Address(m_NetworkPrefix); + return { m_NetworkPrefix }; } /** @@ -774,10 +776,10 @@ namespace pcpp std::string toString() const; private: - uint8_t m_NetworkPrefix[16]; - uint8_t m_Mask[16]; + uint8_t m_NetworkPrefix[16]{}; + uint8_t m_Mask[16]{}; - bool isValidNetmask(const IPv6Address& netmaskAddress); + static bool isValidNetmask(const IPv6Address& netmaskAddress); void initFromAddressAndPrefixLength(const IPv6Address& address, uint8_t prefixLen); void initFromAddressAndNetmask(const IPv6Address& address, const IPv6Address& netmaskAddress); }; @@ -795,7 +797,7 @@ 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) {} /** @@ -892,10 +894,8 @@ namespace pcpp { return this->operator=(*other.m_IPv4Network); } - else - { - return this->operator=(*other.m_IPv6Network); - } + + return this->operator=(*other.m_IPv6Network); } /** @@ -1032,15 +1032,13 @@ namespace pcpp return m_IPv4Network->includes(address.getIPv4()); } - else - { - if (address.isIPv4()) - { - return false; - } - return m_IPv6Network->includes(address.getIPv6()); + if (address.isIPv4()) + { + return false; } + + return m_IPv6Network->includes(address.getIPv6()); } /** @@ -1058,15 +1056,13 @@ namespace pcpp return m_IPv4Network->includes(*network.m_IPv4Network); } - else - { - if (network.isIPv4Network()) - { - return false; - } - return m_IPv6Network->includes(*network.m_IPv6Network); + if (network.isIPv4Network()) + { + return false; } + + return m_IPv6Network->includes(*network.m_IPv6Network); } /** diff --git a/Common++/header/IpUtils.h b/Common++/header/IpUtils.h index 2cf9f7a00f..ce25b2313a 100644 --- a/Common++/header/IpUtils.h +++ b/Common++/header/IpUtils.h @@ -1,6 +1,6 @@ #pragma once -#include +#include #ifdef __linux__ # include # include @@ -95,7 +95,7 @@ namespace pcpp * @throws std::invalid_argument Sockaddr family is not AF_INET or AF_INET6, sockaddr is nullptr or the result * str buffer is insufficient. */ - void sockaddr2string(sockaddr const* sa, char* resultString, size_t resultBufLen); + void sockaddr2string(const sockaddr* sa, char* resultString, size_t resultBufLen); /** * Convert a in_addr format address to 32bit representation diff --git a/Common++/header/LRUList.h b/Common++/header/LRUList.h index a900c8413a..2954f3209e 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -26,17 +26,15 @@ namespace pcpp template class LRUList { public: - typedef typename std::list::iterator ListIterator; - typedef typename std::unordered_map::iterator MapIterator; + using ListIterator = typename std::list::iterator; + using MapIterator = typename std::unordered_map::iterator; /** * A c'tor for this class * @param[in] maxSize The max size this list can go */ - explicit LRUList(size_t maxSize) - { - m_MaxSize = maxSize; - } + explicit LRUList(std::size_t maxSize) : m_MaxSize(maxSize) + {} /** * Puts an element in the list. This element will be inserted (or advanced if it already exists) to the head of @@ -58,7 +56,7 @@ namespace pcpp // iterator to the element that prevented the insertion std::pair pair = m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin())); - if (pair.second == false) // already exists + if (!static_cast(pair.second)) // already exists { m_CacheItemsList.erase(pair.first->second); pair.first->second = m_CacheItemsList.begin(); @@ -70,11 +68,13 @@ namespace pcpp --lruIter; if (deletedValue != nullptr) + { #if __cplusplus > 199711L || _MSC_VER >= 1800 *deletedValue = std::move(*lruIter); #else *deletedValue = *lruIter; #endif + } m_CacheItemsMap.erase(*lruIter); m_CacheItemsList.erase(lruIter); return 1; @@ -109,7 +109,9 @@ namespace pcpp { MapIterator iter = m_CacheItemsMap.find(element); if (iter == m_CacheItemsMap.end()) + { return; + } m_CacheItemsList.erase(iter->second); m_CacheItemsMap.erase(iter); @@ -118,7 +120,7 @@ namespace pcpp /** * @return The max size of this list as determined in the c'tor */ - size_t getMaxSize() const + std::size_t getMaxSize() const { return m_MaxSize; } @@ -126,7 +128,7 @@ namespace pcpp /** * @return The number of elements currently in this list */ - size_t getSize() const + std::size_t getSize() const { return m_CacheItemsMap.size(); } @@ -134,7 +136,7 @@ namespace pcpp private: std::list m_CacheItemsList; std::unordered_map m_CacheItemsMap; - size_t m_MaxSize; + std::size_t m_MaxSize; }; } // namespace pcpp diff --git a/Common++/header/Logger.h b/Common++/header/Logger.h index fafe6a9e37..5b95039d63 100644 --- a/Common++/header/Logger.h +++ b/Common++/header/Logger.h @@ -1,10 +1,10 @@ #pragma once -#include +#include #include #include #include -#include +#include #ifndef LOG_MODULE # define LOG_MODULE UndefinedLogModule @@ -159,8 +159,7 @@ 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); + using LogPrinter = void (*)(LogLevel, const std::string&, const std::string&, const std::string&, const int); /** * A static method for converting the log level enum to a string. @@ -206,7 +205,9 @@ namespace pcpp void setAllModulesToLogLevel(LogLevel level) { for (int i = 1; i < NumOfLogModules; i++) + { m_LogModulesArray[i] = level; + } } /** @@ -265,7 +266,7 @@ namespace pcpp return *this; } - std::ostringstream* internalCreateLogStream(); + static std::ostringstream* internalCreateLogStream(); /** * An internal method to print log messages. Shouldn't be used externally. @@ -286,15 +287,15 @@ namespace pcpp private: bool m_LogsEnabled; - Logger::LogLevel m_LogModulesArray[NumOfLogModules]; + Logger::LogLevel m_LogModulesArray[NumOfLogModules]{}; LogPrinter m_LogPrinter; std::string m_LastError; - std::ostringstream* m_LogStream; + std::ostringstream* m_LogStream{}; // private c'tor - this class is a singleton Logger(); static void defaultLogPrinter(LogLevel logLevel, const std::string& logMessage, const std::string& file, - const std::string& method, const int line); + const std::string& method, int line); }; } // namespace pcpp diff --git a/Common++/header/MacAddress.h b/Common++/header/MacAddress.h index 29333aa02d..649b904a45 100644 --- a/Common++/header/MacAddress.h +++ b/Common++/header/MacAddress.h @@ -4,8 +4,8 @@ #include #include #include -#include -#include +#include +#include #include /// @file diff --git a/Common++/header/OUILookup.h b/Common++/header/OUILookup.h index fb49ac236d..8a7270c66d 100644 --- a/Common++/header/OUILookup.h +++ b/Common++/header/OUILookup.h @@ -45,7 +45,7 @@ namespace pcpp * MAC addresses with only first three octets. The first element is unsigned integer equivalent of "XX:XX:XX" * formatted MAC address */ - typedef std::unordered_map OUIVendorMap; + using OUIVendorMap = std::unordered_map; /// Internal vendor list for MAC addresses OUIVendorMap vendorMap; diff --git a/Common++/header/PointerVector.h b/Common++/header/PointerVector.h index 342ad62e0b..2052c7f850 100644 --- a/Common++/header/PointerVector.h +++ b/Common++/header/PointerVector.h @@ -1,8 +1,8 @@ #pragma once #include -#include -#include +#include +#include #include #include #include @@ -70,8 +70,7 @@ namespace pcpp /** * A constructor that create an empty instance of this object */ - PointerVector() - {} + PointerVector() = default; /** * Copies the vector along with all elements inside it. @@ -259,7 +258,7 @@ namespace pcpp /** * @return A pointer to the first element in the vector */ - T const* front() const + const T* front() const { return m_Vector.front(); } @@ -275,7 +274,7 @@ namespace pcpp /* * @return A pointer to the last element in the vector. */ - T const* back() const + const T* back() const { return m_Vector.back(); } @@ -336,7 +335,7 @@ namespace pcpp * @param[in] position An iterator pointing to the element to detach. * @return An unique pointer that holds ownership of the detached element. */ - std::unique_ptr getAndDetach(VectorIterator const& position) + std::unique_ptr getAndDetach(const VectorIterator& position) { std::unique_ptr result(*position); m_Vector.erase(position); @@ -369,7 +368,7 @@ namespace pcpp * The caller is responsible of freeing the copied elements. * @return A vector of pointers to the newly copied elements. */ - static std::vector deepCopyUnsafe(std::vector const& origin) + static std::vector deepCopyUnsafe(const std::vector& origin) { std::vector copyVec; // Allocate the vector initially to ensure no exceptions are thrown during push_back. @@ -402,7 +401,7 @@ namespace pcpp * @param[in] origin The vector of elements to free. * @remarks The vector's contents are not cleared and will point to invalid locations in memory. */ - static void freeVectorUnsafe(std::vector const& origin) + static void freeVectorUnsafe(const std::vector& origin) { for (auto& obj : origin) { diff --git a/Common++/header/SystemUtils.h b/Common++/header/SystemUtils.h index c68ab8f777..de7a48424c 100644 --- a/Common++/header/SystemUtils.h +++ b/Common++/header/SystemUtils.h @@ -1,12 +1,15 @@ #pragma once -#include +#include #include #include /// @file -#define MAX_NUM_OF_CORES 32 +enum +{ + MAX_NUM_OF_CORES = 32 +}; #ifdef _MSC_VER int gettimeofday(struct timeval* tp, struct timezone* tzp); @@ -189,7 +192,7 @@ namespace pcpp static const SystemCore IdToSystemCore[MAX_NUM_OF_CORES]; }; - typedef uint32_t CoreMask; + using CoreMask = uint32_t; /** * Get total number of cores on device @@ -362,7 +365,7 @@ namespace pcpp * The callback to be invoked when the event occurs * @param[in] cookie A pointer the the cookie provided by the user in ApplicationEventHandler c'tor */ - typedef void (*EventHandlerCallback)(void* cookie); + using EventHandlerCallback = void (*)(void*); /** * As ApplicationEventHandler is a singleton, this is the static getter to retrieve its instance diff --git a/Common++/src/GeneralUtils.cpp b/Common++/src/GeneralUtils.cpp index 04aec21a62..429ad3a4d4 100644 --- a/Common++/src/GeneralUtils.cpp +++ b/Common++/src/GeneralUtils.cpp @@ -12,14 +12,18 @@ 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) { if (i >= static_cast(stringSizeLimit)) + { break; + } dataStream << std::setw(2) << std::setfill('0') << static_cast(byteArr[i]); } @@ -30,11 +34,17 @@ namespace pcpp 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; } @@ -50,10 +60,12 @@ namespace pcpp for (size_t i = 0; i < hexString.length(); i += 2) { if (i >= resultByteArrSize * 2) + { return resultByteArrSize; + } - int firstChar = char2int(hexString[i]); - int secondChar = char2int(hexString[i + 1]); + const int firstChar = char2int(hexString[i]); + const int secondChar = char2int(hexString[i + 1]); if (firstChar < 0 || secondChar < 0) { PCPP_LOG_ERROR("Input string has an illegal character"); @@ -82,12 +94,15 @@ namespace pcpp } if (0 == memcmp(ptr, needle, needleLen)) + { return ptr; - else - ++ptr; + } + ++ptr; } else + { break; + } } return nullptr; diff --git a/Common++/src/IpAddress.cpp b/Common++/src/IpAddress.cpp index dd1c1a3d5f..18b8b67620 100644 --- a/Common++/src/IpAddress.cpp +++ b/Common++/src/IpAddress.cpp @@ -33,9 +33,11 @@ namespace pcpp char addrBuffer[INET_ADDRSTRLEN]; if (inet_ntop(AF_INET, toBytes(), addrBuffer, sizeof(addrBuffer)) != nullptr) + { return std::string(addrBuffer); + } - return std::string(); + return {}; } bool IPv4Address::isMulticast() const @@ -73,7 +75,9 @@ namespace pcpp bool IPv4Address::isValidIPv4Address(const std::string& addrAsString) { - struct sockaddr_in sa_in; + struct sockaddr_in sa_in + { + }; return inet_pton(AF_INET, addrAsString.data(), &(sa_in.sin_addr)) > 0; } @@ -86,9 +90,11 @@ namespace pcpp char addrBuffer[INET6_ADDRSTRLEN]; if (inet_ntop(AF_INET6, toBytes(), addrBuffer, sizeof(addrBuffer)) != nullptr) + { return std::string(addrBuffer); + } - return std::string(); + return {}; } bool IPv6Address::isMulticast() const @@ -133,7 +139,9 @@ namespace pcpp bool IPv6Address::isValidIPv6Address(const std::string& addrAsString) { - struct sockaddr_in6 sa_in6; + struct sockaddr_in6 sa_in6 + { + }; return inet_pton(AF_INET6, addrAsString.data(), &(sa_in6.sin6_addr)) > 0; } @@ -170,18 +178,16 @@ namespace pcpp return true; } - uint32_t maskAsInt = be32toh(maskAddress.toInt()); - std::bitset<32> bitset(maskAsInt); + const uint32_t maskAsInt = be32toh(maskAddress.toInt()); + const std::bitset<32> bitset(maskAsInt); auto bitsetCount = bitset.count(); if (bitsetCount == 32) { return true; } - else - { - return maskAsInt << bitsetCount == 0; - } + + return maskAsInt << bitsetCount == 0; } void IPv4Network::initFromAddressAndPrefixLength(const IPv4Address& address, uint8_t prefixLen) @@ -227,7 +233,8 @@ namespace pcpp IPv4Network::IPv4Network(const std::string& addressAndNetmask) { std::stringstream stream(addressAndNetmask); - std::string networkPrefixStr, netmaskStr; + std::string networkPrefixStr; + std::string netmaskStr; std::getline(stream, networkPrefixStr, '/'); std::getline(stream, netmaskStr); @@ -249,7 +256,7 @@ namespace pcpp if (std::all_of(netmaskStr.begin(), netmaskStr.end(), ::isdigit)) { - uint32_t prefixLen = std::stoi(netmaskStr); + const uint32_t prefixLen = std::stoi(netmaskStr); if (prefixLen > 32) { throw std::invalid_argument("Prefix length must be an integer between 0 and 32"); @@ -278,26 +285,26 @@ namespace pcpp uint8_t IPv4Network::getPrefixLen() const { - std::bitset<32> bitset(m_Mask); + const std::bitset<32> bitset(m_Mask); return bitset.count(); } IPv4Address IPv4Network::getLowestAddress() const { - std::bitset<32> bitset(m_Mask); + 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); - std::bitset<32> bitset(m_Mask); + const 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)); + const std::bitset<32> bitset(static_cast(~m_Mask)); return 1ULL << bitset.count(); } @@ -308,8 +315,8 @@ namespace pcpp bool IPv4Network::includes(const IPv4Network& network) const { - uint32_t lowestAddress = network.m_NetworkPrefix; - uint32_t highestAddress = network.m_NetworkPrefix | ~network.m_Mask; + const uint32_t lowestAddress = network.m_NetworkPrefix; + const uint32_t highestAddress = network.m_NetworkPrefix | ~network.m_Mask; return ((lowestAddress & m_Mask) == m_NetworkPrefix && (highestAddress & m_Mask) == m_NetworkPrefix); } @@ -344,7 +351,7 @@ namespace pcpp { continue; } - std::bitset<8> bitset(curByte); + const std::bitset<8> bitset(curByte); if (((curByte << bitset.count()) & 0xff) != 0) { return false; @@ -364,15 +371,15 @@ namespace pcpp { memset(m_Mask, 0, IPV6_ADDR_SIZE); int remainingPrefixLen = prefixLen; - for (auto byteIndex = 0; byteIndex < IPV6_ADDR_SIZE; byteIndex++) + for (unsigned char& byteIndex : m_Mask) { if (remainingPrefixLen >= 8) { - m_Mask[byteIndex] = 0xff; + byteIndex = 0xff; } else if (remainingPrefixLen > 0) { - m_Mask[byteIndex] = 0xff << (8 - remainingPrefixLen); + byteIndex = 0xff << (8 - remainingPrefixLen); } else { @@ -433,7 +440,8 @@ namespace pcpp IPv6Network::IPv6Network(const std::string& addressAndNetmask) { std::stringstream stream(addressAndNetmask); - std::string networkPrefixStr, netmaskStr; + std::string networkPrefixStr; + std::string netmaskStr; std::getline(stream, networkPrefixStr, '/'); std::getline(stream, netmaskStr); @@ -454,7 +462,7 @@ namespace pcpp } if (std::all_of(netmaskStr.begin(), netmaskStr.end(), ::isdigit)) { - uint32_t prefixLen = std::stoi(netmaskStr); + const uint32_t prefixLen = std::stoi(netmaskStr); if (prefixLen > 128) { throw std::invalid_argument("Prefix length must be an integer between 0 and 128"); @@ -484,9 +492,9 @@ namespace pcpp uint8_t IPv6Network::getPrefixLen() const { uint8_t result = 0; - for (auto byteIndex = 0; byteIndex < IPV6_ADDR_SIZE; byteIndex++) + for (unsigned char byteIndex : m_Mask) { - std::bitset<8> bs(m_Mask[byteIndex]); + const std::bitset<8> bs(byteIndex); result += static_cast(bs.count()); } return result; @@ -520,9 +528,9 @@ namespace pcpp uint64_t IPv6Network::getTotalAddressCount() const { int numOfBitset = 0; - for (auto byteIndex = 0; byteIndex < IPV6_ADDR_SIZE; byteIndex++) + for (unsigned char byteIndex : m_Mask) { - std::bitset<8> bitset(static_cast(~m_Mask[byteIndex])); + const std::bitset<8> bitset(static_cast(~byteIndex)); numOfBitset += bitset.count(); } diff --git a/Common++/src/IpUtils.cpp b/Common++/src/IpUtils.cpp index 3c812d5bfe..277a1d9472 100644 --- a/Common++/src/IpUtils.cpp +++ b/Common++/src/IpUtils.cpp @@ -21,10 +21,14 @@ namespace pcpp in_addr* sockaddr2in_addr(sockaddr* sa) { if (sa == nullptr) + { throw std::invalid_argument("sockaddr is nullptr"); + } if (sa->sa_family != AF_INET) + { throw std::invalid_argument("sockaddr family is not AF_INET."); + } return &(reinterpret_cast(sa)->sin_addr); } @@ -45,10 +49,14 @@ namespace pcpp in6_addr* sockaddr2in6_addr(sockaddr* sa) { if (sa == nullptr) + { throw std::invalid_argument("sockaddr is nullptr"); + } if (sa->sa_family != AF_INET6) + { throw std::invalid_argument("sockaddr family is not AF_INET6."); + } return &(reinterpret_cast(sa)->sin6_addr); } @@ -66,10 +74,12 @@ namespace pcpp } } - void sockaddr2string(sockaddr const* sa, char* resultString, size_t resultBufLen) + void sockaddr2string(const sockaddr* sa, char* resultString, size_t resultBufLen) { if (sa == nullptr) + { throw std::invalid_argument("sockaddr is nullptr"); + } switch (sa->sa_family) { @@ -77,9 +87,11 @@ namespace pcpp { PCPP_LOG_DEBUG("IPv4 packet address"); if (resultBufLen < INET_ADDRSTRLEN) + { throw std::invalid_argument("Insufficient buffer"); + } - if (inet_ntop(AF_INET, &(reinterpret_cast(sa)->sin_addr), resultString, + if (inet_ntop(AF_INET, &(reinterpret_cast(sa)->sin_addr), resultString, resultBufLen) == nullptr) { throw std::runtime_error("Unknown error during conversion"); @@ -90,9 +102,11 @@ namespace pcpp { PCPP_LOG_DEBUG("IPv6 packet address"); if (resultBufLen < INET6_ADDRSTRLEN) + { throw std::invalid_argument("Insufficient buffer"); + } - if (inet_ntop(AF_INET6, &(reinterpret_cast(sa)->sin6_addr), resultString, + if (inet_ntop(AF_INET6, &(reinterpret_cast(sa)->sin6_addr), resultString, resultBufLen) == nullptr) { throw std::runtime_error("Unknown error during conversion"); diff --git a/Common++/src/Logger.cpp b/Common++/src/Logger.cpp index 7608911b6b..c4ac8d2d4e 100644 --- a/Common++/src/Logger.cpp +++ b/Common++/src/Logger.cpp @@ -7,8 +7,7 @@ namespace pcpp Logger::Logger() : m_LogsEnabled(true), m_LogPrinter(&defaultLogPrinter) { m_LastError.reserve(200); - for (int i = 0; i < NumOfLogModules; i++) - m_LogModulesArray[i] = Info; + std::fill(m_LogModulesArray, m_LogModulesArray + NumOfLogModules, Info); } std::string Logger::logLevelAsString(LogLevel logLevel) @@ -30,7 +29,7 @@ namespace pcpp std::ostringstream sstream; sstream << file << ": " << method << ":" << line; std::cerr << std::left << "[" << std::setw(5) << Logger::logLevelAsString(logLevel) << ": " << std::setw(45) - << sstream.str() << "] " << logMessage << std::endl; + << sstream.str() << "] " << logMessage << '\n'; } std::ostringstream* Logger::internalCreateLogStream() @@ -41,7 +40,7 @@ namespace pcpp void Logger::internalPrintLogMessage(std::ostringstream* logStream, Logger::LogLevel logLevel, const char* file, const char* method, int line) { - std::string logMessage = logStream->str(); + const std::string logMessage = logStream->str(); delete logStream; if (logLevel == Logger::Error) { diff --git a/Common++/src/OUILookup.cpp b/Common++/src/OUILookup.cpp index d116ee8388..898a64a903 100644 --- a/Common++/src/OUILookup.cpp +++ b/Common++/src/OUILookup.cpp @@ -18,10 +18,14 @@ namespace pcpp for (const auto& line : parsedJson.items()) { 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()) @@ -30,13 +34,15 @@ namespace pcpp for (const auto& entry : val["maskedFilters"]) { 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()) { - int maskValue = subVal["mask"].get(); - vLocalMaskedFilter.push_back({ maskValue, {} }); + const int maskValue = subVal["mask"].get(); + vLocalMaskedFilter.emplace_back(); // Parse masked filter for (const auto& subentry : subVal["vendors"].items()) @@ -81,28 +87,34 @@ namespace pcpp 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); - 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)); + const 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"; + } for (const auto& entry : itr->second.maskedFilter) { - uint64_t maskValue = ~((1 << (48 - entry.mask)) - 1); - uint64_t bufferAddr = macAddr & maskValue; + const uint64_t maskValue = ~((1 << (48 - entry.mask)) - 1); + const uint64_t bufferAddr = macAddr & maskValue; auto subItr = entry.vendorMap.find(bufferAddr); if (subItr != entry.vendorMap.end()) + { return subItr->second; + } } return itr->second.vendorName; diff --git a/Common++/src/SystemUtils.cpp b/Common++/src/SystemUtils.cpp index 13f2d68caa..eff15103d2 100644 --- a/Common++/src/SystemUtils.cpp +++ b/Common++/src/SystemUtils.cpp @@ -128,7 +128,7 @@ namespace pcpp CoreMask getCoreMaskForAllMachineCores() { - int numOfCores = getNumOfCores() < 32 ? getNumOfCores() : 32; + const int numOfCores = getNumOfCores() < 32 ? getNumOfCores() : 32; CoreMask result = 0; for (int i = 0; i < numOfCores; i++) { @@ -167,7 +167,7 @@ namespace pcpp int i = 0; while (coreMask != 0) { - if (1 & coreMask) + if ((1 & coreMask) != 0u) { resultVec.push_back(SystemCores::IdToSystemCore[i]); } @@ -179,29 +179,36 @@ namespace pcpp std::string executeShellCommand(const std::string& command) { - std::unique_ptr pipe = std::unique_ptr(POPEN(command.c_str(), "r")); + const std::unique_ptr pipe = + std::unique_ptr(POPEN(command.c_str(), "r")); if (!pipe) { throw std::runtime_error("Error executing command: " + command); } - std::array buffer; + std::array buffer{}; std::string result; - while (!feof(pipe.get())) + while (feof(pipe.get()) == 0) { 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; + struct stat info + { + }; if (stat(dirPath.c_str(), &info) != 0) + { return false; - else if (info.st_mode & S_IFDIR) + } + if (info.st_mode & S_IFDIR) return true; else return false; @@ -256,10 +263,10 @@ namespace pcpp #else // Linux -# include +# include - timespec ts; - int res = clock_gettime(CLOCK_REALTIME, &ts); + timespec ts{}; + const int res = clock_gettime(CLOCK_REALTIME, &ts); if (res == 0) { sec = ts.tv_sec; @@ -345,8 +352,10 @@ namespace pcpp const std::lock_guard lock(UnixLinuxHandlerRoutineMutex); if (ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler != nullptr) + { ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler( ApplicationEventHandler::getInstance().m_ApplicationInterruptedCookie); + } ApplicationEventHandler::getInstance().m_ApplicationInterruptedHandler = nullptr; @@ -372,7 +381,9 @@ namespace pcpp #if defined(_WIN32) SetConsoleCtrlHandler((PHANDLER_ROUTINE)handlerRoutine, TRUE); #else - struct sigaction action; + struct sigaction action + { + }; memset(&action, 0, sizeof(struct sigaction)); action.sa_handler = handlerRoutine; sigemptyset(&action.sa_mask); diff --git a/Common++/src/TablePrinter.cpp b/Common++/src/TablePrinter.cpp index ac7745f18f..9adb8fbd43 100644 --- a/Common++/src/TablePrinter.cpp +++ b/Common++/src/TablePrinter.cpp @@ -62,7 +62,7 @@ namespace pcpp std::cout << std::left << "| " << std::setw(m_ColumnWidths.at(i)) << val << " "; } - std::cout << "|" << std::endl; + std::cout << "|" << '\n'; return true; } @@ -90,18 +90,22 @@ namespace pcpp } auto totalLen = std::accumulate(m_ColumnWidths.begin(), m_ColumnWidths.end(), m_ColumnWidths.size() * 3) + 1; - std::cout << std::string(totalLen, '-') << std::endl; + std::cout << std::string(totalLen, '-') << '\n'; } 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; + } printSeparator(); @@ -124,7 +128,7 @@ namespace pcpp std::cout << std::left << "| " << std::setw(m_ColumnWidths.at(i)) << m_ColumnNames.at(i) << " "; } - std::cout << "|" << std::endl; + std::cout << "|" << '\n'; printSeparator(); }