diff --git a/.clang-tidy-new b/.clang-tidy-new new file mode 100644 index 0000000000..c32d3842fc --- /dev/null +++ b/.clang-tidy-new @@ -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++/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 29096b524a..38936e8570 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; } @@ -276,7 +276,7 @@ namespace pcpp { public: /// An enum representing the address type: IPv4 or IPv6 - enum AddressType + enum AddressType : uint8_t { /// IPv4 address type IPv4AddressType, @@ -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 @@ -692,14 +694,14 @@ namespace pcpp /// @return A reference to the assignee IPNetwork& operator=(const IPNetwork& other) { + // NOLINTBEGIN(cppcoreguidelines-c-copy-assignment-signature,misc-unconventional-assign-operator) if (other.isIPv4Network()) { return this->operator=(*other.m_IPv4Network); } - else - { - return this->operator=(*other.m_IPv6Network); - } + + return this->operator=(*other.m_IPv6Network); + // NOLINTEND(cppcoreguidelines-c-copy-assignment-signature,misc-unconventional-assign-operator) } /// Overload of an assignment operator. @@ -796,15 +798,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 @@ -820,15 +820,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: @@ -843,40 +841,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..2b5ec3954f 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 @@ -48,7 +48,7 @@ namespace pcpp { /// An enum representing all PcapPlusPlus modules - enum LogModule + enum LogModule : uint8_t { UndefinedLogModule, CommonLogModuleIpUtils, ///< IP Utils module (Common++) @@ -113,6 +113,11 @@ namespace pcpp NumOfLogModules }; + /// Cross-platform and thread-safe version of strerror + /// @param errnum Value of errno + /// @return String representation of the error number + std::string getErrorString(int errnum); + /// @class Logger /// PcapPlusPlus logger manager. /// PcapPlusPlus uses this logger to output both error and debug logs. @@ -135,7 +140,7 @@ 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 - enum LogLevel + enum LogLevel : uint8_t { Error, ///< Error log level Info, ///< Info log level @@ -149,8 +154,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 +190,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 +239,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 +256,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..e34c9d99a9 100644 --- a/Common++/header/MacAddress.h +++ b/Common++/header/MacAddress.h @@ -4,8 +4,8 @@ #include #include #include -#include -#include +#include +#include #include /// @file @@ -52,8 +52,8 @@ namespace pcpp /// @param[in] fourthOctet Represent the fourth octet in the address /// @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) + 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; @@ -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..399d7c62df 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. @@ -86,6 +85,12 @@ namespace pcpp /// @return A reference to the current object. PointerVector& operator=(const PointerVector& other) { + // Self-assignment check. + if (this == &other) + { + return *this; + } + // Saves a copy of the old pointer to defer cleanup. auto oldValues = m_Vector; try @@ -277,7 +282,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 +309,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 +340,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..f638a8dbb2 100644 --- a/Common++/header/SystemUtils.h +++ b/Common++/header/SystemUtils.h @@ -1,12 +1,17 @@ #pragma once -#include +#include "DeprecationUtils.h" + +#include #include #include /// @file -#define MAX_NUM_OF_CORES 32 +enum : uint8_t +{ + MAX_NUM_OF_CORES = 32 +}; #ifdef _MSC_VER int gettimeofday(struct timeval* tp, struct timezone* tzp); @@ -112,7 +117,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 @@ -158,11 +163,17 @@ namespace pcpp /// 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 + /// @deprecated Please use std::this_thread::sleep_for(). It is a standard C++ (since C++11) method which is already + /// cross-platform + PCPP_DEPRECATED("Please use std::this_thread::sleep_for(std::chrono::seconds(seconds)) instead") 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. /// @param[in] milliseconds Number of milliseconds to sleep + /// @deprecated Please use std::this_thread::sleep_for(). It is a standard C++ (since C++11) method which is already + /// cross-platform + PCPP_DEPRECATED("Please use std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)) instead") void multiPlatformMSleep(uint32_t milliseconds); /// A multi-platform version of `htons` which convert host to network byte order @@ -247,7 +258,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..90ef1b59fe 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,7 @@ namespace pcpp bool IPv4Address::isValidIPv4Address(const std::string& addrAsString) { - struct sockaddr_in sa_in; + sockaddr_in sa_in{}; return inet_pton(AF_INET, addrAsString.data(), &(sa_in.sin_addr)) > 0; } @@ -86,9 +88,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 +137,7 @@ namespace pcpp bool IPv6Address::isValidIPv6Address(const std::string& addrAsString) { - struct sockaddr_in6 sa_in6; + sockaddr_in6 sa_in6{}; return inet_pton(AF_INET6, addrAsString.data(), &(sa_in6.sin6_addr)) > 0; } @@ -170,18 +174,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 +229,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 +252,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 +281,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 +311,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 +347,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 +367,15 @@ namespace pcpp { memset(m_Mask, 0, IPV6_ADDR_SIZE); int remainingPrefixLen = prefixLen; - for (auto byteIndex = 0; byteIndex < IPV6_ADDR_SIZE; byteIndex++) + for (auto& byte : m_Mask) { if (remainingPrefixLen >= 8) { - m_Mask[byteIndex] = 0xff; + byte = 0xff; } else if (remainingPrefixLen > 0) { - m_Mask[byteIndex] = 0xff << (8 - remainingPrefixLen); + byte = 0xff << (8 - remainingPrefixLen); } else { @@ -433,7 +436,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 +458,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 +488,10 @@ namespace pcpp uint8_t IPv6Network::getPrefixLen() const { uint8_t result = 0; - for (auto byteIndex = 0; byteIndex < IPV6_ADDR_SIZE; byteIndex++) + for (const auto& byte : m_Mask) { - std::bitset<8> bs(m_Mask[byteIndex]); - result += static_cast(bs.count()); + const std::bitset<8> bset(byte); + result += static_cast(bset.count()); } return result; } @@ -520,10 +524,10 @@ namespace pcpp uint64_t IPv6Network::getTotalAddressCount() const { int numOfBitset = 0; - for (auto byteIndex = 0; byteIndex < IPV6_ADDR_SIZE; byteIndex++) + for (const auto& byte : m_Mask) { - std::bitset<8> bitset(static_cast(~m_Mask[byteIndex])); - numOfBitset += bitset.count(); + const std::bitset<8> bitset(static_cast(~byte)); + 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..e67388ea5a 100644 --- a/Common++/src/Logger.cpp +++ b/Common++/src/Logger.cpp @@ -1,14 +1,39 @@ +#include +#include +#include #include #include "Logger.h" namespace pcpp { + // Alpine Linux incorrectly declares strerror_r + // https://stackoverflow.com/questions/41953104/strerror-r-is-incorrectly-declared-on-alpine-linux + char* checkError(int /*unused*/, char* buffer, int /*unused*/) + { + return buffer; + } + + char* checkError(char* result, const char* /*unused*/, int /*unused*/) + { + return result; + } + + std::string getErrorString(int errnum) + { + std::array buffer{}; +#if defined(_WIN32) + strerror_s(buffer.data(), buffer.size(), errnum); + return buffer.data(); +#else + return checkError(strerror_r(errnum, buffer.data(), BUFSIZ), buffer.data(), errnum); +#endif + } + 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 +55,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 +66,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..18886faaea 100644 --- a/Common++/src/MacAddress.cpp +++ b/Common++/src/MacAddress.cpp @@ -8,9 +8,12 @@ namespace pcpp 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); + if (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]) < 0) + { + throw std::runtime_error("Conversion of MAC address to string failed"); + } + return str; } MacAddress::MacAddress(const std::string& address) @@ -18,6 +21,7 @@ namespace pcpp constexpr size_t validMacAddressLength = 17; unsigned int values[6]; if (address.size() != validMacAddressLength || + // NOLINTNEXTLINE(cert-err34-c) sscanf(address.c_str(), "%x:%x:%x:%x:%x:%x", &values[0], &values[1], &values[2], &values[3], &values[4], &values[5]) != 6) { diff --git a/Common++/src/OUILookup.cpp b/Common++/src/OUILookup.cpp index d116ee8388..6d1700a572 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()) @@ -70,7 +76,7 @@ namespace pcpp dataFile.open(path); if (!dataFile.is_open()) { - PCPP_LOG_ERROR(std::string("Can't open OUI database: ") + strerror(errno)); + PCPP_LOG_ERROR(std::string("Can't open OUI database: ") + getErrorString(errno)); return -1; } @@ -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..91e76583f4 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,49 @@ 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 +258,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 +274,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 +339,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 +368,7 @@ 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/Examples/ArpSpoofing/main.cpp b/Examples/ArpSpoofing/main.cpp index 837e2555be..538dd4c7b8 100644 --- a/Examples/ArpSpoofing/main.cpp +++ b/Examples/ArpSpoofing/main.cpp @@ -85,7 +85,7 @@ pcpp::MacAddress getMacAddress(const pcpp::IPv4Address& ipAddr, pcpp::PcapLiveDe pDevice->sendPacket(&arpRequest); pcpp::RawPacketVector capturedPackets; pDevice->startCapture(capturedPackets); - pcpp::multiPlatformSleep(2); + std::this_thread::sleep_for(std::chrono::seconds(2)); pDevice->stopCapture(); if (capturedPackets.size() < 1) @@ -160,7 +160,7 @@ void doArpSpoofing(pcpp::PcapLiveDevice* pDevice, const pcpp::IPv4Address& gatew pDevice->sendPacket(&victimArpReply); std::cout << "Sent ARP reply: " << victimAddr << " [victim] is at MAC address " << deviceMacAddress << " [me]" << std::endl; - pcpp::multiPlatformSleep(5); + std::this_thread::sleep_for(std::chrono::seconds(5)); } } diff --git a/Examples/DnsSpoofing/main.cpp b/Examples/DnsSpoofing/main.cpp index 3e03c6833a..8d7ffb0127 100644 --- a/Examples/DnsSpoofing/main.cpp +++ b/Examples/DnsSpoofing/main.cpp @@ -348,7 +348,7 @@ void doDnsSpoofing(pcpp::PcapLiveDevice* dev, const pcpp::IPAddress& dnsServer, while (!args.shouldStop) { std::cout << "Spoofed " << args.stats.numOfSpoofedDnsRequests << " DNS requests so far" << std::endl; - pcpp::multiPlatformSleep(5); + std::this_thread::sleep_for(std::chrono::seconds(5)); } } diff --git a/Examples/HttpAnalyzer/main.cpp b/Examples/HttpAnalyzer/main.cpp index 372d89b10a..b321e3cab0 100644 --- a/Examples/HttpAnalyzer/main.cpp +++ b/Examples/HttpAnalyzer/main.cpp @@ -468,7 +468,7 @@ void analyzeHttpFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriod while (!shouldStop) { - pcpp::multiPlatformSleep(printRatePeriod); + std::this_thread::sleep_for(std::chrono::seconds(printRatePeriod)); // calculate rates if (printRatesPeriodically) diff --git a/Examples/IcmpFileTransfer/IcmpFileTransfer-pitcher.cpp b/Examples/IcmpFileTransfer/IcmpFileTransfer-pitcher.cpp index e17382f498..59019d0745 100644 --- a/Examples/IcmpFileTransfer/IcmpFileTransfer-pitcher.cpp +++ b/Examples/IcmpFileTransfer/IcmpFileTransfer-pitcher.cpp @@ -269,7 +269,7 @@ void receiveFile(pcpp::IPv4Address pitcherIP, pcpp::IPv4Address catcherIP, int p nullptr, 0); icmpId++; // sleep for a few seconds between sending the message - pcpp::multiPlatformSleep(SEND_TIMEOUT_BEFORE_FT_START); + std::this_thread::sleep_for(std::chrono::seconds(SEND_TIMEOUT_BEFORE_FT_START)); } // stop capturing packets @@ -318,7 +318,7 @@ void receiveFile(pcpp::IPv4Address pitcherIP, pcpp::IPv4Address catcherIP, int p if (packetPerSec > 1) usleep(sleepBetweenPackets); else if (packetPerSec == 1) - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); icmpId++; } @@ -504,7 +504,7 @@ void sendFile(const std::string& filePath, pcpp::IPv4Address pitcherIP, pcpp::IP if (packetPerSec > 1) usleep(sleepBetweenPackets); else if (packetPerSec == 1) - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); bytesSentSoFar += blockSize; diff --git a/Examples/SSLAnalyzer/main.cpp b/Examples/SSLAnalyzer/main.cpp index d600cfa196..bf644e748b 100644 --- a/Examples/SSLAnalyzer/main.cpp +++ b/Examples/SSLAnalyzer/main.cpp @@ -437,7 +437,7 @@ void analyzeSSLFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriodi while (!shouldStop) { - pcpp::multiPlatformSleep(printRatePeriod); + std::this_thread::sleep_for(std::chrono::seconds(printRatePeriod)); // calculate rates if (printRatesPeriodically) diff --git a/Examples/TLSFingerprinting/main.cpp b/Examples/TLSFingerprinting/main.cpp index 87acfa5af0..3c25dea9cb 100644 --- a/Examples/TLSFingerprinting/main.cpp +++ b/Examples/TLSFingerprinting/main.cpp @@ -516,7 +516,7 @@ void doTlsFingerprintingOnLiveTraffic(const std::string& interfaceNameOrIP, std: // run in an endless loop until the user press ctrl+c while (!shouldStop) - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); // stop capturing and close the live device dev->stopCapture(); diff --git a/Examples/TcpReassembly/main.cpp b/Examples/TcpReassembly/main.cpp index 56546258c2..5b6b8a5209 100644 --- a/Examples/TcpReassembly/main.cpp +++ b/Examples/TcpReassembly/main.cpp @@ -583,7 +583,7 @@ void doTcpReassemblyOnLiveTraffic(pcpp::PcapLiveDevice* dev, pcpp::TcpReassembly // run in an endless loop until the user presses ctrl+c while (!shouldStop) - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); // stop capturing and close the live device dev->stopCapture(); diff --git a/Examples/Tutorials/Tutorial-LiveTraffic/main.cpp b/Examples/Tutorials/Tutorial-LiveTraffic/main.cpp index 3f10863e99..2dbeb6fe60 100644 --- a/Examples/Tutorials/Tutorial-LiveTraffic/main.cpp +++ b/Examples/Tutorials/Tutorial-LiveTraffic/main.cpp @@ -152,7 +152,7 @@ int main(int argc, char* argv[]) dev->startCapture(onPacketArrives, &stats); // sleep for 10 seconds in main thread, in the meantime packets are captured in the async thread - pcpp::multiPlatformSleep(10); + std::this_thread::sleep_for(std::chrono::seconds(10)); // stop capturing packets dev->stopCapture(); @@ -176,7 +176,7 @@ int main(int argc, char* argv[]) dev->startCapture(packetVec); // sleep for 10 seconds in main thread, in the meantime packets are captured in the async thread - pcpp::multiPlatformSleep(10); + std::this_thread::sleep_for(std::chrono::seconds(10)); // stop capturing packets dev->stopCapture(); @@ -264,7 +264,7 @@ int main(int argc, char* argv[]) dev->startCapture(onPacketArrives, &stats); // sleep for 10 seconds in main thread, in the meantime packets are captured in the async thread - pcpp::multiPlatformSleep(10); + std::this_thread::sleep_for(std::chrono::seconds(10)); // stop capturing packets dev->stopCapture(); diff --git a/Pcap++/src/PcapLiveDevice.cpp b/Pcap++/src/PcapLiveDevice.cpp index c5d33c4048..cff0fdd476 100644 --- a/Pcap++/src/PcapLiveDevice.cpp +++ b/Pcap++/src/PcapLiveDevice.cpp @@ -249,7 +249,7 @@ namespace pcpp PcapStats stats; getStatistics(stats); m_cbOnStatsUpdate(stats, m_cbOnStatsUpdateUserCookie); - multiPlatformSleep(m_IntervalToUpdateStats); + std::this_thread::sleep_for(std::chrono::seconds(m_IntervalToUpdateStats)); } PCPP_LOG_DEBUG("Ended stats thread for device '" << m_InterfaceDetails.name << "'"); } diff --git a/Tests/Pcap++Test/Tests/DpdkTests.cpp b/Tests/Pcap++Test/Tests/DpdkTests.cpp index b71226c3a2..169fc678fa 100644 --- a/Tests/Pcap++Test/Tests/DpdkTests.cpp +++ b/Tests/Pcap++Test/Tests/DpdkTests.cpp @@ -6,6 +6,7 @@ #ifdef USE_DPDK # include +# include # include "Logger.h" # include "PacketUtils.h" # include "IPv4Layer.h" @@ -57,7 +58,7 @@ int incSleep(int maxSleepTime, int minPacketCount, const DpdkPacketData& packetD int totalSleepTime = 0; while (totalSleepTime < maxSleepTime) { - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); totalSleepTime += 1; if (packetData.PacketCount > minPacketCount) break; @@ -72,7 +73,7 @@ int incSleepMultiThread(int maxSleepTime, DpdkPacketData packetData[], int total int totalSleepTime = 0; while (totalSleepTime < maxSleepTime) { - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); totalSleepTime += 1; int coresWithPacketCountNotZero = 0; @@ -665,7 +666,7 @@ PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) while (rxQueueId < numOfRxQueues) { dev->receivePackets(rawPacketVec, rxQueueId); - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); if (rawPacketVec.size() > 0) { isPacketRecvd = true; @@ -693,7 +694,7 @@ PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) while (rxQueueId < numOfRxQueues) { mBufRawPacketArrLen = dev->receivePackets(mBufRawPacketArr, 32, rxQueueId); - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); if (mBufRawPacketArrLen > 0) { isPacketRecvd = true; @@ -726,7 +727,7 @@ PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) while (rxQueueId < numOfRxQueues) { packetArrLen = dev->receivePackets(packetArr, 32, rxQueueId); - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); if (packetArrLen > 0) { isPacketRecvd = true; @@ -797,7 +798,7 @@ PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) PTF_PRINT_VERBOSE("Bytes captured on RX queue #" << i << " according to stats: " << stats.rxStats[i].bytes); } - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); if (stats.aggregatedRxStats.packets > curPackets) break; @@ -900,7 +901,7 @@ PTF_TEST_CASE(TestDpdkMbufRawPacket) for (int i = 0; i < dev->getNumOfOpenedRxQueues(); i++) { dev->receivePackets(rawPacketVec, i); - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); for (pcpp::MBufRawPacketVector::VectorIterator iter = rawPacketVec.begin(); iter != rawPacketVec.end(); iter++) { diff --git a/Tests/Pcap++Test/Tests/FilterTests.cpp b/Tests/Pcap++Test/Tests/FilterTests.cpp index 13f656fbb0..bb23059375 100644 --- a/Tests/Pcap++Test/Tests/FilterTests.cpp +++ b/Tests/Pcap++Test/Tests/FilterTests.cpp @@ -25,7 +25,7 @@ static int incSleep(const pcpp::RawPacketVector& capturedPackets, size_t expecte return totalSleepTime; } - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); totalSleepTime += 1; } diff --git a/Tests/Pcap++Test/Tests/KniTests.cpp b/Tests/Pcap++Test/Tests/KniTests.cpp index 07bb1383ba..b090767f44 100644 --- a/Tests/Pcap++Test/Tests/KniTests.cpp +++ b/Tests/Pcap++Test/Tests/KniTests.cpp @@ -7,6 +7,7 @@ # include "PcapFileDevice.h" # include "RawSocketDevice.h" # include "SystemUtils.h" +# include extern PcapTestArgs PcapTestGlobalArgs; @@ -193,7 +194,7 @@ PTF_TEST_CASE(TestKniDevice) PTF_ASSERT_TRUE(device->open()); PTF_ASSERT_TRUE(device->startRequestHandlerThread(0, 150000000)); - pcpp::multiPlatformSleep(2); // Wait for thread to start + std::this_thread::sleep_for(std::chrono::seconds(2)); // Wait for thread to start if (pcpp::KniDeviceList::isCallbackSupported(pcpp::KniDeviceList::CALLBACK_PROMISC)) { bool modeSet = device->setPromiscuous(pcpp::KniDevice::PROMISC_ENABLE); @@ -337,7 +338,7 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) PTF_ASSERT_TRUE(device->startRequestHandlerThread(0, 250000000)); KniDeviceTeardown devTeardown(device); - pcpp::multiPlatformSleep(1); // Wait for thread to start + std::this_thread::sleep_for(std::chrono::seconds(1)); // Wait for thread to start // KNI device management PTF_ASSERT_TRUE(setKniDeviceIp(kniIp, KNI_DEVICE1)); @@ -363,7 +364,7 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) pcpp::Logger::getInstance().suppressLogs(); PTF_ASSERT_FALSE(device->startCapture(KniRequestsCallbacksMock::onPacketsMock, NULL)); pcpp::Logger::getInstance().enableLogs(); - pcpp::multiPlatformSleep(1); // Give some time to start capture thread + std::this_thread::sleep_for(std::chrono::seconds(1)); // Give some time to start capture thread for (int i = 0; i < 10; ++i) { fileReaderDev.getNextPacket(rawPacket); @@ -374,12 +375,12 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) rsdevice.sendPackets(rawPacketVec); pcpp::Logger::getInstance().enableLogs(); rawPacketVec.clear(); - pcpp::multiPlatformSleep(1); // Give some time to receive packets + std::this_thread::sleep_for(std::chrono::seconds(1)); // Give some time to receive packets device->stopCapture(); PTF_PRINT_VERBOSE("KNI have captured " << counter << " packets in single burst on device " << KNI_DEVICE1); counter = 0; PTF_ASSERT_TRUE(device->startCapture(KniRequestsCallbacksMock::onPacketsCallback, &counter)); - pcpp::multiPlatformSleep(1); // Give some time to start capture thread + std::this_thread::sleep_for(std::chrono::seconds(1)); // Give some time to start capture thread pcpp::Logger::getInstance().suppressLogs(); PTF_ASSERT_EQUAL(device->receivePackets(mbufRawPacketVec), 0); PTF_ASSERT_EQUAL(device->receivePackets(mBufRawPacketArr, mBufRawPacketArrLen), 0); @@ -395,7 +396,7 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) rsdevice.sendPackets(rawPacketVec); pcpp::Logger::getInstance().enableLogs(); rawPacketVec.clear(); - pcpp::multiPlatformSleep(1); // Give some time to receive packets + std::this_thread::sleep_for(std::chrono::seconds(1)); // Give some time to receive packets device->stopCapture(); PTF_PRINT_VERBOSE("KNI have captured " << counter << " packets on device " << KNI_DEVICE1); counter = 0; diff --git a/Tests/Pcap++Test/Tests/LiveDeviceTests.cpp b/Tests/Pcap++Test/Tests/LiveDeviceTests.cpp index a8ee8dbad8..19d4954a02 100644 --- a/Tests/Pcap++Test/Tests/LiveDeviceTests.cpp +++ b/Tests/Pcap++Test/Tests/LiveDeviceTests.cpp @@ -316,7 +316,7 @@ PTF_TEST_CASE(TestPcapLiveDevice) int totalSleepTime = 0; while (totalSleepTime <= 20) { - pcpp::multiPlatformSleep(2); + std::this_thread::sleep_for(std::chrono::seconds(2)); totalSleepTime += 2; if (packetCount > 0) break; @@ -377,7 +377,7 @@ PTF_TEST_CASE(TestPcapLiveDeviceClone) int totalSleepTime = 0; while (totalSleepTime <= 20) { - pcpp::multiPlatformSleep(2); + std::this_thread::sleep_for(std::chrono::seconds(2)); totalSleepTime += 2; if (packetCount > 0) break; @@ -447,7 +447,7 @@ PTF_TEST_CASE(TestPcapLiveDeviceStatsMode) int totalSleepTime = 0; while (totalSleepTime <= 6) { - pcpp::multiPlatformSleep(2); + std::this_thread::sleep_for(std::chrono::seconds(2)); totalSleepTime += 2; pcpp::IPcapDevice::PcapStats statistics; liveDev->getStatistics(statistics); @@ -515,7 +515,7 @@ PTF_TEST_CASE(TestPcapLiveDeviceBlockingMode) int totalSleepTime = 0; while (totalSleepTime <= 5) { - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); totalSleepTime += 1; if (packetCount > 0) break; @@ -554,7 +554,7 @@ PTF_TEST_CASE(TestPcapLiveDeviceBlockingMode) totalSleepTime = 0; while (totalSleepTime <= 5) { - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); totalSleepTime += 1; if (packetCount > 0) break; @@ -599,7 +599,7 @@ PTF_TEST_CASE(TestPcapLiveDeviceWithLambda) int totalSleepTime = 0; while (totalSleepTime <= 20) { - pcpp::multiPlatformSleep(2); + std::this_thread::sleep_for(std::chrono::seconds(2)); totalSleepTime += 2; if (packetCount > 0) break; @@ -985,7 +985,7 @@ PTF_TEST_CASE(TestRemoteCapture) break; } - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); totalSleepTime += 1; } diff --git a/Tests/Pcap++Test/Tests/LoggerTests.cpp b/Tests/Pcap++Test/Tests/LoggerTests.cpp index 00f06d332a..2d53a491e8 100644 --- a/Tests/Pcap++Test/Tests/LoggerTests.cpp +++ b/Tests/Pcap++Test/Tests/LoggerTests.cpp @@ -155,7 +155,7 @@ void printLogThread(int threadId) { pcpp::invokeErrorLog(threadIdAsString); int sleepTime = dist(simpleRand); - pcpp::multiPlatformMSleep(sleepTime); + std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); } } diff --git a/Tests/Pcap++Test/Tests/PfRingTests.cpp b/Tests/Pcap++Test/Tests/PfRingTests.cpp index a8adf6787a..aa97ac748a 100644 --- a/Tests/Pcap++Test/Tests/PfRingTests.cpp +++ b/Tests/Pcap++Test/Tests/PfRingTests.cpp @@ -10,6 +10,7 @@ # include "PfRingDeviceList.h" # include "PcapFileDevice.h" # include "PcapLiveDeviceList.h" +# include #endif extern PcapTestArgs PcapTestGlobalArgs; @@ -141,7 +142,7 @@ int incSleep(int maxSleepTime, const PfRingPacketData& packetData) int totalSleepTime = 0; while (totalSleepTime < maxSleepTime) { - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); totalSleepTime += 1; if (packetData.PacketCount > 0) break; @@ -156,7 +157,7 @@ int incSleepMultiThread(int maxSleepTime, PfRingPacketData packetData[], int tot int totalSleepTime = 0; while (totalSleepTime < maxSleepTime) { - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); totalSleepTime += 1; int coresWithPacketCountNotZero = 0; @@ -181,7 +182,7 @@ int incSleepSetFilter(int maxSleepTime, const SetFilterInstruction& packetData) int totalSleepTime = 0; while (totalSleepTime < maxSleepTime) { - pcpp::multiPlatformSleep(1); + std::this_thread::sleep_for(std::chrono::seconds(1)); totalSleepTime += 1; if (packetData.PacketCount > 0) break; diff --git a/Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp b/Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp index 2635353be3..9b65d9f6a1 100644 --- a/Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp +++ b/Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "EndianPortable.h" #include "SystemUtils.h" #include "TcpReassembly.h" @@ -1137,7 +1138,7 @@ PTF_TEST_CASE(TestTcpReassemblyCleanup) PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn2->second), 0); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn3->second), 0); - pcpp::multiPlatformSleep(3); + std::this_thread::sleep_for(std::chrono::seconds(3)); tcpReassembly.reassemblePacket(&lastPacket); // automatic cleanup of 1 item PTF_ASSERT_EQUAL(tcpReassembly.getConnectionInformation().size(), 2); diff --git a/ci/clang-tidy-all-new.sh b/ci/clang-tidy-all-new.sh new file mode 100755 index 0000000000..6d0dce5570 --- /dev/null +++ b/ci/clang-tidy-all-new.sh @@ -0,0 +1,43 @@ +#!/bin/sh +set -e + +IGNORE_LIST=".*dirent.* .*DpdkDevice* .*KniDevice* .*MBufRawPacket* .*PfRingDevice* .*RemoteDevice* .*XdpDevice* .*WinPcap* .*Examples* .*Tests* .*build* .*3rdParty* .*Packet\+\+* .*Pcap\+\+*" + +SCRIPT=$(readlink -f "$0") +SCRIPTPATH=$(dirname "${SCRIPT}") +ROOTPATH=$(realpath "${SCRIPTPATH}"/..) +if ! command -v clang-tidy; then + echo "clang-tidy is not found!" + exit 1 +fi + +# Determine the mode (all files or changed files) +MODE=${1:-all} +BUILD_DIR=${2:-build} + +if [ "$MODE" = "changed" ]; then + # Get the list of changed files from origin/dev + git fetch origin dev + files=$(git diff --name-only origin/dev -- '*.cpp' '*.h' | grep -v '3rdParty/' || true) +else + # Find all relevant files + files=$(find "${ROOTPATH}" -type f \( -name '*.cpp' -o -name '*.h' \) -not -path "*/3rdParty/*") +fi + +# Check if there are any files to process +if [ -z "$files" ]; then + echo "No files to process." + exit 0 +fi + +# Process each file +echo "$files" | while IFS= read -r file; do + for ignore in $IGNORE_LIST; do + if echo "$file" | grep -qE "$ignore"; then + echo "Ignoring: $file" + continue 2 + fi + done + echo "Checking: $file" + clang-tidy "$file" -p $BUILD_DIR --fix +done