From feba0b7124a4536ec2a0a947bc96c146ada099d7 Mon Sep 17 00:00:00 2001 From: lumiZGorlic <45258126+lumiZGorlic@users.noreply.github.com> Date: Wed, 20 Nov 2024 08:18:06 +0100 Subject: [PATCH] Use `unique_ptr` and C++ casting in Examples (#1643) --- Examples/ArpSpoofing/main.cpp | 6 +-- Examples/Arping/main.cpp | 2 +- Examples/HttpAnalyzer/HttpStatsCollector.h | 22 +++++----- Examples/HttpAnalyzer/main.cpp | 17 ++++---- Examples/PcapSplitter/main.cpp | 48 ++++++++++------------ Examples/SSLAnalyzer/SSLStatsCollector.h | 6 +-- Examples/SSLAnalyzer/main.cpp | 17 ++++---- 7 files changed, 55 insertions(+), 63 deletions(-) diff --git a/Examples/ArpSpoofing/main.cpp b/Examples/ArpSpoofing/main.cpp index 6f452a685d..837e2555be 100644 --- a/Examples/ArpSpoofing/main.cpp +++ b/Examples/ArpSpoofing/main.cpp @@ -65,7 +65,7 @@ pcpp::MacAddress getMacAddress(const pcpp::IPv4Address& ipAddr, pcpp::PcapLiveDe pcpp::MacAddress macSrc = pDevice->getMacAddress(); pcpp::MacAddress macDst(0xff, 0xff, 0xff, 0xff, 0xff, 0xff); - pcpp::EthLayer ethLayer(macSrc, macDst, (uint16_t)PCPP_ETHERTYPE_ARP); + pcpp::EthLayer ethLayer(macSrc, macDst, static_cast(PCPP_ETHERTYPE_ARP)); pcpp::ArpLayer arpLayer(pcpp::ARP_REQUEST, pDevice->getMacAddress(), pDevice->getMacAddress(), pDevice->getIPv4Address(), ipAddr); @@ -136,7 +136,7 @@ void doArpSpoofing(pcpp::PcapLiveDevice* pDevice, const pcpp::IPv4Address& gatew // Create ARP reply for the gateway pcpp::Packet gwArpReply(500); - pcpp::EthLayer gwEthLayer(deviceMacAddress, gatewayMacAddr, (uint16_t)PCPP_ETHERTYPE_ARP); + pcpp::EthLayer gwEthLayer(deviceMacAddress, gatewayMacAddr, static_cast(PCPP_ETHERTYPE_ARP)); pcpp::ArpLayer gwArpLayer(pcpp::ARP_REPLY, pDevice->getMacAddress(), gatewayMacAddr, victimAddr, gatewayAddr); gwArpReply.addLayer(&gwEthLayer); gwArpReply.addLayer(&gwArpLayer); @@ -144,7 +144,7 @@ void doArpSpoofing(pcpp::PcapLiveDevice* pDevice, const pcpp::IPv4Address& gatew // Create ARP reply for the victim pcpp::Packet victimArpReply(500); - pcpp::EthLayer victimEthLayer(deviceMacAddress, victimMacAddr, (uint16_t)PCPP_ETHERTYPE_ARP); + pcpp::EthLayer victimEthLayer(deviceMacAddress, victimMacAddr, static_cast(PCPP_ETHERTYPE_ARP)); pcpp::ArpLayer victimArpLayer(pcpp::ARP_REPLY, pDevice->getMacAddress(), victimMacAddr, gatewayAddr, victimAddr); victimArpReply.addLayer(&victimEthLayer); victimArpReply.addLayer(&victimArpLayer); diff --git a/Examples/Arping/main.cpp b/Examples/Arping/main.cpp index a7871a0efe..446744b2de 100644 --- a/Examples/Arping/main.cpp +++ b/Examples/Arping/main.cpp @@ -101,7 +101,7 @@ void listInterfaces() */ void onApplicationInterrupted(void* cookie) { - auto shouldStop = (bool*)cookie; + auto shouldStop = static_cast(cookie); *shouldStop = true; } diff --git a/Examples/HttpAnalyzer/HttpStatsCollector.h b/Examples/HttpAnalyzer/HttpStatsCollector.h index 42cfa5c09c..9554509641 100644 --- a/Examples/HttpAnalyzer/HttpStatsCollector.h +++ b/Examples/HttpAnalyzer/HttpStatsCollector.h @@ -347,9 +347,9 @@ class HttpStatsCollector if (m_FlowTable.size() != 0) { m_GeneralStats.averageAmountOfDataPerFlow = - (double)m_GeneralStats.amountOfHttpTraffic / (double)m_FlowTable.size(); + static_cast(m_GeneralStats.amountOfHttpTraffic) / static_cast(m_FlowTable.size()); m_GeneralStats.averageNumOfPacketsPerFlow = - (double)m_GeneralStats.numOfHttpPackets / (double)m_FlowTable.size(); + static_cast(m_GeneralStats.numOfHttpPackets) / static_cast(m_FlowTable.size()); } return hashVal; @@ -419,7 +419,8 @@ class HttpStatsCollector // calc average transactions per flow if (m_FlowTable.size() != 0) m_GeneralStats.averageNumOfHttpTransactionsPerFlow = - (double)m_GeneralStats.numOfHttpTransactions / (double)m_FlowTable.size(); + static_cast(m_GeneralStats.numOfHttpTransactions) / + static_cast(m_FlowTable.size()); } // set last seen sequence number @@ -435,8 +436,8 @@ class HttpStatsCollector m_RequestStats.numOfMessages++; m_RequestStats.totalMessageHeaderSize += req->getHeaderLen(); if (m_RequestStats.numOfMessages != 0) - m_RequestStats.averageMessageHeaderSize = - (double)m_RequestStats.totalMessageHeaderSize / (double)m_RequestStats.numOfMessages; + m_RequestStats.averageMessageHeaderSize = static_cast(m_RequestStats.totalMessageHeaderSize) / + static_cast(m_RequestStats.numOfMessages); // extract hostname and add to hostname count map pcpp::HeaderField* hostField = req->getFieldByName(PCPP_HTTP_HOST_FIELD); @@ -454,8 +455,8 @@ class HttpStatsCollector m_ResponseStats.numOfMessages++; m_ResponseStats.totalMessageHeaderSize += res->getHeaderLen(); if (m_ResponseStats.numOfMessages != 0) - m_ResponseStats.averageMessageHeaderSize = - (double)m_ResponseStats.totalMessageHeaderSize / (double)m_ResponseStats.numOfMessages; + m_ResponseStats.averageMessageHeaderSize = static_cast(m_ResponseStats.totalMessageHeaderSize) / + static_cast(m_ResponseStats.numOfMessages); // extract content-length (if exists) pcpp::HeaderField* contentLengthField = res->getFieldByName(PCPP_HTTP_CONTENT_LENGTH_FIELD); @@ -464,8 +465,9 @@ class HttpStatsCollector m_ResponseStats.numOfMessagesWithContentLength++; m_ResponseStats.totalContentLengthSize += atoi(contentLengthField->getFieldValue().c_str()); if (m_ResponseStats.numOfMessagesWithContentLength != 0) - m_ResponseStats.averageContentLengthSize = (double)m_ResponseStats.totalContentLengthSize / - (double)m_ResponseStats.numOfMessagesWithContentLength; + m_ResponseStats.averageContentLengthSize = + static_cast(m_ResponseStats.totalContentLengthSize) / + static_cast(m_ResponseStats.numOfMessagesWithContentLength); } // extract content-type and add to content-type map @@ -497,7 +499,7 @@ class HttpStatsCollector gettimeofday(&tv, nullptr); - return (((double)tv.tv_sec) + (double)(tv.tv_usec / 1000000.0)); + return ((static_cast(tv.tv_sec)) + static_cast(tv.tv_usec / 1000000.0)); } HttpGeneralStats m_GeneralStats; diff --git a/Examples/HttpAnalyzer/main.cpp b/Examples/HttpAnalyzer/main.cpp index 1862720114..372d89b10a 100644 --- a/Examples/HttpAnalyzer/main.cpp +++ b/Examples/HttpAnalyzer/main.cpp @@ -17,6 +17,7 @@ * For more details about modes of operation and parameters run HttpAnalyzer -h */ +#include #include #include #include "PcapLiveDeviceList.h" @@ -150,7 +151,7 @@ void httpPacketArrive(pcpp::RawPacket* packet, pcpp::PcapLiveDevice* dev, void* // parse the packet pcpp::Packet parsedPacket(packet); - HttpPacketArrivedData* data = (HttpPacketArrivedData*)cookie; + HttpPacketArrivedData* data = static_cast(cookie); // give the packet to the collector data->statsCollector->collectStats(&parsedPacket); @@ -392,7 +393,7 @@ void printCurrentRates(HttpStatsCollector& collector) */ void onApplicationInterrupted(void* cookie) { - bool* shouldStop = (bool*)cookie; + bool* shouldStop = static_cast(cookie); *shouldStop = true; } @@ -402,7 +403,7 @@ void onApplicationInterrupted(void* cookie) void analyzeHttpFromPcapFile(const std::string& pcapFileName, uint16_t dstPort) { // open input file (pcap or pcapng file) - pcpp::IFileReaderDevice* reader = pcpp::IFileReaderDevice::getReader(pcapFileName); + std::unique_ptr reader(pcpp::IFileReaderDevice::getReader(pcapFileName)); if (!reader->open()) EXIT_WITH_ERROR("Could not open input pcap file"); @@ -427,9 +428,6 @@ void analyzeHttpFromPcapFile(const std::string& pcapFileName, uint16_t dstPort) // close input file reader->close(); - - // free reader memory - delete reader; } /** @@ -447,10 +445,10 @@ void analyzeHttpFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriod EXIT_WITH_ERROR("Could not set up filter on device"); // if needed to save the captured packets to file - open a writer device - pcpp::PcapFileWriterDevice* pcapWriter = nullptr; + std::unique_ptr pcapWriter; if (savePacketsToFileName != "") { - pcapWriter = new pcpp::PcapFileWriterDevice(savePacketsToFileName); + pcapWriter.reset(new pcpp::PcapFileWriterDevice(savePacketsToFileName)); if (!pcapWriter->open()) { EXIT_WITH_ERROR("Could not open pcap file for writing"); @@ -461,7 +459,7 @@ void analyzeHttpFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriod HttpPacketArrivedData data; HttpStatsCollector collector(dstPort); data.statsCollector = &collector; - data.pcapWriter = pcapWriter; + data.pcapWriter = pcapWriter.get(); dev->startCapture(httpPacketArrive, &data); // register the on app close event to print summary stats on app termination @@ -495,7 +493,6 @@ void analyzeHttpFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriod if (pcapWriter != nullptr) { pcapWriter->close(); - delete pcapWriter; } } diff --git a/Examples/PcapSplitter/main.cpp b/Examples/PcapSplitter/main.cpp index 5f05d17086..241b10ac7d 100644 --- a/Examples/PcapSplitter/main.cpp +++ b/Examples/PcapSplitter/main.cpp @@ -45,6 +45,7 @@ */ #include +#include #include #include #include @@ -294,66 +295,67 @@ int main(int argc, char* argv[]) EXIT_WITH_ERROR("Split method was not given"); } - Splitter* splitter = nullptr; + std::unique_ptr splitter; // decide of the splitter to use, according to the user's choice if (method == SPLIT_BY_FILE_SIZE) { uint64_t paramAsUint64 = (paramWasSet ? strtoull(param, nullptr, 10) : 0); - splitter = new FileSizeSplitter(paramAsUint64); + splitter.reset(new FileSizeSplitter(paramAsUint64)); } else if (method == SPLIT_BY_PACKET_COUNT) { int paramAsInt = (paramWasSet ? atoi(param) : 0); - splitter = new PacketCountSplitter(paramAsInt); + splitter.reset(new PacketCountSplitter(paramAsInt)); } else if (method == SPLIT_BY_IP_CLIENT) { int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER); - splitter = new ClientIPSplitter(paramAsInt); + splitter.reset(new ClientIPSplitter(paramAsInt)); } else if (method == SPLIT_BY_IP_SERVER) { int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER); - splitter = new ServerIPSplitter(paramAsInt); + splitter.reset(new ServerIPSplitter(paramAsInt)); } else if (method == SPLIT_BY_SERVER_PORT) { int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER); - splitter = new ServerPortSplitter(paramAsInt); + splitter.reset(new ServerPortSplitter(paramAsInt)); } else if (method == SPLIT_BY_CLIENT_PORT) { int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER); - splitter = new ClientPortSplitter(paramAsInt); + splitter.reset(new ClientPortSplitter(paramAsInt)); } else if (method == SPLIT_BY_2_TUPLE) { int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER); - splitter = new TwoTupleSplitter(paramAsInt); + splitter.reset(new TwoTupleSplitter(paramAsInt)); } else if (method == SPLIT_BY_5_TUPLE) { int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER); - splitter = new FiveTupleSplitter(paramAsInt); + splitter.reset(new FiveTupleSplitter(paramAsInt)); } else if (method == SPLIT_BY_BPF_FILTER) { - splitter = new BpfCriteriaSplitter(std::string(param)); + splitter.reset(new BpfCriteriaSplitter(std::string(param))); } else if (method == SPLIT_BY_ROUND_ROBIN) { int paramAsInt = (paramWasSet ? atoi(param) : 0); - splitter = new RoundRobinSplitter(paramAsInt); + splitter.reset(new RoundRobinSplitter(paramAsInt)); } else + { EXIT_WITH_ERROR("Unknown method '" << method << "'"); + } // verify splitter param is legal, otherwise return an error std::string errorStr; if (!splitter->isSplitterParamLegal(errorStr)) { - delete splitter; EXIT_WITH_ERROR(errorStr); } @@ -362,8 +364,8 @@ int main(int argc, char* argv[]) outputPcapDir + std::string(1, SEPARATOR) + getFileNameWithoutExtension(inputPcapFileName) + "-"; // open a pcap file for reading - pcpp::IFileReaderDevice* reader = pcpp::IFileReaderDevice::getReader(inputPcapFileName); - bool isReaderPcapng = (dynamic_cast(reader) != nullptr); + std::unique_ptr reader(pcpp::IFileReaderDevice::getReader(inputPcapFileName)); + bool isReaderPcapng = (dynamic_cast(reader.get()) != nullptr); if (reader == nullptr || !reader->open()) { @@ -387,7 +389,7 @@ int main(int argc, char* argv[]) pcpp::RawPacket rawPacket; // prepare a map of file number to IFileWriterDevice - std::unordered_map outputFiles; + std::unordered_map> outputFiles; // read all packets from input file, for each packet do: while (reader->getNextPacket(rawPacket)) @@ -411,12 +413,12 @@ int main(int argc, char* argv[]) if (isReaderPcapng) { // if reader is pcapng, create a pcapng writer - outputFiles[fileNum] = new pcpp::PcapNgFileWriterDevice(fileName); + outputFiles[fileNum].reset(new pcpp::PcapNgFileWriterDevice(fileName)); } else { // if reader is pcap, create a pcap writer - outputFiles[fileNum] = new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType()); + outputFiles[fileNum].reset(new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType())); } // open the writer @@ -438,12 +440,12 @@ int main(int argc, char* argv[]) if (isReaderPcapng) { // if reader is pcapng, create a pcapng writer - outputFiles[fileNum] = new pcpp::PcapNgFileWriterDevice(fileName); + outputFiles[fileNum].reset(new pcpp::PcapNgFileWriterDevice(fileName)); } else { // if reader is pcap, create a pcap writer - outputFiles[fileNum] = new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType()); + outputFiles[fileNum].reset(new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType())); } // open the writer in __append__ mode @@ -464,8 +466,7 @@ int main(int argc, char* argv[]) outputFiles[fileId]->close(); // free the writer memory and put null in the map record - delete outputFiles[fileId]; - outputFiles[fileId] = nullptr; + outputFiles[fileId].reset(); } } @@ -478,17 +479,12 @@ int main(int argc, char* argv[]) // close the reader file reader->close(); - // free reader memory - delete reader; - delete splitter; - // close the writer files which are still open for (const auto& it : outputFiles) { if (it.second != nullptr) { it.second->close(); - delete it.second; } } diff --git a/Examples/SSLAnalyzer/SSLStatsCollector.h b/Examples/SSLAnalyzer/SSLStatsCollector.h index bac5d0f050..c7015baa20 100644 --- a/Examples/SSLAnalyzer/SSLStatsCollector.h +++ b/Examples/SSLAnalyzer/SSLStatsCollector.h @@ -302,9 +302,9 @@ class SSLStatsCollector if (m_FlowTable.size() != 0) { m_GeneralStats.averageAmountOfDataPerFlow = - (double)m_GeneralStats.amountOfSSLTraffic / (double)m_FlowTable.size(); + static_cast(m_GeneralStats.amountOfSSLTraffic) / static_cast(m_FlowTable.size()); m_GeneralStats.averageNumOfPacketsPerFlow = - (double)m_GeneralStats.numOfSSLPackets / (double)m_FlowTable.size(); + static_cast(m_GeneralStats.numOfSSLPackets) / static_cast(m_FlowTable.size()); } return hashVal; @@ -406,7 +406,7 @@ class SSLStatsCollector gettimeofday(&tv, nullptr); - return (((double)tv.tv_sec) + (double)(tv.tv_usec / 1000000.0)); + return ((static_cast(tv.tv_sec)) + static_cast(tv.tv_usec / 1000000.0)); } SSLGeneralStats m_GeneralStats; diff --git a/Examples/SSLAnalyzer/main.cpp b/Examples/SSLAnalyzer/main.cpp index 0ea01a9bcb..d600cfa196 100644 --- a/Examples/SSLAnalyzer/main.cpp +++ b/Examples/SSLAnalyzer/main.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include "PcapLiveDeviceList.h" #include "PcapFilter.h" #include "PcapFileDevice.h" @@ -149,7 +150,7 @@ void sslPacketArrive(pcpp::RawPacket* packet, pcpp::PcapLiveDevice* dev, void* c // parse the packet pcpp::Packet parsedPacket(packet); - SSLPacketArrivedData* data = (SSLPacketArrivedData*)cookie; + SSLPacketArrivedData* data = static_cast(cookie); // give the packet to the collector data->statsCollector->collectStats(&parsedPacket); @@ -349,7 +350,7 @@ void printCurrentRates(SSLStatsCollector& collector) */ void onApplicationInterrupted(void* cookie) { - bool* shouldStop = (bool*)cookie; + bool* shouldStop = static_cast(cookie); *shouldStop = true; } @@ -359,7 +360,7 @@ void onApplicationInterrupted(void* cookie) void analyzeSSLFromPcapFile(const std::string& pcapFileName) { // open input file (pcap or pcapng file) - pcpp::IFileReaderDevice* reader = pcpp::IFileReaderDevice::getReader(pcapFileName); + std::unique_ptr reader(pcpp::IFileReaderDevice::getReader(pcapFileName)); if (!reader->open()) EXIT_WITH_ERROR("Could not open input pcap file"); @@ -379,9 +380,6 @@ void analyzeSSLFromPcapFile(const std::string& pcapFileName) // close input file reader->close(); - - // free reader memory - delete reader; } /** @@ -416,10 +414,10 @@ void analyzeSSLFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriodi } // if needed to save the captured packets to file - open a writer device - pcpp::PcapFileWriterDevice* pcapWriter = nullptr; + std::unique_ptr pcapWriter; if (savePacketsToFileName != "") { - pcapWriter = new pcpp::PcapFileWriterDevice(savePacketsToFileName); + pcapWriter.reset(new pcpp::PcapFileWriterDevice(savePacketsToFileName)); if (!pcapWriter->open()) { EXIT_WITH_ERROR("Could not open pcap file for writing"); @@ -430,7 +428,7 @@ void analyzeSSLFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriodi SSLPacketArrivedData data; SSLStatsCollector collector; data.statsCollector = &collector; - data.pcapWriter = pcapWriter; + data.pcapWriter = pcapWriter.get(); dev->startCapture(sslPacketArrive, &data); // register the on app close event to print summary stats on app termination @@ -464,7 +462,6 @@ void analyzeSSLFromLiveTraffic(pcpp::PcapLiveDevice* dev, bool printRatesPeriodi if (pcapWriter != nullptr) { pcapWriter->close(); - delete pcapWriter; } }