diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000000..c32d3842fc --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,34 @@ +Checks: 'cert-*, +clang-analyzer-*, +concurrency-*, +cppcoreguidelines-*, +misc-*, +modernize-*, +performance-*, +portability-*, +readability-*, +-cert-env33-c, +-cert-err58-cpp, +-clang-analyzer-optin.cplusplus.VirtualCall, +-cppcoreguidelines-avoid-c-arrays, +-cppcoreguidelines-avoid-do-while, +-cppcoreguidelines-avoid-magic-numbers, +-cppcoreguidelines-avoid-non-const-global-variables, +-cppcoreguidelines-macro-usage, +-cppcoreguidelines-owning-memory, +-cppcoreguidelines-pro-bounds-array-to-pointer-decay, +-cppcoreguidelines-pro-bounds-constant-array-index, +-cppcoreguidelines-pro-bounds-pointer-arithmetic, +-cppcoreguidelines-pro-type-reinterpret-cast, +-cppcoreguidelines-pro-type-const-cast, +-cppcoreguidelines-pro-type-vararg, +-cppcoreguidelines-special-member-functions, +-modernize-avoid-c-arrays, +-modernize-use-trailing-return-type, +-misc-header-include-cycle, +-misc-include-cleaner, +-misc-no-recursion, +-misc-non-private-member-variables-in-classes, +-misc-use-anonymous-namespace, +-readability-function-cognitive-complexity, +-readability-magic-numbers' diff --git a/Common++/CMakeLists.txt b/Common++/CMakeLists.txt index 5b75bf9f77..9170aea53e 100644 --- a/Common++/CMakeLists.txt +++ b/Common++/CMakeLists.txt @@ -9,23 +9,26 @@ add_library( src/OUILookup.cpp src/PcapPlusPlusVersion.cpp src/SystemUtils.cpp - src/TablePrinter.cpp) + src/TablePrinter.cpp +) -set(public_headers - header/DeprecationUtils.h - header/GeneralUtils.h - header/IpAddress.h - header/IpAddressUtils.h - header/IpUtils.h - header/Logger.h - header/LRUList.h - header/MacAddress.h - header/OUILookup.h - header/PcapPlusPlusVersion.h - header/PointerVector.h - header/SystemUtils.h - header/TablePrinter.h - header/TimespecTimeval.h) +set( + public_headers + header/DeprecationUtils.h + header/GeneralUtils.h + header/IpAddress.h + header/IpAddressUtils.h + header/IpUtils.h + header/Logger.h + header/LRUList.h + header/MacAddress.h + header/OUILookup.h + header/PcapPlusPlusVersion.h + header/PointerVector.h + header/SystemUtils.h + header/TablePrinter.h + header/TimespecTimeval.h +) # Set the public header that will be installed set_property(TARGET Common++ PROPERTY PUBLIC_HEADER ${public_headers}) @@ -35,7 +38,8 @@ target_include_directories( PUBLIC $ $ # Don't link with EndianPortable and json as it won't be exported PRIVATE $ - PRIVATE $) + PRIVATE $ +) if(WIN32) target_link_libraries(Common++ PRIVATE ws2_32 iphlpapi) @@ -48,7 +52,8 @@ if(PCAPPP_INSTALL) ARCHIVE DESTINATION ${PCAPPP_INSTALL_LIBDIR} LIBRARY DESTINATION ${PCAPPP_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${PCAPPP_INSTALL_INCLUDEDIR} - RUNTIME DESTINATION ${PCAPPP_INSTALL_BINDIR}) + RUNTIME DESTINATION ${PCAPPP_INSTALL_BINDIR} + ) endif() set_property(TARGET Common++ PROPERTY OUTPUT_NAME "Common++") diff --git a/Common++/header/GeneralUtils.h b/Common++/header/GeneralUtils.h index 316ee22913..7e49fa12fc 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 6cafb2ed7d..e29d7bfc77 100644 --- a/Common++/header/IpAddress.h +++ b/Common++/header/IpAddress.h @@ -1,7 +1,7 @@ #pragma once -#include -#include +#include +#include #include #include #include @@ -145,7 +145,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; } @@ -395,7 +395,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; } @@ -433,7 +435,7 @@ namespace pcpp /// A constructor that creates an instance of the class out of an address and a full prefix length, /// essentially making a network of consisting of only 1 address. /// @param address An address representing the network prefix. - explicit IPv4Network(const IPv4Address& address) : IPv4Network(address, 32u) + explicit IPv4Network(const IPv4Address& address) : IPv4Network(address, 32U) {} /// A constructor that creates an instance of the class out of an address representing the network prefix @@ -476,7 +478,7 @@ namespace pcpp /// @return The network prefix, for example: the network prefix of 10.10.10.10/16 is 10.10.0.0 IPv4Address getNetworkPrefix() const { - return IPv4Address(m_NetworkPrefix); + return m_NetworkPrefix; } /// @return The lowest non-reserved IPv4 address in this network, for example: the lowest address @@ -505,10 +507,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); }; @@ -521,7 +523,7 @@ namespace pcpp /// A constructor that creates an instance of the class out of an address and a full prefix length, /// essentially making a network of consisting of only 1 address. /// @param address An address representing the network prefix. - explicit IPv6Network(const IPv6Address& address) : IPv6Network(address, 128u) + explicit IPv6Network(const IPv6Address& address) : IPv6Network(address, 128U) {} /// A constructor that creates an instance of the class out of an address representing the network prefix @@ -564,7 +566,7 @@ namespace pcpp /// @return The network prefix, for example: the network prefix of 3546:f321::/16 is 3546:: IPv6Address getNetworkPrefix() const { - return IPv6Address(m_NetworkPrefix); + return { m_NetworkPrefix }; } /// @return The lowest non-reserved IPv6 address in this network, for example: the lowest address in 3546::/16 @@ -593,10 +595,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); }; @@ -609,7 +611,7 @@ namespace pcpp /// A constructor that creates an instance of the class out of an IP address and a full prefix length, /// essentially making a network of consisting of only 1 address. /// @param address An address representing the network prefix. - explicit IPNetwork(const IPAddress& address) : IPNetwork(address, address.isIPv4() ? 32u : 128u) + explicit IPNetwork(const IPAddress& address) : IPNetwork(address, address.isIPv4() ? 32U : 128U) {} /// A constructor that creates an instance of the class out of an address representing the network prefix @@ -696,10 +698,8 @@ namespace pcpp { return this->operator=(*other.m_IPv4Network); } - else - { - return this->operator=(*other.m_IPv6Network); - } + + return this->operator=(*other.m_IPv6Network); } /// Overload of an assignment operator. @@ -814,15 +814,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()); } /// @param network An IP network @@ -838,15 +836,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); } /// @return A string representation of the network in a format of NETWORK_PREFIX/PREFIX_LEN, for example: @@ -861,40 +857,40 @@ namespace pcpp std::unique_ptr m_IPv6Network; }; - inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv4Address& ipv4Address) + inline std::ostream& operator<<(std::ostream& oss, const pcpp::IPv4Address& ipv4Address) { - os << ipv4Address.toString(); - return os; + oss << ipv4Address.toString(); + return oss; } - inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv6Address& ipv6Address) + inline std::ostream& operator<<(std::ostream& oss, const pcpp::IPv6Address& ipv6Address) { - os << ipv6Address.toString(); - return os; + oss << ipv6Address.toString(); + return oss; } - inline std::ostream& operator<<(std::ostream& os, const pcpp::IPAddress& ipAddress) + inline std::ostream& operator<<(std::ostream& oss, const pcpp::IPAddress& ipAddress) { - os << ipAddress.toString(); - return os; + oss << ipAddress.toString(); + return oss; } - inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv4Network& network) + inline std::ostream& operator<<(std::ostream& oss, const pcpp::IPv4Network& network) { - os << network.toString(); - return os; + oss << network.toString(); + return oss; } - inline std::ostream& operator<<(std::ostream& os, const pcpp::IPv6Network& network) + inline std::ostream& operator<<(std::ostream& oss, const pcpp::IPv6Network& network) { - os << network.toString(); - return os; + oss << network.toString(); + return oss; } - inline std::ostream& operator<<(std::ostream& os, const pcpp::IPNetwork& network) + inline std::ostream& operator<<(std::ostream& oss, const pcpp::IPNetwork& network) { - os << network.toString(); - return os; + oss << network.toString(); + return oss; } } // namespace pcpp diff --git a/Common++/header/IpUtils.h b/Common++/header/IpUtils.h index 6dadfb5028..46ad6f6617 100644 --- a/Common++/header/IpUtils.h +++ b/Common++/header/IpUtils.h @@ -1,6 +1,6 @@ #pragma once -#include +#include #ifdef __linux__ # include # include @@ -53,34 +53,34 @@ namespace pcpp namespace internal { /// Extract IPv4 address from sockaddr - /// @param[in] sa - input sockaddr + /// @param[in] sAddr - input sockaddr /// @return Address in in_addr format /// @throws std::invalid_argument Sockaddr family is not AF_INET or sockaddr is nullptr. - in_addr* sockaddr2in_addr(sockaddr* sa); + in_addr* sockaddr2in_addr(sockaddr* sAddr); /// Attempt to extract IPv4 address from sockaddr - /// @param[in] sa - input sockaddr + /// @param[in] sAddr - input sockaddr /// @return Pointer to address in in_addr format or nullptr if extraction fails. - in_addr* try_sockaddr2in_addr(sockaddr* sa); + in_addr* try_sockaddr2in_addr(sockaddr* sAddr); /// Extract IPv6 address from sockaddr - /// @param[in] sa - input sockaddr + /// @param[in] sAddr - input sockaddr /// @return Address in in6_addr format /// @throws std::invalid_argument Sockaddr family is not AF_INET6 or sockaddr is nullptr. - in6_addr* sockaddr2in6_addr(sockaddr* sa); + in6_addr* sockaddr2in6_addr(sockaddr* sAddr); /// Attempt to extract IPv6 address from sockaddr - /// @param[in] sa - input sockaddr + /// @param[in] sAddr - input sockaddr /// @return Pointer to address in in6_addr format or nullptr if extraction fails. - in6_addr* try_sockaddr2in6_addr(sockaddr* sa); + in6_addr* try_sockaddr2in6_addr(sockaddr* sAddr); /// Converts a sockaddr format address to its string representation - /// @param[in] sa Address in sockaddr format + /// @param[in] sAddr 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. - void sockaddr2string(sockaddr const* sa, char* resultString, size_t resultBufLen); + void sockaddr2string(const sockaddr* sAddr, char* resultString, size_t resultBufLen); /// Convert a in_addr format address to 32bit representation /// @param[in] inAddr Address in in_addr format diff --git a/Common++/header/LRUList.h b/Common++/header/LRUList.h index 81bc6db3a7..002ea6721f 100644 --- a/Common++/header/LRUList.h +++ b/Common++/header/LRUList.h @@ -23,15 +23,13 @@ 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(std::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 /// the list as the most recently used element. If the list already reached its max size and the element is new @@ -51,7 +49,7 @@ namespace pcpp // iterator to the element that prevented the insertion std::pair pair = m_CacheItemsMap.insert(std::make_pair(element, m_CacheItemsList.begin())); - if (pair.second == false) // already exists + if (!pair.second) // already exists { m_CacheItemsList.erase(pair.first->second); pair.first->second = m_CacheItemsList.begin(); @@ -63,11 +61,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; @@ -96,7 +96,9 @@ namespace pcpp { MapIterator iter = m_CacheItemsMap.find(element); if (iter == m_CacheItemsMap.end()) + { return; + } m_CacheItemsList.erase(iter->second); m_CacheItemsMap.erase(iter); diff --git a/Common++/header/Logger.h b/Common++/header/Logger.h index 49d05ef759..f446645c5f 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 @@ -149,8 +149,7 @@ namespace pcpp /// @param[in] file The source file in PcapPlusPlus code the log message is coming from /// @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. /// @param[in] logLevel A log level enum @@ -186,7 +185,9 @@ namespace pcpp void setAllModulesToLogLevel(LogLevel level) { for (int i = 1; i < NumOfLogModules; i++) + { m_LogModulesArray[i] = level; + } } /// Set a custom log printer. @@ -233,7 +234,7 @@ namespace pcpp return *this; } - std::ostringstream* internalCreateLogStream(); + static 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, @@ -250,15 +251,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 6e0834b013..d1fa31f56a 100644 --- a/Common++/header/MacAddress.h +++ b/Common++/header/MacAddress.h @@ -4,8 +4,8 @@ #include #include #include -#include -#include +#include +#include #include /// @file @@ -142,9 +142,9 @@ namespace pcpp uint8_t m_Address[6] = { 0 }; }; - inline std::ostream& operator<<(std::ostream& os, const pcpp::MacAddress& macAddress) + inline std::ostream& operator<<(std::ostream& oss, const pcpp::MacAddress& macAddress) { - os << macAddress.toString(); - return os; + oss << macAddress.toString(); + return oss; } } // namespace pcpp diff --git a/Common++/header/OUILookup.h b/Common++/header/OUILookup.h index 20ac58d56f..105c23b9a0 100644 --- a/Common++/header/OUILookup.h +++ b/Common++/header/OUILookup.h @@ -24,6 +24,10 @@ namespace pcpp /// be 36, and the second element will be unsigned integer equivalent of "XX:XX:XX:XX:X0:00" and vendor name. struct MaskedFilter { + MaskedFilter(int maskVal, std::unordered_map map) + : mask(maskVal), vendorMap(std::move(map)) + {} + int mask; std::unordered_map vendorMap; }; @@ -37,7 +41,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 be2a072c56..f8b2521b32 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 @@ -56,8 +56,7 @@ namespace pcpp using ConstVectorIterator = typename std::vector::const_iterator; /// A constructor that create an empty instance of this object - PointerVector() - {} + PointerVector() = default; /// Copies the vector along with all elements inside it. /// All elements inside the copied vector are duplicates and the originals remain unchanged. @@ -214,7 +213,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(); } @@ -226,7 +225,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(); } @@ -277,7 +276,7 @@ namespace pcpp /// Removes an element from the vector and transfers ownership to the returned unique pointer. /// @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); @@ -304,7 +303,7 @@ namespace pcpp /// Performs a copy of the vector along with its elements. /// 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. @@ -335,7 +334,7 @@ namespace pcpp /// Calling this function with non-heap allocated pointers is UB. /// @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 bd557ca824..8b3c8b72e1 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); @@ -112,7 +115,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 /// @return Total number of CPU cores on device @@ -247,7 +250,7 @@ namespace pcpp /// @typedef EventHandlerCallback /// The callback to be invoked when the event occurs /// @param[in] cookie A pointer the the cookie provided by the user in ApplicationEventHandler c'tor - typedef void (*EventHandlerCallback)(void* cookie); + using EventHandlerCallback = void (*)(void*); /// As ApplicationEventHandler is a singleton, this is the static getter to retrieve its instance /// @return The singleton instance of ApplicationEventHandler diff --git a/Common++/src/GeneralUtils.cpp b/Common++/src/GeneralUtils.cpp index 04aec21a62..1143e25d96 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; + { + stringSizeLimit = static_cast(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..fd586b5445 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 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 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,10 +492,10 @@ namespace pcpp uint8_t IPv6Network::getPrefixLen() const { uint8_t result = 0; - for (auto byteIndex = 0; byteIndex < IPV6_ADDR_SIZE; byteIndex++) + for (const unsigned char byteIndex : m_Mask) { - std::bitset<8> bs(m_Mask[byteIndex]); - result += static_cast(bs.count()); + const std::bitset<8> bset(byteIndex); + result += static_cast(bset.count()); } return result; } @@ -520,10 +528,10 @@ namespace pcpp uint64_t IPv6Network::getTotalAddressCount() const { int numOfBitset = 0; - for (auto byteIndex = 0; byteIndex < IPV6_ADDR_SIZE; byteIndex++) + for (const unsigned char byteIndex : m_Mask) { - std::bitset<8> bitset(static_cast(~m_Mask[byteIndex])); - numOfBitset += bitset.count(); + const std::bitset<8> bitset(static_cast(~byteIndex)); + numOfBitset += static_cast(bitset.count()); } if (numOfBitset >= 64) diff --git a/Common++/src/IpUtils.cpp b/Common++/src/IpUtils.cpp index 3c812d5bfe..44bd7e1f90 100644 --- a/Common++/src/IpUtils.cpp +++ b/Common++/src/IpUtils.cpp @@ -18,22 +18,26 @@ namespace pcpp { namespace internal { - in_addr* sockaddr2in_addr(sockaddr* sa) + in_addr* sockaddr2in_addr(sockaddr* sAddr) { - if (sa == nullptr) + if (sAddr == nullptr) + { throw std::invalid_argument("sockaddr is nullptr"); + } - if (sa->sa_family != AF_INET) + if (sAddr->sa_family != AF_INET) + { throw std::invalid_argument("sockaddr family is not AF_INET."); + } - return &(reinterpret_cast(sa)->sin_addr); + return &(reinterpret_cast(sAddr)->sin_addr); } - in_addr* try_sockaddr2in_addr(sockaddr* sa) + in_addr* try_sockaddr2in_addr(sockaddr* sAddr) { try { - return sockaddr2in_addr(sa); + return sockaddr2in_addr(sAddr); } catch (const std::invalid_argument& e) { @@ -42,22 +46,26 @@ namespace pcpp } } - in6_addr* sockaddr2in6_addr(sockaddr* sa) + in6_addr* sockaddr2in6_addr(sockaddr* sAddr) { - if (sa == nullptr) + if (sAddr == nullptr) + { throw std::invalid_argument("sockaddr is nullptr"); + } - if (sa->sa_family != AF_INET6) + if (sAddr->sa_family != AF_INET6) + { throw std::invalid_argument("sockaddr family is not AF_INET6."); + } - return &(reinterpret_cast(sa)->sin6_addr); + return &(reinterpret_cast(sAddr)->sin6_addr); } - in6_addr* try_sockaddr2in6_addr(sockaddr* sa) + in6_addr* try_sockaddr2in6_addr(sockaddr* sAddr) { try { - return sockaddr2in6_addr(sa); + return sockaddr2in6_addr(sAddr); } catch (const std::invalid_argument& e) { @@ -66,20 +74,24 @@ namespace pcpp } } - void sockaddr2string(sockaddr const* sa, char* resultString, size_t resultBufLen) + void sockaddr2string(const sockaddr* sAddr, char* resultString, size_t resultBufLen) { - if (sa == nullptr) + if (sAddr == nullptr) + { throw std::invalid_argument("sockaddr is nullptr"); + } - switch (sa->sa_family) + switch (sAddr->sa_family) { case AF_INET: { 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(sAddr)->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(sAddr)->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..4a4b427eae 100644 --- a/Common++/src/Logger.cpp +++ b/Common++/src/Logger.cpp @@ -1,3 +1,4 @@ +#include #include #include "Logger.h" @@ -7,8 +8,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 +30,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 +41,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/MacAddress.cpp b/Common++/src/MacAddress.cpp index 47d990a017..01709b529c 100644 --- a/Common++/src/MacAddress.cpp +++ b/Common++/src/MacAddress.cpp @@ -10,7 +10,7 @@ namespace pcpp char str[19]; snprintf(str, sizeof str, "%02x:%02x:%02x:%02x:%02x:%02x", m_Address[0], m_Address[1], m_Address[2], m_Address[3], m_Address[4], m_Address[5]); - return std::string(str); + return str; } MacAddress::MacAddress(const std::string& address) diff --git a/Common++/src/OUILookup.cpp b/Common++/src/OUILookup.cpp index d116ee8388..f75665ff77 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(maskValue, std::unordered_map{}); // 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 9a5bc84a92..6dc85d8dba 100644 --- a/Common++/src/SystemUtils.cpp +++ b/Common++/src/SystemUtils.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #if defined(__APPLE__) # include # include @@ -121,13 +122,13 @@ namespace pcpp GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #else - return sysconf(_SC_NPROCESSORS_ONLN); + return static_cast(sysconf(_SC_NPROCESSORS_ONLN)); #endif } 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++) { @@ -163,47 +164,51 @@ namespace pcpp void createCoreVectorFromCoreMask(CoreMask coreMask, std::vector& resultVec) { - int i = 0; + int idx = 0; while (coreMask != 0) { - if (1 & coreMask) + if ((1 & coreMask) != 0U) { - resultVec.push_back(SystemCores::IdToSystemCore[i]); + resultVec.push_back(SystemCores::IdToSystemCore[idx]); } coreMask = coreMask >> 1; - i++; + ++idx; } } 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) - return true; - else - return false; + } + return (info.st_mode & S_IFDIR) != 0; } int clockGetTime(long& sec, long& nsec) @@ -255,14 +260,14 @@ namespace pcpp #else // Linux -# include +# include - timespec ts; - int res = clock_gettime(CLOCK_REALTIME, &ts); + timespec tspec{}; + const int res = clock_gettime(CLOCK_REALTIME, &tspec); if (res == 0) { - sec = ts.tv_sec; - nsec = ts.tv_nsec; + sec = tspec.tv_sec; + nsec = tspec.tv_nsec; } return res; @@ -271,20 +276,12 @@ namespace pcpp void multiPlatformSleep(uint32_t seconds) { -#if defined(_WIN32) - Sleep(seconds * 1000); -#else - sleep(seconds); -#endif + std::this_thread::sleep_for(std::chrono::seconds(seconds)); } void multiPlatformMSleep(uint32_t milliseconds) { -#if defined(_WIN32) - Sleep(milliseconds); -#else - usleep(milliseconds * 1000); -#endif + std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); } uint16_t hostToNet16(uint16_t host) @@ -344,8 +341,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; @@ -371,7 +370,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(); } diff --git a/ci/clang-tidy-all.sh b/ci/clang-tidy-all.sh index c2cd4031c6..3f9a204632 100755 --- a/ci/clang-tidy-all.sh +++ b/ci/clang-tidy-all.sh @@ -1,7 +1,7 @@ #!/bin/sh set -e -IGNORE_LIST=".*dirent.* .*DpdkDevice* .*KniDevice* .*MBufRawPacket* .*PfRingDevice* .*RemoteDevice* .*XdpDevice* .*WinPcap*" +IGNORE_LIST=".*dirent.* .*DpdkDevice* .*KniDevice* .*MBufRawPacket* .*PfRingDevice* .*RemoteDevice* .*XdpDevice* .*WinPcap* .*Examples* .*Tests* .*build* .*3rdParty* .*Packet\+\+* .*Pcap\+\+*" SCRIPT=$(readlink -f "$0") SCRIPTPATH=$(dirname "${SCRIPT}") @@ -39,5 +39,5 @@ echo "$files" | while IFS= read -r file; do fi done echo "Checking: $file" - clang-tidy "$file" -p $BUILD_DIR --fix --checks=modernize-use-nullptr,modernize-use-override,performance-unnecessary-value-param + clang-tidy "$file" -p $BUILD_DIR --fix-errors done