diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 13192b809c..f902d5f9bb 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,7 +18,7 @@ repos: hooks: - id: clang-format args: ["--style=file"] # Use the .clang-format file for configuration - files: ^Common\+\+/.*\.(cpp|h)$ + files: ^(Common\+\+|Tests)/.*\.(cpp|h)$ - id: cppcheck args: ["--std=c++11", "--language=c++", "--suppressions-list=cppcheckSuppressions.txt", "--inline-suppr", "--force"] - repo: https://github.com/codespell-project/codespell diff --git a/Tests/Fuzzers/DumpToFile.h b/Tests/Fuzzers/DumpToFile.h index b67b31a42f..b54962c7df 100644 --- a/Tests/Fuzzers/DumpToFile.h +++ b/Tests/Fuzzers/DumpToFile.h @@ -4,9 +4,9 @@ // This function is created as PcapPlusPlus doesn't seem to offer a way of // parsing Pcap files directly from memory -static int dumpDataToPcapFile(const uint8_t *data, size_t size, const char* path) +static int dumpDataToPcapFile(const uint8_t* data, size_t size, const char* path) { - FILE *fd; + FILE* fd; int written = 0; fd = fopen(path, "wb"); diff --git a/Tests/Fuzzers/FuzzTarget.cpp b/Tests/Fuzzers/FuzzTarget.cpp index 293bd66252..8d543a3c6f 100644 --- a/Tests/Fuzzers/FuzzTarget.cpp +++ b/Tests/Fuzzers/FuzzTarget.cpp @@ -7,10 +7,10 @@ static std::string tmpName; static std::string tmpFile; -extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { if (tmpName.empty()) - tmpName = tmpnam (NULL); + tmpName = tmpnam(NULL); if (tmpFile.empty()) tmpFile = tmpName + FILE_EXT; @@ -32,15 +32,14 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) pcpp::IPcapDevice::PcapStats stats; reader->getStatistics(stats); - std::cout << "Read " << stats.packetsRecv << " packets successfully and " - << stats.packetsDrop << " packets could not be read" << std::endl; + std::cout << "Read " << stats.packetsRecv << " packets successfully and " << stats.packetsDrop + << " packets could not be read" << std::endl; if (auto ngReader = dynamic_cast(reader.get())) { std::cout << "OS is '" << ngReader->getOS() << "'; Hardware is '" << ngReader->getHardware() << "'" - << "'; CaptureApplication is '" << ngReader->getCaptureApplication() - << "'; CaptureFileComment is '" << ngReader->getCaptureFileComment() - << "'" << std::endl; + << "'; CaptureApplication is '" << ngReader->getCaptureApplication() << "'; CaptureFileComment is '" + << ngReader->getCaptureFileComment() << "'" << std::endl; } pcpp::RawPacketVector packets; diff --git a/Tests/Fuzzers/FuzzWriter.cpp b/Tests/Fuzzers/FuzzWriter.cpp index 2af45a6c42..ba0ab8d361 100644 --- a/Tests/Fuzzers/FuzzWriter.cpp +++ b/Tests/Fuzzers/FuzzWriter.cpp @@ -10,10 +10,10 @@ static std::string tmpFile; static std::string outPcapFile; static int writes = 0; -extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { if (tmpName.empty()) - tmpName = tmpnam (NULL); + tmpName = tmpnam(NULL); if (tmpFile.empty()) tmpFile = tmpName + FILE_EXT; @@ -41,9 +41,9 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) #endif #ifdef NG_WRITER - pcpp::PcapNgFileWriterDevice pcapWriter(outPcapFile); + pcpp::PcapNgFileWriterDevice pcapWriter(outPcapFile); #else - pcpp::PcapFileWriterDevice pcapWriter(outPcapFile, pcpp::LINKTYPE_ETHERNET); + pcpp::PcapFileWriterDevice pcapWriter(outPcapFile, pcpp::LINKTYPE_ETHERNET); #endif if (writes++ == 10) { @@ -71,8 +71,8 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) pcpp::IPcapDevice::PcapStats stats; pcapWriter.getStatistics(stats); - std::cout << "Written " << stats.packetsRecv << " packets successfully to pcap writer and " - << stats.packetsDrop << " packets could not be written" << std::endl; + std::cout << "Written " << stats.packetsRecv << " packets successfully to pcap writer and " << stats.packetsDrop + << " packets could not be written" << std::endl; pcapWriter.close(); return 0; diff --git a/Tests/Fuzzers/ReadParsedPacket.h b/Tests/Fuzzers/ReadParsedPacket.h index 9fc0dbb326..c0e6779dfb 100644 --- a/Tests/Fuzzers/ReadParsedPacket.h +++ b/Tests/Fuzzers/ReadParsedPacket.h @@ -26,494 +26,497 @@ // If you made changes to PcapPlusPlus and the code doesn't compile - fix the method call as any other unit test static void readParsedPacket(pcpp::Packet parsedPacket, pcpp::Layer* layer) { - if (parsedPacket.isPacketOfType(pcpp::Telnet)) - { - if (auto telnetLayer = dynamic_cast(layer)) - { - telnetLayer->getFirstCommand(); - telnetLayer->getTotalNumberOfCommands(); + if (parsedPacket.isPacketOfType(pcpp::Telnet)) + { + if (auto telnetLayer = dynamic_cast(layer)) + { + telnetLayer->getFirstCommand(); + telnetLayer->getTotalNumberOfCommands(); - pcpp::TelnetLayer::TelnetCommand commandVal; - do - { - commandVal = telnetLayer->getNextCommand(); - std::cout << "Telnet command is '" << telnetLayer->getTelnetCommandAsString(commandVal) << "'" << std::endl; - pcpp::TelnetLayer::TelnetOption option = telnetLayer->getOption(); - std::cout << "Telnet option is '" << telnetLayer->getTelnetOptionAsString(option) << "'" << std::endl; + pcpp::TelnetLayer::TelnetCommand commandVal; + do + { + commandVal = telnetLayer->getNextCommand(); + std::cout << "Telnet command is '" << telnetLayer->getTelnetCommandAsString(commandVal) << "'" + << std::endl; + pcpp::TelnetLayer::TelnetOption option = telnetLayer->getOption(); + std::cout << "Telnet option is '" << telnetLayer->getTelnetOptionAsString(option) << "'" << std::endl; - telnetLayer->getDataAsString(true); - telnetLayer->getNumberOfCommands(commandVal); - telnetLayer->getOption(commandVal); - size_t length = 0; - telnetLayer->getOptionData(length); - telnetLayer->getOptionData(commandVal, length); - } - while (commandVal != pcpp::TelnetLayer::TelnetCommand::TelnetCommandEndOfPacket); - } - } - if (parsedPacket.isPacketOfType(pcpp::ARP)) - { - if (auto arpLayer = dynamic_cast(layer)) - { - arpLayer->isReply(); - arpLayer->isRequest(); - } - } - if (parsedPacket.isPacketOfType(pcpp::SomeIP)) - { - if (auto someipLayer = dynamic_cast(layer)) - { - auto entries = someipLayer->getEntries(); - if (!entries.empty()) - { - auto opts = someipLayer->getOptionsFromEntry(0); - for (auto opt : opts) - delete opt; - } + telnetLayer->getDataAsString(true); + telnetLayer->getNumberOfCommands(commandVal); + telnetLayer->getOption(commandVal); + size_t length = 0; + telnetLayer->getOptionData(length); + telnetLayer->getOptionData(commandVal, length); + } while (commandVal != pcpp::TelnetLayer::TelnetCommand::TelnetCommandEndOfPacket); + } + } + if (parsedPacket.isPacketOfType(pcpp::ARP)) + { + if (auto arpLayer = dynamic_cast(layer)) + { + arpLayer->isReply(); + arpLayer->isRequest(); + } + } + if (parsedPacket.isPacketOfType(pcpp::SomeIP)) + { + if (auto someipLayer = dynamic_cast(layer)) + { + auto entries = someipLayer->getEntries(); + if (!entries.empty()) + { + auto opts = someipLayer->getOptionsFromEntry(0); + for (auto opt : opts) + delete opt; + } - for (auto entry : entries) - { - entry->getNumOptions(); - entry->getServiceId(); - entry->getInstanceId(); - entry->getMajorVersion(); - entry->getMinorVersion(); - entry->getCounter(); - entry->getEventgroupId(); - delete entry; - } + for (auto entry : entries) + { + entry->getNumOptions(); + entry->getServiceId(); + entry->getInstanceId(); + entry->getMajorVersion(); + entry->getMinorVersion(); + entry->getCounter(); + entry->getEventgroupId(); + delete entry; + } - someipLayer->getFlags(); - auto opts = someipLayer->getOptions(); - for (auto opt : opts) - { - opt->getType(); - if (auto v4opt = dynamic_cast(opt)) - { - v4opt->getIpAddress(); - v4opt->getPort(); - v4opt->getProtocol(); - } - else if (auto v6opt = dynamic_cast(opt)) - { - v6opt->getIpAddress(); - v6opt->getPort(); - v6opt->getProtocol(); - } - delete opt; - } - } - } - if (parsedPacket.isPacketOfType(pcpp::GTP)) - { - if (auto gtpLayer = dynamic_cast(layer)) - { - uint16_t value16 = 0; - gtpLayer->getSequenceNumber(value16); - uint8_t value8; - gtpLayer->getNpduNumber(value8); - gtpLayer->getMessageType(); - gtpLayer->getMessageTypeAsString(); - gtpLayer->isGTPUMessage(); - gtpLayer->isGTPCMessage(); - auto ext = gtpLayer->getNextExtension(); - ext.getExtensionType(); - ext.getContent(); - ext.getContentLength(); - ext.getNextExtension(); - } - } - if (parsedPacket.isPacketOfType(pcpp::GRE)) - { - if (auto greLayer = dynamic_cast(layer)) - { - uint32_t value32 = 0; - greLayer->getSequenceNumber(value32); - } - } - if (parsedPacket.isPacketOfType(pcpp::GREv0)) - { - if (auto greLayer = dynamic_cast(layer)) - { - uint16_t value16 = 0; - greLayer->getChecksum(value16); - greLayer->getOffset(value16); - uint32_t value32 = 0; - greLayer->getKey(value32); - } - } - if (parsedPacket.isPacketOfType(pcpp::GREv1)) - { - if (auto greLayer = dynamic_cast(layer)) - { - uint32_t value32 = 0; - greLayer->getAcknowledgmentNum(value32); - } - } - if (parsedPacket.isPacketOfType(pcpp::FTP)) - { - if (auto ftpLayer = dynamic_cast(layer)) - { - ftpLayer->getCommandOption(false); - ftpLayer->getCommandOption(true); - } - else if (auto ftpLayer = dynamic_cast(layer)) - { - ftpLayer->getStatusCode(); - ftpLayer->getStatusOption(false); - ftpLayer->getStatusOption(true); - } - } - if (parsedPacket.isPacketOfType(pcpp::SLL2)) - { - if (auto sllLayer = dynamic_cast(layer)) - { - sllLayer->getLinkLayerAsMacAddress(); - sllLayer->getProtocolType(); - sllLayer->getInterfaceIndex(); - sllLayer->getArphrdType(); - sllLayer->getPacketType(); - } - } - if (parsedPacket.isPacketOfType(pcpp::VRRP)) - { - if (auto vrrpLayer = dynamic_cast(layer)) - { - vrrpLayer->getIPAddresses(); - vrrpLayer->isChecksumCorrect(); - vrrpLayer->getChecksum(); - vrrpLayer->getPriorityAsEnum(); - vrrpLayer->getPriority(); - vrrpLayer->getType(); - } - } - if (parsedPacket.isPacketOfType(pcpp::VRRPv2)) - { - if (auto vrrpLayer = dynamic_cast(layer)) - { - vrrpLayer->getAuthTypeAsEnum(); - vrrpLayer->getAdvInt(); - } - } - if (parsedPacket.isPacketOfType(pcpp::VRRPv3)) - { - if (auto vrrpLayer = dynamic_cast(layer)) - { - vrrpLayer->getMaxAdvInt(); - } - } - if (parsedPacket.isPacketOfType(pcpp::TCP)) - { - if (auto tcpLayer = dynamic_cast(layer)) - { - auto tcpLayer2 (*tcpLayer); - tcpLayer2.insertTcpOptionAfter(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NopEolOptionEnumType::Nop), pcpp::TcpOptionEnumType::Nop); - } - } - if (parsedPacket.isPacketOfType(pcpp::SDP)) - { - if (auto sdpLayer = dynamic_cast(layer)) - { - sdpLayer->getOwnerIPv4Address(); - sdpLayer->getMediaPort("audio"); - sdpLayer->getFieldCount(); + someipLayer->getFlags(); + auto opts = someipLayer->getOptions(); + for (auto opt : opts) + { + opt->getType(); + if (auto v4opt = dynamic_cast(opt)) + { + v4opt->getIpAddress(); + v4opt->getPort(); + v4opt->getProtocol(); + } + else if (auto v6opt = dynamic_cast(opt)) + { + v6opt->getIpAddress(); + v6opt->getPort(); + v6opt->getProtocol(); + } + delete opt; + } + } + } + if (parsedPacket.isPacketOfType(pcpp::GTP)) + { + if (auto gtpLayer = dynamic_cast(layer)) + { + uint16_t value16 = 0; + gtpLayer->getSequenceNumber(value16); + uint8_t value8; + gtpLayer->getNpduNumber(value8); + gtpLayer->getMessageType(); + gtpLayer->getMessageTypeAsString(); + gtpLayer->isGTPUMessage(); + gtpLayer->isGTPCMessage(); + auto ext = gtpLayer->getNextExtension(); + ext.getExtensionType(); + ext.getContent(); + ext.getContentLength(); + ext.getNextExtension(); + } + } + if (parsedPacket.isPacketOfType(pcpp::GRE)) + { + if (auto greLayer = dynamic_cast(layer)) + { + uint32_t value32 = 0; + greLayer->getSequenceNumber(value32); + } + } + if (parsedPacket.isPacketOfType(pcpp::GREv0)) + { + if (auto greLayer = dynamic_cast(layer)) + { + uint16_t value16 = 0; + greLayer->getChecksum(value16); + greLayer->getOffset(value16); + uint32_t value32 = 0; + greLayer->getKey(value32); + } + } + if (parsedPacket.isPacketOfType(pcpp::GREv1)) + { + if (auto greLayer = dynamic_cast(layer)) + { + uint32_t value32 = 0; + greLayer->getAcknowledgmentNum(value32); + } + } + if (parsedPacket.isPacketOfType(pcpp::FTP)) + { + if (auto ftpLayer = dynamic_cast(layer)) + { + ftpLayer->getCommandOption(false); + ftpLayer->getCommandOption(true); + } + else if (auto ftpLayer = dynamic_cast(layer)) + { + ftpLayer->getStatusCode(); + ftpLayer->getStatusOption(false); + ftpLayer->getStatusOption(true); + } + } + if (parsedPacket.isPacketOfType(pcpp::SLL2)) + { + if (auto sllLayer = dynamic_cast(layer)) + { + sllLayer->getLinkLayerAsMacAddress(); + sllLayer->getProtocolType(); + sllLayer->getInterfaceIndex(); + sllLayer->getArphrdType(); + sllLayer->getPacketType(); + } + } + if (parsedPacket.isPacketOfType(pcpp::VRRP)) + { + if (auto vrrpLayer = dynamic_cast(layer)) + { + vrrpLayer->getIPAddresses(); + vrrpLayer->isChecksumCorrect(); + vrrpLayer->getChecksum(); + vrrpLayer->getPriorityAsEnum(); + vrrpLayer->getPriority(); + vrrpLayer->getType(); + } + } + if (parsedPacket.isPacketOfType(pcpp::VRRPv2)) + { + if (auto vrrpLayer = dynamic_cast(layer)) + { + vrrpLayer->getAuthTypeAsEnum(); + vrrpLayer->getAdvInt(); + } + } + if (parsedPacket.isPacketOfType(pcpp::VRRPv3)) + { + if (auto vrrpLayer = dynamic_cast(layer)) + { + vrrpLayer->getMaxAdvInt(); + } + } + if (parsedPacket.isPacketOfType(pcpp::TCP)) + { + if (auto tcpLayer = dynamic_cast(layer)) + { + auto tcpLayer2(*tcpLayer); + tcpLayer2.insertTcpOptionAfter(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NopEolOptionEnumType::Nop), + pcpp::TcpOptionEnumType::Nop); + } + } + if (parsedPacket.isPacketOfType(pcpp::SDP)) + { + if (auto sdpLayer = dynamic_cast(layer)) + { + sdpLayer->getOwnerIPv4Address(); + sdpLayer->getMediaPort("audio"); + sdpLayer->getFieldCount(); - auto sdpLayer2 = *sdpLayer; - std::vector audioAttributes; - audioAttributes.push_back("rtpmap:8 PCMA/8000"); - sdpLayer2.addMediaDescription("audio", 6010, "RTP/AVP", "8 96", audioAttributes); - sdpLayer2.addField(PCPP_SDP_PROTOCOL_VERSION_FIELD, "0"); - sdpLayer2.removeField(PCPP_SDP_PROTOCOL_VERSION_FIELD); - } - } - if (parsedPacket.isPacketOfType(pcpp::SSL)) - { - if (auto handshakeLayer = dynamic_cast(layer)) - { - if (auto clientHelloMessage = handshakeLayer->getHandshakeMessageOfType()) - { - clientHelloMessage->getCompressionMethodsValue(); - clientHelloMessage->getSessionID(); - clientHelloMessage->getHandshakeType(); - clientHelloMessage->getHandshakeVersion(); + auto sdpLayer2 = *sdpLayer; + std::vector audioAttributes; + audioAttributes.push_back("rtpmap:8 PCMA/8000"); + sdpLayer2.addMediaDescription("audio", 6010, "RTP/AVP", "8 96", audioAttributes); + sdpLayer2.addField(PCPP_SDP_PROTOCOL_VERSION_FIELD, "0"); + sdpLayer2.removeField(PCPP_SDP_PROTOCOL_VERSION_FIELD); + } + } + if (parsedPacket.isPacketOfType(pcpp::SSL)) + { + if (auto handshakeLayer = dynamic_cast(layer)) + { + if (auto clientHelloMessage = handshakeLayer->getHandshakeMessageOfType()) + { + clientHelloMessage->getCompressionMethodsValue(); + clientHelloMessage->getSessionID(); + clientHelloMessage->getHandshakeType(); + clientHelloMessage->getHandshakeVersion(); - pcpp::SSLCipherSuite::getCipherSuiteByName("TLS_RSA_WITH_NULL_MD5"); - for (int i = 0; i < clientHelloMessage->getCipherSuiteCount(); i++) - { - clientHelloMessage->getCipherSuite(i); - bool valid; - clientHelloMessage->getCipherSuiteID(i, valid); - } - if (auto ext = clientHelloMessage->getExtensionOfType()) - ext->getHostName(); - if (auto ext = clientHelloMessage->getExtensionOfType()) - ext->getSupportedVersions(); + pcpp::SSLCipherSuite::getCipherSuiteByName("TLS_RSA_WITH_NULL_MD5"); + for (int i = 0; i < clientHelloMessage->getCipherSuiteCount(); i++) + { + clientHelloMessage->getCipherSuite(i); + bool valid; + clientHelloMessage->getCipherSuiteID(i, valid); + } + if (auto ext = clientHelloMessage->getExtensionOfType()) + ext->getHostName(); + if (auto ext = clientHelloMessage->getExtensionOfType()) + ext->getSupportedVersions(); - clientHelloMessage->getExtensionOfType(pcpp::SSL_EXT_SERVER_NAME); - clientHelloMessage->getExtensionOfType((uint16_t)0); + clientHelloMessage->getExtensionOfType(pcpp::SSL_EXT_SERVER_NAME); + clientHelloMessage->getExtensionOfType((uint16_t)0); - auto fingerprint = clientHelloMessage->generateTLSFingerprint(); - fingerprint.toMD5(); - } - if (auto serverHelloMessage = handshakeLayer->getHandshakeMessageOfType()) - { - serverHelloMessage->getCompressionMethodsValue(); - serverHelloMessage->getSessionID(); - serverHelloMessage->getCipherSuite(); + auto fingerprint = clientHelloMessage->generateTLSFingerprint(); + fingerprint.toMD5(); + } + if (auto serverHelloMessage = handshakeLayer->getHandshakeMessageOfType()) + { + serverHelloMessage->getCompressionMethodsValue(); + serverHelloMessage->getSessionID(); + serverHelloMessage->getCipherSuite(); - serverHelloMessage->getExtensionOfType(); - serverHelloMessage->getExtensionOfType(pcpp::SSL_EXT_SERVER_NAME); - serverHelloMessage->getExtensionOfType((uint16_t)0); + serverHelloMessage->getExtensionOfType(); + serverHelloMessage->getExtensionOfType(pcpp::SSL_EXT_SERVER_NAME); + serverHelloMessage->getExtensionOfType((uint16_t)0); - serverHelloMessage->getHandshakeVersion(); - auto fingerprint = serverHelloMessage->generateTLSFingerprint(); - fingerprint.toMD5(); - } - if (auto handshakeMessage = handshakeLayer->getHandshakeMessageOfType()) - { - handshakeMessage->isMessageComplete(); - } - } - } - if (parsedPacket.isPacketOfType(pcpp::NTP)) - { - if (auto ntpLayer = dynamic_cast(layer)) - { - ntpLayer->getLeapIndicator(); - ntpLayer->getMode(); - ntpLayer->getModeString(); - ntpLayer->getStratum(); - ntpLayer->getPollInterval(); - ntpLayer->getPrecision(); - ntpLayer->getRootDelay(); - ntpLayer->getRootDispersion(); - ntpLayer->getReferenceIdentifier(); - ntpLayer->getReferenceIdentifierString(); - ntpLayer->getReferenceTimestamp(); - ntpLayer->getOriginTimestamp(); - ntpLayer->getReceiveTimestamp(); - ntpLayer->getTransmitTimestamp(); + serverHelloMessage->getHandshakeVersion(); + auto fingerprint = serverHelloMessage->generateTLSFingerprint(); + fingerprint.toMD5(); + } + if (auto handshakeMessage = handshakeLayer->getHandshakeMessageOfType()) + { + handshakeMessage->isMessageComplete(); + } + } + } + if (parsedPacket.isPacketOfType(pcpp::NTP)) + { + if (auto ntpLayer = dynamic_cast(layer)) + { + ntpLayer->getLeapIndicator(); + ntpLayer->getMode(); + ntpLayer->getModeString(); + ntpLayer->getStratum(); + ntpLayer->getPollInterval(); + ntpLayer->getPrecision(); + ntpLayer->getRootDelay(); + ntpLayer->getRootDispersion(); + ntpLayer->getReferenceIdentifier(); + ntpLayer->getReferenceIdentifierString(); + ntpLayer->getReferenceTimestamp(); + ntpLayer->getOriginTimestamp(); + ntpLayer->getReceiveTimestamp(); + ntpLayer->getTransmitTimestamp(); - ntpLayer->getDigest(); - ntpLayer->getKeyID(); + ntpLayer->getDigest(); + ntpLayer->getKeyID(); - ntpLayer->getPollIntervalInSecs(); - ntpLayer->getPrecisionInSecs(); - ntpLayer->getRootDelayInSecs(); - ntpLayer->getRootDispersionInSecs(); - ntpLayer->getReferenceTimestampInSecs(); - ntpLayer->getOriginTimestampInSecs(); - ntpLayer->getReceiveTimestampInSecs(); - ntpLayer->getTransmitTimestampInSecs(); + ntpLayer->getPollIntervalInSecs(); + ntpLayer->getPrecisionInSecs(); + ntpLayer->getRootDelayInSecs(); + ntpLayer->getRootDispersionInSecs(); + ntpLayer->getReferenceTimestampInSecs(); + ntpLayer->getOriginTimestampInSecs(); + ntpLayer->getReceiveTimestampInSecs(); + ntpLayer->getTransmitTimestampInSecs(); - ntpLayer->getReferenceTimestampAsString(); - ntpLayer->getOriginTimestampAsString(); - ntpLayer->getReceiveTimestampAsString(); - ntpLayer->getTransmitTimestampAsString(); + ntpLayer->getReferenceTimestampAsString(); + ntpLayer->getOriginTimestampAsString(); + ntpLayer->getReceiveTimestampAsString(); + ntpLayer->getTransmitTimestampAsString(); - auto ntpLayer2 (*ntpLayer); - ntpLayer2.setRootDelayInSecs(0.1); - ntpLayer2.setReferenceTimestampInSecs(0.1); - } - } - if (parsedPacket.isPacketOfType(pcpp::ICMP)) - { - if (auto icmpLayer = dynamic_cast(layer)) - { - auto icmpLayer2 (*icmpLayer); + auto ntpLayer2(*ntpLayer); + ntpLayer2.setRootDelayInSecs(0.1); + ntpLayer2.setReferenceTimestampInSecs(0.1); + } + } + if (parsedPacket.isPacketOfType(pcpp::ICMP)) + { + if (auto icmpLayer = dynamic_cast(layer)) + { + auto icmpLayer2(*icmpLayer); - if (icmpLayer->isMessageOfType(pcpp::ICMP_TIMESTAMP_REPLY)) - { - icmpLayer->getTimestampReplyData(); - timeval orig = { 16131, 171000 }; - timeval recv = { 16133, 474000 }; - timeval tran = { 16133, 474000 }; - icmpLayer2.setTimestampReplyData(14640, 0, orig, recv, tran); - } - else if (icmpLayer->isMessageOfType(pcpp::ICMP_ADDRESS_MASK_REQUEST)) - { - icmpLayer->getAddressMaskRequestData(); - icmpLayer2.setAddressMaskRequestData(45068, 1536, pcpp::IPv4Address::Zero); - } - else if (icmpLayer->isMessageOfType(pcpp::ICMP_ADDRESS_MASK_REPLY)) - { - icmpLayer->getAddressMaskReplyData(); - icmpLayer2.setAddressMaskReplyData(45068, 1536, pcpp::IPv4Address::Zero); - } - else if (icmpLayer->isMessageOfType(pcpp::ICMP_DEST_UNREACHABLE)) - { - icmpLayer->getDestUnreachableData(); - icmpLayer2.setDestUnreachableData(pcpp::IcmpHostUnreachable, 0, nullptr, nullptr); - } - else if (icmpLayer->isMessageOfType(pcpp::ICMP_INFO_REPLY)) - { - auto layerData = icmpLayer->getInfoReplyData(); - icmpLayer2.setInfoReplyData(layerData->id, layerData->sequence); - } - else if (icmpLayer->isMessageOfType(pcpp::ICMP_INFO_REQUEST)) - { - auto layerData = icmpLayer->getInfoRequestData(); - icmpLayer2.setInfoRequestData(layerData->id, layerData->sequence); - } - else if (icmpLayer->isMessageOfType(pcpp::ICMP_PARAM_PROBLEM)) - { - auto layerData = icmpLayer->getParamProblemData(); - icmpLayer2.setParamProblemData(layerData->code, layerData->pointer, nullptr, nullptr); - } - else if (icmpLayer->isMessageOfType(pcpp::ICMP_TIME_EXCEEDED)) - { - icmpLayer->getTimeExceededData(); - icmpLayer2.setTimeExceededData(1, nullptr, nullptr); - } - else if (icmpLayer->isMessageOfType(pcpp::ICMP_ROUTER_ADV)) - { - icmpLayer->getRouterAdvertisementData(); - pcpp::icmp_router_address_structure addr1; - addr1.setRouterAddress(pcpp::IPv4Address("192.168.144.2"), (uint32_t)0x08000000); - std::vector routerAddresses; - routerAddresses.push_back(addr1); - icmpLayer2.setRouterAdvertisementData(16, 200, routerAddresses); - } - } - } - if (parsedPacket.isPacketOfType(pcpp::DHCPv6)) - { - if (auto dhcpLayer = dynamic_cast(layer)) - { - dhcpLayer->getTransactionID(); - if (dhcpLayer->getOptionCount() > 0) - { - pcpp::DhcpV6Option opt = dhcpLayer->getFirstOptionData(); - opt.getType(); - opt.getTotalSize(); - opt.getValueAsHexString(); - for (size_t i = 0; i < dhcpLayer->getOptionCount(); i++) - { - opt = dhcpLayer->getNextOptionData(opt); - } - dhcpLayer->getOptionData(pcpp::DHCPV6_OPT_CLIENTID); - } - } - } - if (parsedPacket.isPacketOfType(pcpp::DHCP)) - { - if (auto dhcpLayer = dynamic_cast(layer)) - { - dhcpLayer->getOpCode(); - dhcpLayer->getDhcpHeader(); - dhcpLayer->getClientIpAddress(); - dhcpLayer->getYourIpAddress(); - dhcpLayer->getServerIpAddress(); - dhcpLayer->getGatewayIpAddress(); - dhcpLayer->getClientHardwareAddress(); - if (dhcpLayer->getOptionsCount() > 0) - { - pcpp::DhcpOption opt = dhcpLayer->getFirstOptionData(); - opt.getValueAsIpAddr(); - opt.getValueAsString(); - for (size_t i = 0; i < dhcpLayer->getOptionsCount(); i++) - { - opt = dhcpLayer->getNextOptionData(opt); - } - } - dhcpLayer->getOptionData(pcpp::DHCPOPT_SUBNET_MASK); - } - } - if (parsedPacket.isPacketOfType(pcpp::BGP)) - { - if (auto bgpLayer = dynamic_cast(layer)) - { - bgpLayer->getMessageTypeAsString(); - if (auto bgpOpenMsgLayer = dynamic_cast(bgpLayer)) - { - std::vector optionalParams; - bgpOpenMsgLayer->getOptionalParameters(optionalParams); - std::vector optionalParams2(optionalParams); - optionalParams2.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "010400010001")); - optionalParams2.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "8000")); - optionalParams2.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "0200")); - optionalParams2.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "4600")); - optionalParams2.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "410400000001")); - bgpOpenMsgLayer->setOptionalParameters(optionalParams2); - bgpOpenMsgLayer->clearOptionalParameters(); - bgpOpenMsgLayer->setOptionalParameters(optionalParams); - } - else if (auto bgpUpdateMsgLayer = dynamic_cast(bgpLayer)) - { - std::vector withdrawnRoutes; - bgpUpdateMsgLayer->getWithdrawnRoutes(withdrawnRoutes); - std::vector withdrawnRoutes2(withdrawnRoutes); - withdrawnRoutes2.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "40.1.1.0")); - withdrawnRoutes2.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "40.40.40.0")); - withdrawnRoutes2.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(16, "103.103.0.0")); - withdrawnRoutes2.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "103.103.40.0")); - bgpUpdateMsgLayer->setWithdrawnRoutes(withdrawnRoutes2); - bgpUpdateMsgLayer->clearWithdrawnRoutes(); - bgpUpdateMsgLayer->setWithdrawnRoutes(withdrawnRoutes); + if (icmpLayer->isMessageOfType(pcpp::ICMP_TIMESTAMP_REPLY)) + { + icmpLayer->getTimestampReplyData(); + timeval orig = { 16131, 171000 }; + timeval recv = { 16133, 474000 }; + timeval tran = { 16133, 474000 }; + icmpLayer2.setTimestampReplyData(14640, 0, orig, recv, tran); + } + else if (icmpLayer->isMessageOfType(pcpp::ICMP_ADDRESS_MASK_REQUEST)) + { + icmpLayer->getAddressMaskRequestData(); + icmpLayer2.setAddressMaskRequestData(45068, 1536, pcpp::IPv4Address::Zero); + } + else if (icmpLayer->isMessageOfType(pcpp::ICMP_ADDRESS_MASK_REPLY)) + { + icmpLayer->getAddressMaskReplyData(); + icmpLayer2.setAddressMaskReplyData(45068, 1536, pcpp::IPv4Address::Zero); + } + else if (icmpLayer->isMessageOfType(pcpp::ICMP_DEST_UNREACHABLE)) + { + icmpLayer->getDestUnreachableData(); + icmpLayer2.setDestUnreachableData(pcpp::IcmpHostUnreachable, 0, nullptr, nullptr); + } + else if (icmpLayer->isMessageOfType(pcpp::ICMP_INFO_REPLY)) + { + auto layerData = icmpLayer->getInfoReplyData(); + icmpLayer2.setInfoReplyData(layerData->id, layerData->sequence); + } + else if (icmpLayer->isMessageOfType(pcpp::ICMP_INFO_REQUEST)) + { + auto layerData = icmpLayer->getInfoRequestData(); + icmpLayer2.setInfoRequestData(layerData->id, layerData->sequence); + } + else if (icmpLayer->isMessageOfType(pcpp::ICMP_PARAM_PROBLEM)) + { + auto layerData = icmpLayer->getParamProblemData(); + icmpLayer2.setParamProblemData(layerData->code, layerData->pointer, nullptr, nullptr); + } + else if (icmpLayer->isMessageOfType(pcpp::ICMP_TIME_EXCEEDED)) + { + icmpLayer->getTimeExceededData(); + icmpLayer2.setTimeExceededData(1, nullptr, nullptr); + } + else if (icmpLayer->isMessageOfType(pcpp::ICMP_ROUTER_ADV)) + { + icmpLayer->getRouterAdvertisementData(); + pcpp::icmp_router_address_structure addr1; + addr1.setRouterAddress(pcpp::IPv4Address("192.168.144.2"), (uint32_t)0x08000000); + std::vector routerAddresses; + routerAddresses.push_back(addr1); + icmpLayer2.setRouterAdvertisementData(16, 200, routerAddresses); + } + } + } + if (parsedPacket.isPacketOfType(pcpp::DHCPv6)) + { + if (auto dhcpLayer = dynamic_cast(layer)) + { + dhcpLayer->getTransactionID(); + if (dhcpLayer->getOptionCount() > 0) + { + pcpp::DhcpV6Option opt = dhcpLayer->getFirstOptionData(); + opt.getType(); + opt.getTotalSize(); + opt.getValueAsHexString(); + for (size_t i = 0; i < dhcpLayer->getOptionCount(); i++) + { + opt = dhcpLayer->getNextOptionData(opt); + } + dhcpLayer->getOptionData(pcpp::DHCPV6_OPT_CLIENTID); + } + } + } + if (parsedPacket.isPacketOfType(pcpp::DHCP)) + { + if (auto dhcpLayer = dynamic_cast(layer)) + { + dhcpLayer->getOpCode(); + dhcpLayer->getDhcpHeader(); + dhcpLayer->getClientIpAddress(); + dhcpLayer->getYourIpAddress(); + dhcpLayer->getServerIpAddress(); + dhcpLayer->getGatewayIpAddress(); + dhcpLayer->getClientHardwareAddress(); + if (dhcpLayer->getOptionsCount() > 0) + { + pcpp::DhcpOption opt = dhcpLayer->getFirstOptionData(); + opt.getValueAsIpAddr(); + opt.getValueAsString(); + for (size_t i = 0; i < dhcpLayer->getOptionsCount(); i++) + { + opt = dhcpLayer->getNextOptionData(opt); + } + } + dhcpLayer->getOptionData(pcpp::DHCPOPT_SUBNET_MASK); + } + } + if (parsedPacket.isPacketOfType(pcpp::BGP)) + { + if (auto bgpLayer = dynamic_cast(layer)) + { + bgpLayer->getMessageTypeAsString(); + if (auto bgpOpenMsgLayer = dynamic_cast(bgpLayer)) + { + std::vector optionalParams; + bgpOpenMsgLayer->getOptionalParameters(optionalParams); + std::vector optionalParams2(optionalParams); + optionalParams2.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "010400010001")); + optionalParams2.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "8000")); + optionalParams2.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "0200")); + optionalParams2.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "4600")); + optionalParams2.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "410400000001")); + bgpOpenMsgLayer->setOptionalParameters(optionalParams2); + bgpOpenMsgLayer->clearOptionalParameters(); + bgpOpenMsgLayer->setOptionalParameters(optionalParams); + } + else if (auto bgpUpdateMsgLayer = dynamic_cast(bgpLayer)) + { + std::vector withdrawnRoutes; + bgpUpdateMsgLayer->getWithdrawnRoutes(withdrawnRoutes); + std::vector withdrawnRoutes2(withdrawnRoutes); + withdrawnRoutes2.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "40.1.1.0")); + withdrawnRoutes2.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "40.40.40.0")); + withdrawnRoutes2.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(16, "103.103.0.0")); + withdrawnRoutes2.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "103.103.40.0")); + bgpUpdateMsgLayer->setWithdrawnRoutes(withdrawnRoutes2); + bgpUpdateMsgLayer->clearWithdrawnRoutes(); + bgpUpdateMsgLayer->setWithdrawnRoutes(withdrawnRoutes); - std::vector nlriVec; - bgpUpdateMsgLayer->getNetworkLayerReachabilityInfo(nlriVec); - std::vector nlriVec2(nlriVec); - nlriVec2.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "40.1.1.0")); - bgpUpdateMsgLayer->setNetworkLayerReachabilityInfo(nlriVec2); - bgpUpdateMsgLayer->clearNetworkLayerReachabilityInfo(); - bgpUpdateMsgLayer->setNetworkLayerReachabilityInfo(nlriVec); + std::vector nlriVec; + bgpUpdateMsgLayer->getNetworkLayerReachabilityInfo(nlriVec); + std::vector nlriVec2(nlriVec); + nlriVec2.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "40.1.1.0")); + bgpUpdateMsgLayer->setNetworkLayerReachabilityInfo(nlriVec2); + bgpUpdateMsgLayer->clearNetworkLayerReachabilityInfo(); + bgpUpdateMsgLayer->setNetworkLayerReachabilityInfo(nlriVec); - std::vector pathAttributes; - bgpUpdateMsgLayer->getPathAttributes(pathAttributes); - std::vector pathAttributes2(pathAttributes); - pathAttributes2.push_back(pcpp::BgpUpdateMessageLayer::path_attribute(0x40, 1, "02")); - pathAttributes2.push_back(pcpp::BgpUpdateMessageLayer::path_attribute(0x40, 2, "02030000000a0000001400000028")); - pathAttributes2.push_back(pcpp::BgpUpdateMessageLayer::path_attribute(0x40, 3, "1e031e03")); - bgpUpdateMsgLayer->setPathAttributes(pathAttributes2); - bgpUpdateMsgLayer->clearPathAttributes(); - bgpUpdateMsgLayer->setPathAttributes(pathAttributes); - } - else if (auto bgpNotificationMsgLayer = dynamic_cast(bgpLayer)) - { - bgpNotificationMsgLayer->getNotificationDataAsHexString(); - } - } - } - if (parsedPacket.isPacketOfType(pcpp::DNS)) - { - if (auto dnsLayer = dynamic_cast(layer)) - { - dnsLayer->addQuery("mail-attachment.googleusercontent.com", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN); - dnsLayer->removeQuery("a", true); - dnsLayer->removeQuery("mail-attachment.googleusercontent.com", false); - pcpp::IPv4DnsResourceData ipv4DnsData(std::string("151.249.90.217")); - dnsLayer->addAnswer("assets.pinterest.com.cdngc.net", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN, 3, &ipv4DnsData); - dnsLayer->removeAnswer("a", true); - dnsLayer->removeAnswer("assets.pinterest.com.cdngc.net", false); - dnsLayer->addAuthority("Yaels-iPhone.local", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN, 120, &ipv4DnsData); - dnsLayer->removeAuthority("a", true); - dnsLayer->removeAuthority("Yaels-iPhone.local", false); - pcpp::GenericDnsResourceData genericData("0004000800df581faa4f3f9d"); - dnsLayer->addAdditionalRecord("abc", pcpp::DNS_TYPE_OPT, 0xa005, 0x1194, &genericData); - dnsLayer->removeAdditionalRecord("a", true); - dnsLayer->removeAdditionalRecord("abc", false); + std::vector pathAttributes; + bgpUpdateMsgLayer->getPathAttributes(pathAttributes); + std::vector pathAttributes2(pathAttributes); + pathAttributes2.push_back(pcpp::BgpUpdateMessageLayer::path_attribute(0x40, 1, "02")); + pathAttributes2.push_back( + pcpp::BgpUpdateMessageLayer::path_attribute(0x40, 2, "02030000000a0000001400000028")); + pathAttributes2.push_back(pcpp::BgpUpdateMessageLayer::path_attribute(0x40, 3, "1e031e03")); + bgpUpdateMsgLayer->setPathAttributes(pathAttributes2); + bgpUpdateMsgLayer->clearPathAttributes(); + bgpUpdateMsgLayer->setPathAttributes(pathAttributes); + } + else if (auto bgpNotificationMsgLayer = dynamic_cast(bgpLayer)) + { + bgpNotificationMsgLayer->getNotificationDataAsHexString(); + } + } + } + if (parsedPacket.isPacketOfType(pcpp::DNS)) + { + if (auto dnsLayer = dynamic_cast(layer)) + { + dnsLayer->addQuery("mail-attachment.googleusercontent.com", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN); + dnsLayer->removeQuery("a", true); + dnsLayer->removeQuery("mail-attachment.googleusercontent.com", false); + pcpp::IPv4DnsResourceData ipv4DnsData(std::string("151.249.90.217")); + dnsLayer->addAnswer("assets.pinterest.com.cdngc.net", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN, 3, + &ipv4DnsData); + dnsLayer->removeAnswer("a", true); + dnsLayer->removeAnswer("assets.pinterest.com.cdngc.net", false); + dnsLayer->addAuthority("Yaels-iPhone.local", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN, 120, &ipv4DnsData); + dnsLayer->removeAuthority("a", true); + dnsLayer->removeAuthority("Yaels-iPhone.local", false); + pcpp::GenericDnsResourceData genericData("0004000800df581faa4f3f9d"); + dnsLayer->addAdditionalRecord("abc", pcpp::DNS_TYPE_OPT, 0xa005, 0x1194, &genericData); + dnsLayer->removeAdditionalRecord("a", true); + dnsLayer->removeAdditionalRecord("abc", false); - auto add = dnsLayer->getFirstAdditionalRecord(); - while (add != nullptr) - { - add = dnsLayer->getNextAdditionalRecord(add); - } + auto add = dnsLayer->getFirstAdditionalRecord(); + while (add != nullptr) + { + add = dnsLayer->getNextAdditionalRecord(add); + } - auto answer = dnsLayer->getFirstAnswer(); - while (answer != nullptr) - { - answer = dnsLayer->getNextAnswer(answer); - } + auto answer = dnsLayer->getFirstAnswer(); + while (answer != nullptr) + { + answer = dnsLayer->getNextAnswer(answer); + } - auto auth = dnsLayer->getFirstAuthority(); - while (auth != nullptr) - { - auth = dnsLayer->getNextAuthority(auth); - } + auto auth = dnsLayer->getFirstAuthority(); + while (auth != nullptr) + { + auth = dnsLayer->getNextAuthority(auth); + } - pcpp::DnsLayer other(*dnsLayer); - other = *dnsLayer; - } - } + pcpp::DnsLayer other(*dnsLayer); + other = *dnsLayer; + } + } } diff --git a/Tests/Packet++Test/Tests/Asn1Tests.cpp b/Tests/Packet++Test/Tests/Asn1Tests.cpp index 03b8d3264c..a945708e4a 100644 --- a/Tests/Packet++Test/Tests/Asn1Tests.cpp +++ b/Tests/Packet++Test/Tests/Asn1Tests.cpp @@ -6,343 +6,342 @@ #include #include -PTF_TEST_CASE(Asn1DecodingTest) +PTF_TEST_CASE(Asn1DecodingTest){ // Context specific + { uint8_t data[20]; +auto dataLen = pcpp::hexStringToByteArray("870b6f626a656374636c617373", data, 20); +auto record = pcpp::Asn1Record::decode(data, dataLen); + +PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::ContextSpecific, enumclass); +PTF_ASSERT_FALSE(record->isConstructed()); +PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::NotApplicable, enumclass); +PTF_ASSERT_EQUAL(record->getTotalLength(), 13); +PTF_ASSERT_EQUAL(record->getValueLength(), 11); +PTF_ASSERT_EQUAL(record->toString(), "ContextSpecific (7), Length: 2+11"); +auto genericRecord = record->castAs(); +auto recordValue = std::string(genericRecord->getValue(), genericRecord->getValue() + genericRecord->getValueLength()); +PTF_ASSERT_EQUAL(recordValue, "objectclass"); +} + +// Integer 1 byte { - // Context specific - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("870b6f626a656374636c617373", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::ContextSpecific, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::NotApplicable, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 13); - PTF_ASSERT_EQUAL(record->getValueLength(), 11); - PTF_ASSERT_EQUAL(record->toString(), "ContextSpecific (7), Length: 2+11"); - auto genericRecord = record->castAs(); - auto recordValue = std::string(genericRecord->getValue(), genericRecord->getValue() + genericRecord->getValueLength()); - PTF_ASSERT_EQUAL(recordValue, "objectclass"); - } - - // Integer 1 byte - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("020106", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Integer, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 3); - PTF_ASSERT_EQUAL(record->getValueLength(), 1); - PTF_ASSERT_EQUAL(record->castAs()->getValue(), 6); - PTF_ASSERT_EQUAL(record->toString(), "Integer, Length: 2+1, Value: 6"); - } - - // Integer 2 bytes - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("020203e8", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Integer, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 4); - PTF_ASSERT_EQUAL(record->getValueLength(), 2); - PTF_ASSERT_EQUAL(record->castAs()->getValue(), 1000); - PTF_ASSERT_EQUAL(record->toString(), "Integer, Length: 2+2, Value: 1000"); - } - - // Integer 3 bytes - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("02030186a0", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Integer, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 5); - PTF_ASSERT_EQUAL(record->getValueLength(), 3); - PTF_ASSERT_EQUAL(record->castAs()->getValue(), 100000); - PTF_ASSERT_EQUAL(record->toString(), "Integer, Length: 2+3, Value: 100000"); - } - - // Integer 4 bytes - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("020400989680", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Integer, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 6); - PTF_ASSERT_EQUAL(record->getValueLength(), 4); - PTF_ASSERT_EQUAL(record->castAs()->getValue(), 10000000); - PTF_ASSERT_EQUAL(record->toString(), "Integer, Length: 2+4, Value: 10000000"); - } - - // Integer more than 4 bytes - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("020502540be400", data, 20); - PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, dataLen, false), std::runtime_error, "An integer ASN.1 record of more than 4 bytes is not supported"); - } - - // Enumerated - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("0a022000", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Enumerated, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 4); - PTF_ASSERT_EQUAL(record->getValueLength(), 2); - PTF_ASSERT_EQUAL(record->castAs()->getValue(), 8192); - PTF_ASSERT_EQUAL(record->toString(), "Enumerated, Length: 2+2, Value: 8192"); - } - - // Boolean - true - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("0101ff", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Boolean, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 3); - PTF_ASSERT_EQUAL(record->getValueLength(), 1); - PTF_ASSERT_TRUE(record->castAs()->getValue()); - PTF_ASSERT_EQUAL(record->toString(), "Boolean, Length: 2+1, Value: true"); - } - - // Boolean - false - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("010100", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Boolean, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 3); - PTF_ASSERT_EQUAL(record->getValueLength(), 1); - PTF_ASSERT_FALSE(record->castAs()->getValue()); - PTF_ASSERT_EQUAL(record->toString(), "Boolean, Length: 2+1, Value: false"); - } - - // OctetString with printable value - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("0411737562736368656d61537562656e747279", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::OctetString, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 19); - PTF_ASSERT_EQUAL(record->getValueLength(), 17); - PTF_ASSERT_EQUAL(record->castAs()->getValue(), "subschemaSubentry"); - PTF_ASSERT_EQUAL(record->toString(), "OctetString, Length: 2+17, Value: subschemaSubentry"); - } - - // OctetString with non-printable value - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("04083006020201f40400", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::OctetString, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 10); - PTF_ASSERT_EQUAL(record->getValueLength(), 8); - PTF_ASSERT_EQUAL(record->castAs()->getValue(), "3006020201f40400"); - PTF_ASSERT_EQUAL(record->toString(), "OctetString, Length: 2+8, Value: 3006020201f40400"); - } - - // Null - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("0500", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Null, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 2); - PTF_ASSERT_EQUAL(record->getValueLength(), 0); - PTF_ASSERT_NOT_NULL(record->castAs()); - PTF_ASSERT_EQUAL(record->toString(), "Null, Length: 2+0"); - } - - // Sequence - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("300a040461626364020203e8", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_TRUE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Sequence, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 12); - PTF_ASSERT_EQUAL(record->getValueLength(), 10); - - auto& subRecords = record->castAs()->getSubRecords(); - PTF_ASSERT_EQUAL(subRecords.size(), 2); - PTF_ASSERT_EQUAL(subRecords.at(0)->castAs()->getValue(), "abcd"); - PTF_ASSERT_EQUAL(subRecords.at(1)->castAs()->getValue(), 1000); - - std::ostringstream expectedString; - expectedString - << "Sequence (constructed), Length: 2+10" << std::endl - << " OctetString, Length: 2+4, Value: abcd" << std::endl - << " Integer, Length: 2+2, Value: 1000"; - - PTF_ASSERT_EQUAL(record->toString(), expectedString.str()); - } - - // Set - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("310a020203e8040461626364", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_TRUE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Set, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 12); - PTF_ASSERT_EQUAL(record->getValueLength(), 10); - - auto& subRecords = record->castAs()->getSubRecords(); - PTF_ASSERT_EQUAL(subRecords.size(), 2); - PTF_ASSERT_EQUAL(subRecords.at(0)->castAs()->getValue(), 1000); - PTF_ASSERT_EQUAL(subRecords.at(1)->castAs()->getValue(), "abcd"); - - std::ostringstream expectedString; - expectedString - << "Set (constructed), Length: 2+10" << std::endl - << " Integer, Length: 2+2, Value: 1000" << std::endl - << " OctetString, Length: 2+4, Value: abcd"; - - PTF_ASSERT_EQUAL(record->toString(), expectedString.str()); - } - - // Application constructed - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("630a040461626364020203e8", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Application, enumclass); - PTF_ASSERT_TRUE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::NotApplicable, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 12); - PTF_ASSERT_EQUAL(record->getValueLength(), 10); - - auto& subRecords = record->castAs()->getSubRecords(); - PTF_ASSERT_EQUAL(subRecords.size(), 2); - PTF_ASSERT_EQUAL(subRecords.at(0)->castAs()->getValue(), "abcd"); - PTF_ASSERT_EQUAL(subRecords.at(1)->castAs()->getValue(), 1000); - - std::ostringstream expectedString; - expectedString - << "Application (3) (constructed), Length: 2+10" << std::endl - << " OctetString, Length: 2+4, Value: abcd" << std::endl - << " Integer, Length: 2+2, Value: 1000"; - - PTF_ASSERT_EQUAL(record->toString(), expectedString.str()); - } - - // Tag > 30 - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("1f23076d7976616c7565", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::ObjectIdentifierIRI, enumclass); - PTF_ASSERT_EQUAL(record->getTotalLength(), 10); - PTF_ASSERT_EQUAL(record->getValueLength(), 7); - PTF_ASSERT_EQUAL(record->toString(), "ObjectIdentifierIRI, Length: 3+7"); - auto genericRecord = record->castAs(); - auto recordValue = std::string(genericRecord->getValue(), genericRecord->getValue() + genericRecord->getValueLength()); - PTF_ASSERT_EQUAL(recordValue, "myvalue"); - } - - // Unknown tag - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("1f28076d7976616c7565", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - - PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); - PTF_ASSERT_FALSE(record->isConstructed()); - PTF_ASSERT_EQUAL(record->getTagType(), 40); - PTF_ASSERT_EQUAL(record->getTotalLength(), 10); - PTF_ASSERT_EQUAL(record->getValueLength(), 7); - PTF_ASSERT_EQUAL(record->toString(), "Unknown, Length: 3+7"); - auto genericRecord = record->castAs(); - auto recordValue = std::string(genericRecord->getValue(), genericRecord->getValue() + genericRecord->getValueLength()); - PTF_ASSERT_EQUAL(recordValue, "myvalue"); - } - - // Tag > 127 - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("1f8100076d7976616c7565", data, 20); - PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, dataLen), std::invalid_argument, "ASN.1 tags with value larger than 127 are not supported"); - } + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("020106", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Integer, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 3); + PTF_ASSERT_EQUAL(record->getValueLength(), 1); + PTF_ASSERT_EQUAL(record->castAs()->getValue(), 6); + PTF_ASSERT_EQUAL(record->toString(), "Integer, Length: 2+1, Value: 6"); +} + +// Integer 2 bytes +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("020203e8", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Integer, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 4); + PTF_ASSERT_EQUAL(record->getValueLength(), 2); + PTF_ASSERT_EQUAL(record->castAs()->getValue(), 1000); + PTF_ASSERT_EQUAL(record->toString(), "Integer, Length: 2+2, Value: 1000"); +} + +// Integer 3 bytes +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("02030186a0", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Integer, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 5); + PTF_ASSERT_EQUAL(record->getValueLength(), 3); + PTF_ASSERT_EQUAL(record->castAs()->getValue(), 100000); + PTF_ASSERT_EQUAL(record->toString(), "Integer, Length: 2+3, Value: 100000"); +} + +// Integer 4 bytes +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("020400989680", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Integer, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 6); + PTF_ASSERT_EQUAL(record->getValueLength(), 4); + PTF_ASSERT_EQUAL(record->castAs()->getValue(), 10000000); + PTF_ASSERT_EQUAL(record->toString(), "Integer, Length: 2+4, Value: 10000000"); +} + +// Integer more than 4 bytes +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("020502540be400", data, 20); + PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, dataLen, false), std::runtime_error, + "An integer ASN.1 record of more than 4 bytes is not supported"); +} - // Not enough data to parse tag - { - uint8_t data[20]; - pcpp::hexStringToByteArray("1f8100076d7976616c7565", data, 20); - PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, 0), std::invalid_argument, "Cannot decode ASN.1 record tag"); - PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, 1), std::invalid_argument, "Cannot decode ASN.1 record tag"); - } +// Enumerated +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("0a022000", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Enumerated, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 4); + PTF_ASSERT_EQUAL(record->getValueLength(), 2); + PTF_ASSERT_EQUAL(record->castAs()->getValue(), 8192); + PTF_ASSERT_EQUAL(record->toString(), "Enumerated, Length: 2+2, Value: 8192"); +} + +// Boolean - true +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("0101ff", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Boolean, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 3); + PTF_ASSERT_EQUAL(record->getValueLength(), 1); + PTF_ASSERT_TRUE(record->castAs()->getValue()); + PTF_ASSERT_EQUAL(record->toString(), "Boolean, Length: 2+1, Value: true"); +} + +// Boolean - false +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("010100", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Boolean, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 3); + PTF_ASSERT_EQUAL(record->getValueLength(), 1); + PTF_ASSERT_FALSE(record->castAs()->getValue()); + PTF_ASSERT_EQUAL(record->toString(), "Boolean, Length: 2+1, Value: false"); +} + +// OctetString with printable value +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("0411737562736368656d61537562656e747279", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::OctetString, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 19); + PTF_ASSERT_EQUAL(record->getValueLength(), 17); + PTF_ASSERT_EQUAL(record->castAs()->getValue(), "subschemaSubentry"); + PTF_ASSERT_EQUAL(record->toString(), "OctetString, Length: 2+17, Value: subschemaSubentry"); +} + +// OctetString with non-printable value +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("04083006020201f40400", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::OctetString, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 10); + PTF_ASSERT_EQUAL(record->getValueLength(), 8); + PTF_ASSERT_EQUAL(record->castAs()->getValue(), "3006020201f40400"); + PTF_ASSERT_EQUAL(record->toString(), "OctetString, Length: 2+8, Value: 3006020201f40400"); +} + +// Null +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("0500", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Null, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 2); + PTF_ASSERT_EQUAL(record->getValueLength(), 0); + PTF_ASSERT_NOT_NULL(record->castAs()); + PTF_ASSERT_EQUAL(record->toString(), "Null, Length: 2+0"); +} + +// Sequence +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("300a040461626364020203e8", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_TRUE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Sequence, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 12); + PTF_ASSERT_EQUAL(record->getValueLength(), 10); + + auto& subRecords = record->castAs()->getSubRecords(); + PTF_ASSERT_EQUAL(subRecords.size(), 2); + PTF_ASSERT_EQUAL(subRecords.at(0)->castAs()->getValue(), "abcd"); + PTF_ASSERT_EQUAL(subRecords.at(1)->castAs()->getValue(), 1000); + + std::ostringstream expectedString; + expectedString << "Sequence (constructed), Length: 2+10" << std::endl + << " OctetString, Length: 2+4, Value: abcd" << std::endl + << " Integer, Length: 2+2, Value: 1000"; + + PTF_ASSERT_EQUAL(record->toString(), expectedString.str()); +} + +// Set +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("310a020203e8040461626364", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_TRUE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::Set, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 12); + PTF_ASSERT_EQUAL(record->getValueLength(), 10); + + auto& subRecords = record->castAs()->getSubRecords(); + PTF_ASSERT_EQUAL(subRecords.size(), 2); + PTF_ASSERT_EQUAL(subRecords.at(0)->castAs()->getValue(), 1000); + PTF_ASSERT_EQUAL(subRecords.at(1)->castAs()->getValue(), "abcd"); + + std::ostringstream expectedString; + expectedString << "Set (constructed), Length: 2+10" << std::endl + << " Integer, Length: 2+2, Value: 1000" << std::endl + << " OctetString, Length: 2+4, Value: abcd"; + + PTF_ASSERT_EQUAL(record->toString(), expectedString.str()); +} + +// Application constructed +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("630a040461626364020203e8", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Application, enumclass); + PTF_ASSERT_TRUE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::NotApplicable, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 12); + PTF_ASSERT_EQUAL(record->getValueLength(), 10); + + auto& subRecords = record->castAs()->getSubRecords(); + PTF_ASSERT_EQUAL(subRecords.size(), 2); + PTF_ASSERT_EQUAL(subRecords.at(0)->castAs()->getValue(), "abcd"); + PTF_ASSERT_EQUAL(subRecords.at(1)->castAs()->getValue(), 1000); + + std::ostringstream expectedString; + expectedString << "Application (3) (constructed), Length: 2+10" << std::endl + << " OctetString, Length: 2+4, Value: abcd" << std::endl + << " Integer, Length: 2+2, Value: 1000"; + + PTF_ASSERT_EQUAL(record->toString(), expectedString.str()); +} + +// Tag > 30 +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("1f23076d7976616c7565", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getUniversalTagType(), pcpp::Asn1UniversalTagType::ObjectIdentifierIRI, enumclass); + PTF_ASSERT_EQUAL(record->getTotalLength(), 10); + PTF_ASSERT_EQUAL(record->getValueLength(), 7); + PTF_ASSERT_EQUAL(record->toString(), "ObjectIdentifierIRI, Length: 3+7"); + auto genericRecord = record->castAs(); + auto recordValue = + std::string(genericRecord->getValue(), genericRecord->getValue() + genericRecord->getValueLength()); + PTF_ASSERT_EQUAL(recordValue, "myvalue"); +} + +// Unknown tag +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("1f28076d7976616c7565", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); + + PTF_ASSERT_EQUAL(record->getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); + PTF_ASSERT_FALSE(record->isConstructed()); + PTF_ASSERT_EQUAL(record->getTagType(), 40); + PTF_ASSERT_EQUAL(record->getTotalLength(), 10); + PTF_ASSERT_EQUAL(record->getValueLength(), 7); + PTF_ASSERT_EQUAL(record->toString(), "Unknown, Length: 3+7"); + auto genericRecord = record->castAs(); + auto recordValue = + std::string(genericRecord->getValue(), genericRecord->getValue() + genericRecord->getValueLength()); + PTF_ASSERT_EQUAL(recordValue, "myvalue"); +} + +// Tag > 127 +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("1f8100076d7976616c7565", data, 20); + PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, dataLen), std::invalid_argument, + "ASN.1 tags with value larger than 127 are not supported"); +} - // Not enough data to parse length - { - uint8_t data[20]; - pcpp::hexStringToByteArray("0500", data, 20); - PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, 1), std::invalid_argument, "Cannot decode ASN.1 record length"); - } +// Not enough data to parse tag +{ + uint8_t data[20]; + pcpp::hexStringToByteArray("1f8100076d7976616c7565", data, 20); + PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, 0), std::invalid_argument, "Cannot decode ASN.1 record tag"); + PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, 1), std::invalid_argument, "Cannot decode ASN.1 record tag"); +} - // Incomplete record - doesn't contain the entire value - { - uint8_t data[20]; - pcpp::hexStringToByteArray("0a022000", data, 20); - PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, 3), std::invalid_argument, "Cannot decode ASN.1 record, data doesn't contain the entire record"); - } +// Not enough data to parse length +{ + uint8_t data[20]; + pcpp::hexStringToByteArray("0500", data, 20); + PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, 1), std::invalid_argument, "Cannot decode ASN.1 record length"); +} - // Cast as the wrong type - { - uint8_t data[20]; - auto dataLen = pcpp::hexStringToByteArray("0a022000", data, 20); - auto record = pcpp::Asn1Record::decode(data, dataLen); - #ifdef _MSC_VER - auto expectedMessage = "bad cast"; - #else - auto expectedMessage = "std::bad_cast"; - #endif - PTF_ASSERT_RAISES(record->castAs(), std::bad_cast, expectedMessage); - } -}; // Asn1DecodingTest +// Incomplete record - doesn't contain the entire value +{ + uint8_t data[20]; + pcpp::hexStringToByteArray("0a022000", data, 20); + PTF_ASSERT_RAISES(pcpp::Asn1Record::decode(data, 3), std::invalid_argument, + "Cannot decode ASN.1 record, data doesn't contain the entire record"); +} +// Cast as the wrong type +{ + uint8_t data[20]; + auto dataLen = pcpp::hexStringToByteArray("0a022000", data, 20); + auto record = pcpp::Asn1Record::decode(data, dataLen); +#ifdef _MSC_VER + auto expectedMessage = "bad cast"; +#else + auto expectedMessage = "std::bad_cast"; +#endif + PTF_ASSERT_RAISES(record->castAs(), std::bad_cast, expectedMessage); +} +} +; // Asn1DecodingTest PTF_TEST_CASE(Asn1EncodingTest) { // Generic record with byte array value { - uint8_t value[] = {0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x63, 0x6c, 0x61, 0x73, 0x73}; + uint8_t value[] = { 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x63, 0x6c, 0x61, 0x73, 0x73 }; pcpp::Asn1GenericRecord record(pcpp::Asn1TagClass::ContextSpecific, false, 7, value, 11); PTF_ASSERT_EQUAL(record.getTagClass(), pcpp::Asn1TagClass::ContextSpecific, enumclass); @@ -383,10 +382,17 @@ PTF_TEST_CASE(Asn1EncodingTest) // Record length > 128 { - pcpp::Asn1OctetStringRecord record("12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"); + pcpp::Asn1OctetStringRecord record( + "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456" + "7890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"); uint8_t data[203]; - auto dataLen = pcpp::hexStringToByteArray("0481c83132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930", data, 203); + auto dataLen = pcpp::hexStringToByteArray( + "0481c83132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930" + "3132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233" + "3435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536" + "3738393031323334353637383930313233343536373839303132333435363738393031323334353637383930", + data, 203); auto encodedValue = record.encode(); PTF_ASSERT_EQUAL(encodedValue.size(), dataLen); @@ -395,10 +401,20 @@ PTF_TEST_CASE(Asn1EncodingTest) // Record length > 256 { - pcpp::Asn1OctetStringRecord record("012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"); + pcpp::Asn1OctetStringRecord record( + "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345" + "6789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901" + "2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"); uint8_t data[304]; - auto dataLen = pcpp::hexStringToByteArray("0482012c303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839", data, 304); + auto dataLen = pcpp::hexStringToByteArray( + "0482012c30313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738" + "3930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031" + "3233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334" + "3536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637" + "3839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930" + "313233343536373839303132333435363738393031323334353637383930313233343536373839", + data, 304); auto encodedValue = record.encode(); PTF_ASSERT_EQUAL(encodedValue.size(), dataLen); @@ -522,7 +538,7 @@ PTF_TEST_CASE(Asn1EncodingTest) // OctetString with non-printable value { constexpr size_t valueSize = 8; - uint8_t value[valueSize] = {0x30, 0x06, 0x02, 0x02, 0x01, 0xf4, 0x04, 0x00}; + uint8_t value[valueSize] = { 0x30, 0x06, 0x02, 0x02, 0x01, 0xf4, 0x04, 0x00 }; pcpp::Asn1OctetStringRecord record(value, valueSize); PTF_ASSERT_EQUAL(record.getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); @@ -593,7 +609,7 @@ PTF_TEST_CASE(Asn1EncodingTest) { pcpp::Asn1OctetStringRecord octestStringRecord("abcd"); pcpp::Asn1IntegerRecord integerRecord(1000); - pcpp::Asn1SequenceRecord record({ &octestStringRecord, &integerRecord}); + pcpp::Asn1SequenceRecord record({ &octestStringRecord, &integerRecord }); PTF_ASSERT_EQUAL(record.getTagClass(), pcpp::Asn1TagClass::Universal, enumclass); PTF_ASSERT_TRUE(record.isConstructed()); @@ -668,4 +684,4 @@ PTF_TEST_CASE(Asn1EncodingTest) PTF_ASSERT_EQUAL(encodedValue.size(), dataLen); PTF_ASSERT_BUF_COMPARE(encodedValue.data(), data, dataLen); } -} // Asn1EncodingTest +} // Asn1EncodingTest diff --git a/Tests/Packet++Test/Tests/BgpTests.cpp b/Tests/Packet++Test/Tests/BgpTests.cpp index f17f0aba25..ca632756ff 100644 --- a/Tests/Packet++Test/Tests/BgpTests.cpp +++ b/Tests/Packet++Test/Tests/BgpTests.cpp @@ -8,7 +8,6 @@ #include "BgpLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(BgpLayerParsingTest) { timeval time; @@ -41,8 +40,6 @@ PTF_TEST_CASE(BgpLayerParsingTest) } PTF_ASSERT_EQUAL(be16toh(bgpKALayer->getKeepaliveHeader()->length), 19); - - // parse BGP OPEN message pcpp::Packet bgpOpenPacket(&rawPacket2); @@ -79,14 +76,13 @@ PTF_TEST_CASE(BgpLayerParsingTest) PTF_ASSERT_EQUAL(optParam.value[optParamsDataInedx[i]], optParamsData[i]); } - - // parse BGP NOTIFICATION message pcpp::Packet bgpNotificationPacket(&rawPacket3); PTF_ASSERT_TRUE(bgpNotificationPacket.isPacketOfType(pcpp::BGP)); - pcpp::BgpNotificationMessageLayer* bgpNotificationLayer = bgpNotificationPacket.getLayerOfType(); + pcpp::BgpNotificationMessageLayer* bgpNotificationLayer = + bgpNotificationPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(bgpNotificationLayer); PTF_ASSERT_EQUAL(bgpNotificationLayer->getBgpMessageType(), pcpp::BgpLayer::Notification, enum); PTF_ASSERT_EQUAL(bgpNotificationLayer->getHeaderLen(), 146); @@ -98,7 +94,10 @@ PTF_TEST_CASE(BgpLayerParsingTest) PTF_ASSERT_EQUAL(bgpNotificationLayer->getNotificationMsgHeader()->errorSubCode, 2); PTF_ASSERT_EQUAL(bgpNotificationLayer->getNotificationDataLen(), 125); - std::string notificationDataAsHexString = "7c4e54542077696c6c20706572666f726d206d61696e74656e616e6365206f6e207468697320726f757465722e205468697320697320747261636b656420696e205449434b45542d312d32343832343239342e20436f6e74616374206e6f63406e74742e6e657420666f72206d6f726520696e666f726d6174696f6e2e"; + std::string notificationDataAsHexString = + "7c4e54542077696c6c20706572666f726d206d61696e74656e616e6365206f6e207468697320726f757465722e20546869732069732074" + "7261636b656420696e205449434b45542d312d32343832343239342e20436f6e74616374206e6f63406e74742e6e657420666f72206d6f" + "726520696e666f726d6174696f6e2e"; PTF_ASSERT_EQUAL(bgpNotificationLayer->getNotificationDataAsHexString(), notificationDataAsHexString); pcpp::Packet bgpNotificationNoDataPacket(&rawPacket4); @@ -110,8 +109,6 @@ PTF_TEST_CASE(BgpLayerParsingTest) PTF_ASSERT_NULL(bgpNotificationLayer->getNotificationData()); PTF_ASSERT_EQUAL(bgpNotificationLayer->getNotificationDataAsHexString(), ""); - - // parse BGP ROUTE-REFRESH message pcpp::Packet bgpRRPacket(&rawPacket5); @@ -125,8 +122,6 @@ PTF_TEST_CASE(BgpLayerParsingTest) PTF_ASSERT_EQUAL(bgpRRLayer->getRouteRefreshHeader()->safi, 1); PTF_ASSERT_EQUAL(bgpRRLayer->getRouteRefreshHeader()->reserved, 1); - - // parse BGP UPDATE message with Withdrawn Routes pcpp::Packet bgpUpdatePacket1(&rawPacket6); @@ -159,8 +154,6 @@ PTF_TEST_CASE(BgpLayerParsingTest) PTF_ASSERT_NOT_NULL(bgpUpdateLayer->getNextLayer()); PTF_ASSERT_EQUAL(bgpUpdateLayer->getNextLayer()->getProtocol(), pcpp::BGP, enum); - - // parse BGP UPDATE message with Path Attributes pcpp::Packet bgpUpdatePacket2(&rawPacket7); @@ -201,7 +194,7 @@ PTF_TEST_CASE(BgpLayerParsingTest) pcpp::BgpUpdateMessageLayer::prefix_and_ip nlri = nlriVec[0]; PTF_ASSERT_EQUAL(nlri.prefix, 24); PTF_ASSERT_EQUAL(nlri.ipAddr, pcpp::IPv4Address("104.104.40.0")); - size_t pathAttrSize[3] = {28, 24, 0}; + size_t pathAttrSize[3] = { 28, 24, 0 }; for (int i = 0; i < 3; i++) { PTF_ASSERT_NOT_NULL(bgpUpdateLayer->getNextLayer()); @@ -210,8 +203,7 @@ PTF_TEST_CASE(BgpLayerParsingTest) PTF_ASSERT_NOT_NULL(bgpUpdateLayer); PTF_ASSERT_EQUAL(bgpUpdateLayer->getPathAttributesLength(), pathAttrSize[i]); } -} // BgpLayerParsingTest - +} // BgpLayerParsingTest PTF_TEST_CASE(BgpLayerCreationTest) { @@ -228,13 +220,13 @@ PTF_TEST_CASE(BgpLayerCreationTest) uint8_t origBuffer[1500]; - // create BGP KEEPALIVE message memcpy(origBuffer, buffer1, bufferLength1); pcpp::BgpKeepaliveMessageLayer newKAMessage; pcpp::Packet bgpKAPacket(&rawPacket1); - pcpp::BgpKeepaliveMessageLayer* origKAMessage = dynamic_cast(bgpKAPacket.detachLayer(pcpp::BGP)); + pcpp::BgpKeepaliveMessageLayer* origKAMessage = + dynamic_cast(bgpKAPacket.detachLayer(pcpp::BGP)); PTF_ASSERT_NOT_NULL(origKAMessage); PTF_ASSERT_EQUAL(newKAMessage.getDataLen(), origKAMessage->getDataLen()); PTF_ASSERT_BUF_COMPARE(newKAMessage.getData(), origKAMessage->getData(), origKAMessage->getDataLen()); @@ -244,36 +236,39 @@ PTF_TEST_CASE(BgpLayerCreationTest) PTF_ASSERT_BUF_COMPARE(bgpKAPacket.getRawPacket()->getRawData(), origBuffer, bufferLength1); delete origKAMessage; - - // create BGP ROUTE-REFRESH message memcpy(origBuffer, buffer2, bufferLength2); pcpp::BgpRouteRefreshMessageLayer newRouteRefreshMessage(1, 1); pcpp::Packet bgpRouteRefreshPacket(&rawPacket2); - pcpp::BgpRouteRefreshMessageLayer* origRouteRefreshMessage = dynamic_cast(bgpRouteRefreshPacket.detachLayer(pcpp::BGP)); + pcpp::BgpRouteRefreshMessageLayer* origRouteRefreshMessage = + dynamic_cast(bgpRouteRefreshPacket.detachLayer(pcpp::BGP)); PTF_ASSERT_NOT_NULL(origRouteRefreshMessage); newRouteRefreshMessage.getRouteRefreshHeader()->reserved = 1; PTF_ASSERT_EQUAL(newRouteRefreshMessage.getDataLen(), origRouteRefreshMessage->getDataLen()); - PTF_ASSERT_BUF_COMPARE(newRouteRefreshMessage.getData(), origRouteRefreshMessage->getData(), origRouteRefreshMessage->getDataLen()); + PTF_ASSERT_BUF_COMPARE(newRouteRefreshMessage.getData(), origRouteRefreshMessage->getData(), + origRouteRefreshMessage->getDataLen()); PTF_ASSERT_TRUE(bgpRouteRefreshPacket.addLayer(&newRouteRefreshMessage)); bgpRouteRefreshPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(bgpRouteRefreshPacket.getRawPacket()->getRawDataLen(), bufferLength2); PTF_ASSERT_BUF_COMPARE(bgpRouteRefreshPacket.getRawPacket()->getRawData(), origBuffer, bufferLength2); delete origRouteRefreshMessage; - - // create BGP NOTIFICATION message with notification data memcpy(origBuffer, buffer3, bufferLength3); - std::string notificationData = "7c4e54542077696c6c20706572666f726d206d61696e74656e616e6365206f6e207468697320726f757465722e205468697320697320747261636b656420696e205449434b45542d312d32343832343239342e20436f6e74616374206e6f63406e74742e6e657420666f72206d6f726520696e666f726d6174696f6e2e"; + std::string notificationData = + "7c4e54542077696c6c20706572666f726d206d61696e74656e616e6365206f6e207468697320726f757465722e20546869732069732074" + "7261636b656420696e205449434b45542d312d32343832343239342e20436f6e74616374206e6f63406e74742e6e657420666f72206d6f" + "726520696e666f726d6174696f6e2e"; pcpp::BgpNotificationMessageLayer newNotificationMessage(6, 2, notificationData); pcpp::Packet bgpNotificationPacket(&rawPacket3); - pcpp::BgpNotificationMessageLayer* origNotificationMessage = dynamic_cast(bgpNotificationPacket.detachLayer(pcpp::BGP)); + pcpp::BgpNotificationMessageLayer* origNotificationMessage = + dynamic_cast(bgpNotificationPacket.detachLayer(pcpp::BGP)); PTF_ASSERT_NOT_NULL(origNotificationMessage); PTF_ASSERT_EQUAL(newNotificationMessage.getDataLen(), origNotificationMessage->getDataLen()); - PTF_ASSERT_BUF_COMPARE(newNotificationMessage.getData(), origNotificationMessage->getData(), origNotificationMessage->getDataLen()); + PTF_ASSERT_BUF_COMPARE(newNotificationMessage.getData(), origNotificationMessage->getData(), + origNotificationMessage->getDataLen()); PTF_ASSERT_TRUE(bgpNotificationPacket.addLayer(&newNotificationMessage)); bgpNotificationPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(bgpNotificationPacket.getRawPacket()->getRawDataLen(), bufferLength3); @@ -285,18 +280,18 @@ PTF_TEST_CASE(BgpLayerCreationTest) memcpy(origBuffer, buffer4, bufferLength4); pcpp::BgpNotificationMessageLayer newNotificationMessage2(6, 4); pcpp::Packet bgpNotificationPacket2(&rawPacket4); - origNotificationMessage = dynamic_cast(bgpNotificationPacket2.detachLayer(pcpp::BGP)); + origNotificationMessage = + dynamic_cast(bgpNotificationPacket2.detachLayer(pcpp::BGP)); PTF_ASSERT_NOT_NULL(origNotificationMessage); PTF_ASSERT_EQUAL(newNotificationMessage2.getDataLen(), origNotificationMessage->getDataLen()); - PTF_ASSERT_BUF_COMPARE(newNotificationMessage2.getData(), origNotificationMessage->getData(), origNotificationMessage->getDataLen()); + PTF_ASSERT_BUF_COMPARE(newNotificationMessage2.getData(), origNotificationMessage->getData(), + origNotificationMessage->getDataLen()); PTF_ASSERT_TRUE(bgpNotificationPacket2.addLayer(&newNotificationMessage2)); bgpNotificationPacket2.computeCalculateFields(); PTF_ASSERT_EQUAL(bgpNotificationPacket2.getRawPacket()->getRawDataLen(), bufferLength4); PTF_ASSERT_BUF_COMPARE(bgpNotificationPacket2.getRawPacket()->getRawData(), origBuffer, bufferLength4); delete origNotificationMessage; - - // create BGP UPDATE message with Withdrawn Routes memcpy(origBuffer, buffer5, bufferLength5); @@ -307,7 +302,8 @@ PTF_TEST_CASE(BgpLayerCreationTest) withdrawnRoutes.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "103.103.40.0")); pcpp::BgpUpdateMessageLayer newUpdateMessage(withdrawnRoutes); pcpp::Packet bgpUpdatePacket1(&rawPacket5); - pcpp::BgpUpdateMessageLayer* origUpdateMessage = dynamic_cast(bgpUpdatePacket1.detachLayer(pcpp::BGP)); + pcpp::BgpUpdateMessageLayer* origUpdateMessage = + dynamic_cast(bgpUpdatePacket1.detachLayer(pcpp::BGP)); PTF_ASSERT_NOT_NULL(origUpdateMessage); PTF_ASSERT_EQUAL(newUpdateMessage.getDataLen(), origUpdateMessage->getDataLen()); PTF_ASSERT_BUF_COMPARE(newUpdateMessage.getData(), origUpdateMessage->getData(), origUpdateMessage->getDataLen()); @@ -326,7 +322,8 @@ PTF_TEST_CASE(BgpLayerCreationTest) pathAttributes.push_back(pcpp::BgpUpdateMessageLayer::path_attribute(0x40, 3, "1e031e03")); std::vector nlri; nlri.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "104.104.40.0")); - pcpp::BgpUpdateMessageLayer newUpdateMessage2(std::vector(), pathAttributes, nlri); + pcpp::BgpUpdateMessageLayer newUpdateMessage2(std::vector(), + pathAttributes, nlri); pcpp::Packet bgpUpdatePacket2(&rawPacket6); origUpdateMessage = dynamic_cast(bgpUpdatePacket2.detachLayer(pcpp::BGP)); PTF_ASSERT_NOT_NULL(origUpdateMessage); @@ -338,8 +335,6 @@ PTF_TEST_CASE(BgpLayerCreationTest) PTF_ASSERT_BUF_COMPARE(bgpUpdatePacket2.getRawPacket()->getRawData(), origBuffer, bufferLength6); delete origUpdateMessage; - - // create BGP OPEN message memcpy(origBuffer, buffer7, bufferLength7); @@ -351,7 +346,8 @@ PTF_TEST_CASE(BgpLayerCreationTest) optionalParams.push_back(pcpp::BgpOpenMessageLayer::optional_parameter(2, "410400000001")); pcpp::BgpOpenMessageLayer newOpenMessage(1, 180, pcpp::IPv4Address("1.1.1.1"), optionalParams); pcpp::Packet bgpOpenPacket(&rawPacket7); - pcpp::BgpOpenMessageLayer* origOpenMessage = dynamic_cast(bgpOpenPacket.detachLayer(pcpp::BGP)); + pcpp::BgpOpenMessageLayer* origOpenMessage = + dynamic_cast(bgpOpenPacket.detachLayer(pcpp::BGP)); PTF_ASSERT_NOT_NULL(origOpenMessage); PTF_ASSERT_EQUAL(newOpenMessage.getDataLen(), origOpenMessage->getDataLen()); PTF_ASSERT_BUF_COMPARE(newOpenMessage.getData(), origOpenMessage->getData(), origOpenMessage->getDataLen()); @@ -361,8 +357,6 @@ PTF_TEST_CASE(BgpLayerCreationTest) PTF_ASSERT_BUF_COMPARE(bgpOpenPacket.getRawPacket()->getRawData(), origBuffer, bufferLength7); delete origOpenMessage; - - // create packet with multiple BGP layers pcpp::EthLayer ethLayer(pcpp::MacAddress("fa:16:3e:34:89:43"), pcpp::MacAddress("fa:16:3e:22:35:cf")); @@ -373,7 +367,6 @@ PTF_TEST_CASE(BgpLayerCreationTest) ip4Layer.getIPv4Header()->timeToLive = 1; ip4Layer.getIPv4Header()->fragmentOffset = 0x40; - pcpp::TcpLayer tcpLayer(20576, 179); tcpLayer.getTcpHeader()->sequenceNumber = htobe32(3136152551); tcpLayer.getTcpHeader()->ackNumber = htobe32(4120889265); @@ -421,11 +414,13 @@ PTF_TEST_CASE(BgpLayerCreationTest) PTF_ASSERT_TRUE(newBgpMultiLayerPacket.addLayer(&newBgpUpdateMessage4)); newBgpMultiLayerPacket.computeCalculateFields(); - PTF_ASSERT_EQUAL(newBgpMultiLayerPacket.getRawPacket()->getRawDataLen(), bgpUpdatePacket2.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(newBgpMultiLayerPacket.getRawPacket()->getRawData(), bgpUpdatePacket2.getRawPacket()->getRawData(), bgpUpdatePacket2.getRawPacket()->getRawDataLen()); - -} // BgpLayerCreationTest + PTF_ASSERT_EQUAL(newBgpMultiLayerPacket.getRawPacket()->getRawDataLen(), + bgpUpdatePacket2.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(newBgpMultiLayerPacket.getRawPacket()->getRawData(), + bgpUpdatePacket2.getRawPacket()->getRawData(), + bgpUpdatePacket2.getRawPacket()->getRawDataLen()); +} // BgpLayerCreationTest PTF_TEST_CASE(BgpLayerEditTest) { @@ -441,34 +436,37 @@ PTF_TEST_CASE(BgpLayerEditTest) uint8_t origBuffer[1500]; - - // edit BGP NOTIFICATION message memcpy(origBuffer, buffer1, bufferLength1); pcpp::Packet bgpNotificationPacket1(&rawPacket1); pcpp::Packet bgpNotificationPacket2(&rawPacket2); - pcpp::BgpNotificationMessageLayer* bgpNotificationMessage1 = bgpNotificationPacket1.getLayerOfType(); + pcpp::BgpNotificationMessageLayer* bgpNotificationMessage1 = + bgpNotificationPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(bgpNotificationMessage1); PTF_ASSERT_TRUE(bgpNotificationMessage1->setNotificationData(nullptr, 0)); bgpNotificationMessage1->getNotificationMsgHeader()->errorSubCode = 4; bgpNotificationPacket1.computeCalculateFields(); - pcpp::BgpNotificationMessageLayer* bgpNotificationMessage2 = bgpNotificationPacket2.getLayerOfType(); + pcpp::BgpNotificationMessageLayer* bgpNotificationMessage2 = + bgpNotificationPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(bgpNotificationMessage2); PTF_ASSERT_EQUAL(bgpNotificationMessage1->getDataLen(), bgpNotificationMessage2->getDataLen()); - PTF_ASSERT_BUF_COMPARE(bgpNotificationMessage1->getData(), bgpNotificationMessage2->getData(), bgpNotificationMessage2->getDataLen()); + PTF_ASSERT_BUF_COMPARE(bgpNotificationMessage1->getData(), bgpNotificationMessage2->getData(), + bgpNotificationMessage2->getDataLen()); pcpp::RawPacket rawPacket1Tag(origBuffer, bufferLength1, time, false); bgpNotificationPacket1.setRawPacket(&rawPacket1Tag, false); bgpNotificationMessage1 = bgpNotificationPacket1.getLayerOfType(); - std::string notificationData = "7c4e54542077696c6c20706572666f726d206d61696e74656e616e6365206f6e207468697320726f757465722e205468697320697320747261636b656420696e205449434b45542d312d32343832343239342e20436f6e74616374206e6f63406e74742e6e657420666f72206d6f726520696e666f726d6174696f6e2e"; + std::string notificationData = + "7c4e54542077696c6c20706572666f726d206d61696e74656e616e6365206f6e207468697320726f757465722e20546869732069732074" + "7261636b656420696e205449434b45542d312d32343832343239342e20436f6e74616374206e6f63406e74742e6e657420666f72206d6f" + "726520696e666f726d6174696f6e2e"; PTF_ASSERT_TRUE(bgpNotificationMessage2->setNotificationData(notificationData)); bgpNotificationMessage2->getNotificationMsgHeader()->errorSubCode = 2; bgpNotificationPacket2.computeCalculateFields(); PTF_ASSERT_EQUAL(bgpNotificationMessage1->getDataLen(), bgpNotificationMessage2->getDataLen()); - PTF_ASSERT_BUF_COMPARE(bgpNotificationMessage1->getData(), bgpNotificationMessage2->getData(), bgpNotificationMessage2->getDataLen()); - - + PTF_ASSERT_BUF_COMPARE(bgpNotificationMessage1->getData(), bgpNotificationMessage2->getData(), + bgpNotificationMessage2->getDataLen()); // edit BGP OPEN message @@ -493,18 +491,22 @@ PTF_TEST_CASE(BgpLayerEditTest) PTF_ASSERT_EQUAL(bgpOpenMessage2->getHeaderLen(), 29); PTF_ASSERT_EQUAL(bgpOpenMessage2->getOptionalParametersLength(), 0); - - // edit BGP UPDATE message pcpp::Packet bgpUpdatePacket1(&rawPacket5); pcpp::Packet bgpUpdatePacket2(&rawPacket6); - pcpp::BgpUpdateMessageLayer* bgpUpdateMessage1Packet1 = bgpUpdatePacket1.getLayerOfType(); - pcpp::BgpUpdateMessageLayer* bgpUpdateMessage2Packet1 = bgpUpdatePacket1.getNextLayerOfType(bgpUpdateMessage1Packet1); - pcpp::BgpUpdateMessageLayer* bgpUpdateMessage1Packet2 = bgpUpdatePacket2.getLayerOfType(); - pcpp::BgpUpdateMessageLayer* bgpUpdateMessage2Packet2 = bgpUpdatePacket2.getNextLayerOfType(bgpUpdateMessage1Packet2); - pcpp::BgpUpdateMessageLayer* bgpUpdateMessage3Packet2 = bgpUpdatePacket2.getNextLayerOfType(bgpUpdateMessage2Packet2); - pcpp::BgpUpdateMessageLayer* bgpUpdateMessage4Packet2 = bgpUpdatePacket2.getNextLayerOfType(bgpUpdateMessage3Packet2); + pcpp::BgpUpdateMessageLayer* bgpUpdateMessage1Packet1 = + bgpUpdatePacket1.getLayerOfType(); + pcpp::BgpUpdateMessageLayer* bgpUpdateMessage2Packet1 = + bgpUpdatePacket1.getNextLayerOfType(bgpUpdateMessage1Packet1); + pcpp::BgpUpdateMessageLayer* bgpUpdateMessage1Packet2 = + bgpUpdatePacket2.getLayerOfType(); + pcpp::BgpUpdateMessageLayer* bgpUpdateMessage2Packet2 = + bgpUpdatePacket2.getNextLayerOfType(bgpUpdateMessage1Packet2); + pcpp::BgpUpdateMessageLayer* bgpUpdateMessage3Packet2 = + bgpUpdatePacket2.getNextLayerOfType(bgpUpdateMessage2Packet2); + pcpp::BgpUpdateMessageLayer* bgpUpdateMessage4Packet2 = + bgpUpdatePacket2.getNextLayerOfType(bgpUpdateMessage3Packet2); PTF_ASSERT_NOT_NULL(bgpUpdateMessage1Packet1); PTF_ASSERT_NOT_NULL(bgpUpdateMessage2Packet1); PTF_ASSERT_NOT_NULL(bgpUpdateMessage1Packet2); @@ -516,7 +518,8 @@ PTF_TEST_CASE(BgpLayerEditTest) withdrawnRoutes.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "104.104.40.0")); PTF_ASSERT_TRUE(bgpUpdateMessage1Packet1->setWithdrawnRoutes(withdrawnRoutes)); PTF_ASSERT_EQUAL(bgpUpdateMessage1Packet1->getHeaderLen(), bgpUpdateMessage2Packet1->getHeaderLen()); - PTF_ASSERT_BUF_COMPARE(bgpUpdateMessage1Packet1->getData(), bgpUpdateMessage2Packet1->getData(), bgpUpdateMessage2Packet1->getHeaderLen()); + PTF_ASSERT_BUF_COMPARE(bgpUpdateMessage1Packet1->getData(), bgpUpdateMessage2Packet1->getData(), + bgpUpdateMessage2Packet1->getHeaderLen()); PTF_ASSERT_TRUE(bgpUpdateMessage1Packet1->clearWithdrawnRoutes()); std::vector pathAttributes; @@ -528,7 +531,8 @@ PTF_TEST_CASE(BgpLayerEditTest) PTF_ASSERT_TRUE(bgpUpdateMessage1Packet1->setPathAttributes(pathAttributes)); PTF_ASSERT_TRUE(bgpUpdateMessage1Packet1->setNetworkLayerReachabilityInfo(nlri)); PTF_ASSERT_EQUAL(bgpUpdateMessage1Packet1->getHeaderLen(), bgpUpdateMessage1Packet2->getHeaderLen()); - PTF_ASSERT_BUF_COMPARE(bgpUpdateMessage1Packet1->getData(), bgpUpdateMessage1Packet2->getData(), bgpUpdateMessage1Packet2->getHeaderLen()); + PTF_ASSERT_BUF_COMPARE(bgpUpdateMessage1Packet1->getData(), bgpUpdateMessage1Packet2->getData(), + bgpUpdateMessage1Packet2->getHeaderLen()); pathAttributes.erase(pathAttributes.begin()); pathAttributes.insert(pathAttributes.begin(), pcpp::BgpUpdateMessageLayer::path_attribute(0x40, 1, "00")); @@ -540,20 +544,24 @@ PTF_TEST_CASE(BgpLayerEditTest) nlri.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(24, "103.103.40.0")); PTF_ASSERT_TRUE(bgpUpdateMessage1Packet1->setNetworkLayerReachabilityInfo(nlri)); PTF_ASSERT_EQUAL(bgpUpdateMessage1Packet1->getHeaderLen(), bgpUpdateMessage2Packet2->getHeaderLen()); - PTF_ASSERT_BUF_COMPARE(bgpUpdateMessage1Packet1->getData(), bgpUpdateMessage2Packet2->getData(), bgpUpdateMessage2Packet2->getHeaderLen()); + PTF_ASSERT_BUF_COMPARE(bgpUpdateMessage1Packet1->getData(), bgpUpdateMessage2Packet2->getData(), + bgpUpdateMessage2Packet2->getHeaderLen()); pathAttributes.erase(pathAttributes.begin() + 1); - pathAttributes.insert(pathAttributes.begin() + 1, pcpp::BgpUpdateMessageLayer::path_attribute(0x40, 2, "02020000000a00000014")); + pathAttributes.insert(pathAttributes.begin() + 1, + pcpp::BgpUpdateMessageLayer::path_attribute(0x40, 2, "02020000000a00000014")); PTF_ASSERT_TRUE(bgpUpdateMessage1Packet1->setPathAttributes(pathAttributes)); nlri.clear(); nlri.push_back(pcpp::BgpUpdateMessageLayer::prefix_and_ip(32, "20.100.100.20")); PTF_ASSERT_TRUE(bgpUpdateMessage1Packet1->setNetworkLayerReachabilityInfo(nlri)); PTF_ASSERT_EQUAL(bgpUpdateMessage1Packet1->getHeaderLen(), bgpUpdateMessage3Packet2->getHeaderLen()); - PTF_ASSERT_BUF_COMPARE(bgpUpdateMessage1Packet1->getData(), bgpUpdateMessage3Packet2->getData(), bgpUpdateMessage3Packet2->getHeaderLen()); + PTF_ASSERT_BUF_COMPARE(bgpUpdateMessage1Packet1->getData(), bgpUpdateMessage3Packet2->getData(), + bgpUpdateMessage3Packet2->getHeaderLen()); PTF_ASSERT_TRUE(bgpUpdateMessage1Packet1->clearNetworkLayerReachabilityInfo()); PTF_ASSERT_TRUE(bgpUpdateMessage1Packet1->clearPathAttributes()); PTF_ASSERT_EQUAL(bgpUpdateMessage1Packet1->getHeaderLen(), bgpUpdateMessage4Packet2->getHeaderLen()); - PTF_ASSERT_BUF_COMPARE(bgpUpdateMessage1Packet1->getData(), bgpUpdateMessage4Packet2->getData(), bgpUpdateMessage4Packet2->getHeaderLen()); + PTF_ASSERT_BUF_COMPARE(bgpUpdateMessage1Packet1->getData(), bgpUpdateMessage4Packet2->getData(), + bgpUpdateMessage4Packet2->getHeaderLen()); -} // BgpLayerEditTest +} // BgpLayerEditTest diff --git a/Tests/Packet++Test/Tests/CotpTests.cpp b/Tests/Packet++Test/Tests/CotpTests.cpp index 8c9e033ecc..b8f9ee8b35 100644 --- a/Tests/Packet++Test/Tests/CotpTests.cpp +++ b/Tests/Packet++Test/Tests/CotpTests.cpp @@ -37,4 +37,4 @@ PTF_TEST_CASE(CotpLayerTest) PTF_ASSERT_EQUAL(newCotpPacket.getPduType(), 0xd2); PTF_ASSERT_EQUAL(newCotpPacket.getTpduNumber(), 0x7d); -} // CotpLayerTest +} // CotpLayerTest diff --git a/Tests/Packet++Test/Tests/DhcpTests.cpp b/Tests/Packet++Test/Tests/DhcpTests.cpp index 55e4844d4b..f7702f6881 100644 --- a/Tests/Packet++Test/Tests/DhcpTests.cpp +++ b/Tests/Packet++Test/Tests/DhcpTests.cpp @@ -8,7 +8,6 @@ #include "UdpLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(DhcpParsingTest) { timeval time; @@ -33,20 +32,18 @@ PTF_TEST_CASE(DhcpParsingTest) PTF_ASSERT_EQUAL(dhcpLayer->getOptionsCount(), 12); pcpp::DhcpOption opt = dhcpLayer->getFirstOptionData(); - pcpp::DhcpOptionTypes optTypeArr[] = { - pcpp::DHCPOPT_DHCP_MESSAGE_TYPE, - pcpp::DHCPOPT_SUBNET_MASK, - pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER, - pcpp::DHCPOPT_DHCP_LEASE_TIME, - pcpp::DHCPOPT_ROUTERS, - pcpp::DHCPOPT_DOMAIN_NAME_SERVERS, - pcpp::DHCPOPT_TFTP_SERVER_NAME, - pcpp::DHCPOPT_SIP_SERVERS, - pcpp::DHCPOPT_DHCP_CLIENT_IDENTIFIER, - pcpp::DHCPOPT_AUTHENTICATION, - pcpp::DHCPOPT_DHCP_AGENT_OPTIONS, - pcpp::DHCPOPT_END - }; + pcpp::DhcpOptionTypes optTypeArr[] = { pcpp::DHCPOPT_DHCP_MESSAGE_TYPE, + pcpp::DHCPOPT_SUBNET_MASK, + pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER, + pcpp::DHCPOPT_DHCP_LEASE_TIME, + pcpp::DHCPOPT_ROUTERS, + pcpp::DHCPOPT_DOMAIN_NAME_SERVERS, + pcpp::DHCPOPT_TFTP_SERVER_NAME, + pcpp::DHCPOPT_SIP_SERVERS, + pcpp::DHCPOPT_DHCP_CLIENT_IDENTIFIER, + pcpp::DHCPOPT_AUTHENTICATION, + pcpp::DHCPOPT_DHCP_AGENT_OPTIONS, + pcpp::DHCPOPT_END }; size_t optLenArr[] = { 1, 4, 4, 4, 4, 8, 14, 5, 16, 31, 22, 0 }; @@ -67,14 +64,15 @@ PTF_TEST_CASE(DhcpParsingTest) PTF_ASSERT_FALSE(dhcpLayer->getOptionData(optTypeArr[i]).isNull()); } - PTF_ASSERT_EQUAL(dhcpLayer->getOptionData(pcpp::DHCPOPT_SUBNET_MASK).getValueAsIpAddr(), pcpp::IPv4Address("255.255.255.0")); - PTF_ASSERT_EQUAL(dhcpLayer->getOptionData(pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER).getValueAsIpAddr(), pcpp::IPv4Address("172.22.178.234")); + PTF_ASSERT_EQUAL(dhcpLayer->getOptionData(pcpp::DHCPOPT_SUBNET_MASK).getValueAsIpAddr(), + pcpp::IPv4Address("255.255.255.0")); + PTF_ASSERT_EQUAL(dhcpLayer->getOptionData(pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER).getValueAsIpAddr(), + pcpp::IPv4Address("172.22.178.234")); PTF_ASSERT_EQUAL(dhcpLayer->getOptionData(pcpp::DHCPOPT_DHCP_LEASE_TIME).getValueAs(), htobe32(43200)); PTF_ASSERT_EQUAL(dhcpLayer->getOptionData(pcpp::DHCPOPT_TFTP_SERVER_NAME).getValueAsString(), "172.22.178.234"); PTF_ASSERT_EQUAL(dhcpLayer->getMessageType(), pcpp::DHCP_OFFER, enum); - READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/Dhcp2.dat"); pcpp::Packet dhcpPacket2(&rawPacket2); @@ -92,17 +90,15 @@ PTF_TEST_CASE(DhcpParsingTest) PTF_ASSERT_EQUAL(dhcpLayer->getOptionsCount(), 9); opt = dhcpLayer->getFirstOptionData(); - pcpp::DhcpOptionTypes optTypeArr2[] = { - pcpp::DHCPOPT_DHCP_MESSAGE_TYPE, - pcpp::DHCPOPT_DHCP_MAX_MESSAGE_SIZE, - pcpp::DHCPOPT_DHCP_PARAMETER_REQUEST_LIST, - pcpp::DHCPOPT_DHCP_LEASE_TIME, - pcpp::DHCPOPT_DHCP_OPTION_OVERLOAD, - pcpp::DHCPOPT_DHCP_MESSAGE, - pcpp::DHCPOPT_PAD, - pcpp::DHCPOPT_DHCP_CLIENT_IDENTIFIER, - pcpp::DHCPOPT_END - }; + pcpp::DhcpOptionTypes optTypeArr2[] = { pcpp::DHCPOPT_DHCP_MESSAGE_TYPE, + pcpp::DHCPOPT_DHCP_MAX_MESSAGE_SIZE, + pcpp::DHCPOPT_DHCP_PARAMETER_REQUEST_LIST, + pcpp::DHCPOPT_DHCP_LEASE_TIME, + pcpp::DHCPOPT_DHCP_OPTION_OVERLOAD, + pcpp::DHCPOPT_DHCP_MESSAGE, + pcpp::DHCPOPT_PAD, + pcpp::DHCPOPT_DHCP_CLIENT_IDENTIFIER, + pcpp::DHCPOPT_END }; size_t optLenArr2[] = { 1, 2, 4, 4, 1, 7, 0, 7, 0 }; @@ -126,9 +122,7 @@ PTF_TEST_CASE(DhcpParsingTest) } PTF_ASSERT_EQUAL(dhcpLayer->getMessageType(), pcpp::DHCP_DISCOVER, enum); -} // DhcpParsingTest - - +} // DhcpParsingTest PTF_TEST_CASE(DhcpCreationTest) { @@ -154,28 +148,37 @@ PTF_TEST_CASE(DhcpCreationTest) dhcpLayer.setServerIpAddress(serverIP); dhcpLayer.setGatewayIpAddress(gatewayIP); - pcpp::DhcpOption subnetMaskOpt = dhcpLayer.addOption(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_SUBNET_MASK, pcpp::IPv4Address("255.255.255.0"))); + pcpp::DhcpOption subnetMaskOpt = + dhcpLayer.addOption(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_SUBNET_MASK, pcpp::IPv4Address("255.255.255.0"))); PTF_ASSERT_FALSE(subnetMaskOpt.isNull()); uint8_t sipServersData[] = { 0x01, 0xac, 0x16, 0xb2, 0xea }; - pcpp::DhcpOption sipServersOpt = dhcpLayer.addOption(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_SIP_SERVERS, sipServersData, 5)); + pcpp::DhcpOption sipServersOpt = + dhcpLayer.addOption(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_SIP_SERVERS, sipServersData, 5)); PTF_ASSERT_FALSE(sipServersOpt.isNull()); - uint8_t agentData[] = { 0x01, 0x14, 0x20, 0x50, 0x4f, 0x4e, 0x20, 0x31, 0x2f, 0x31, 0x2f, 0x30, 0x37, 0x2f, 0x30, 0x31, 0x3a, 0x31, 0x2e, 0x30, 0x2e, 0x31 }; - pcpp::DhcpOption agentOpt = dhcpLayer.addOption(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DHCP_AGENT_OPTIONS, agentData, 22)); + uint8_t agentData[] = { 0x01, 0x14, 0x20, 0x50, 0x4f, 0x4e, 0x20, 0x31, 0x2f, 0x31, 0x2f, + 0x30, 0x37, 0x2f, 0x30, 0x31, 0x3a, 0x31, 0x2e, 0x30, 0x2e, 0x31 }; + pcpp::DhcpOption agentOpt = + dhcpLayer.addOption(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DHCP_AGENT_OPTIONS, agentData, 22)); PTF_ASSERT_FALSE(agentOpt.isNull()); - pcpp::DhcpOption clientIdOpt = dhcpLayer.addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DHCP_CLIENT_IDENTIFIER, nullptr, 16), pcpp::DHCPOPT_SIP_SERVERS); + pcpp::DhcpOption clientIdOpt = dhcpLayer.addOptionAfter( + pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DHCP_CLIENT_IDENTIFIER, nullptr, 16), pcpp::DHCPOPT_SIP_SERVERS); clientIdOpt.setValue(0); clientIdOpt.setValueString("nathan1clientid", 1); PTF_ASSERT_FALSE(clientIdOpt.isNull()); - uint8_t authOptData[] = { 0x01, 0x01, 0x00, 0xc8, 0x78, 0xc4, 0x52, 0x56, 0x40, 0x20, 0x81, 0x31, 0x32, 0x33, 0x34, 0x8f, 0xe0, 0xcc, 0xe2, 0xee, 0x85, 0x96, - 0xab, 0xb2, 0x58, 0x17, 0xc4, 0x80, 0xb2, 0xfd, 0x30}; - pcpp::DhcpOption authOpt = dhcpLayer.addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_AUTHENTICATION, authOptData, 31), pcpp::DHCPOPT_DHCP_CLIENT_IDENTIFIER); + uint8_t authOptData[] = { 0x01, 0x01, 0x00, 0xc8, 0x78, 0xc4, 0x52, 0x56, 0x40, 0x20, 0x81, + 0x31, 0x32, 0x33, 0x34, 0x8f, 0xe0, 0xcc, 0xe2, 0xee, 0x85, 0x96, + 0xab, 0xb2, 0x58, 0x17, 0xc4, 0x80, 0xb2, 0xfd, 0x30 }; + pcpp::DhcpOption authOpt = dhcpLayer.addOptionAfter( + pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_AUTHENTICATION, authOptData, 31), pcpp::DHCPOPT_DHCP_CLIENT_IDENTIFIER); PTF_ASSERT_FALSE(authOpt.isNull()); - pcpp::DhcpOption dhcpServerIdOpt = dhcpLayer.addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER, pcpp::IPv4Address("172.22.178.234")), pcpp::DHCPOPT_SUBNET_MASK); + pcpp::DhcpOption dhcpServerIdOpt = dhcpLayer.addOptionAfter( + pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER, pcpp::IPv4Address("172.22.178.234")), + pcpp::DHCPOPT_SUBNET_MASK); PTF_ASSERT_FALSE(dhcpServerIdOpt.isNull()); pcpp::Packet newPacket(6); @@ -184,20 +187,25 @@ PTF_TEST_CASE(DhcpCreationTest) PTF_ASSERT_TRUE(newPacket.addLayer(&udpLayer)); PTF_ASSERT_TRUE(newPacket.addLayer(&dhcpLayer)); - pcpp::DhcpOption routerOpt = dhcpLayer.addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_ROUTERS, pcpp::IPv4Address("10.10.8.254")), pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER); + pcpp::DhcpOption routerOpt = + dhcpLayer.addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_ROUTERS, pcpp::IPv4Address("10.10.8.254")), + pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER); PTF_ASSERT_FALSE(routerOpt.isNull()); - pcpp::DhcpOption tftpServerOpt = dhcpLayer.addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_TFTP_SERVER_NAME, std::string("172.22.178.234")), pcpp::DHCPOPT_ROUTERS); + pcpp::DhcpOption tftpServerOpt = dhcpLayer.addOptionAfter( + pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_TFTP_SERVER_NAME, std::string("172.22.178.234")), pcpp::DHCPOPT_ROUTERS); PTF_ASSERT_FALSE(tftpServerOpt.isNull()); - pcpp::DhcpOption dnsOpt = dhcpLayer.addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DOMAIN_NAME_SERVERS, nullptr, 8), pcpp::DHCPOPT_ROUTERS); + pcpp::DhcpOption dnsOpt = dhcpLayer.addOptionAfter( + pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DOMAIN_NAME_SERVERS, nullptr, 8), pcpp::DHCPOPT_ROUTERS); PTF_ASSERT_FALSE(dnsOpt.isNull()); pcpp::IPv4Address dns1IP("143.209.4.1"); pcpp::IPv4Address dns2IP("143.209.5.1"); dnsOpt.setValueIpAddr(dns1IP); dnsOpt.setValueIpAddr(dns2IP, 4); - pcpp::DhcpOption leaseOpt = dhcpLayer.addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DHCP_LEASE_TIME, (uint32_t)43200), pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER); + pcpp::DhcpOption leaseOpt = dhcpLayer.addOptionAfter( + pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DHCP_LEASE_TIME, (uint32_t)43200), pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER); PTF_ASSERT_FALSE(leaseOpt.isNull()); newPacket.computeCalculateFields(); @@ -207,10 +215,8 @@ PTF_TEST_CASE(DhcpCreationTest) PTF_ASSERT_EQUAL(newPacket.getRawPacket()->getRawDataLen(), bufferLength1); PTF_ASSERT_BUF_COMPARE(newPacket.getRawPacket()->getRawData(), buffer1, bufferLength1); - delete [] buffer1; -} // DhcpCreationTest - - + delete[] buffer1; +} // DhcpCreationTest PTF_TEST_CASE(DhcpEditTest) { @@ -239,10 +245,12 @@ PTF_TEST_CASE(DhcpEditTest) pcpp::IPv4Address newRouter("192.168.2.1"); - opt = dhcpLayer->addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_ROUTERS, newRouter), pcpp::DHCPOPT_SUBNET_MASK); + opt = + dhcpLayer->addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_ROUTERS, newRouter), pcpp::DHCPOPT_SUBNET_MASK); PTF_ASSERT_FALSE(opt.isNull()); - opt = dhcpLayer->addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER, newRouter), pcpp::DHCPOPT_DHCP_MESSAGE_TYPE); + opt = dhcpLayer->addOptionAfter(pcpp::DhcpOptionBuilder(pcpp::DHCPOPT_DHCP_SERVER_IDENTIFIER, newRouter), + pcpp::DHCPOPT_DHCP_MESSAGE_TYPE); PTF_ASSERT_FALSE(opt.isNull()); dhcpPacket.computeCalculateFields(); @@ -252,7 +260,7 @@ PTF_TEST_CASE(DhcpEditTest) PTF_ASSERT_EQUAL(dhcpPacket.getRawPacket()->getRawDataLen(), bufferLength2); PTF_ASSERT_BUF_COMPARE(dhcpPacket.getRawPacket()->getRawData(), buffer2, bufferLength2); - delete [] buffer2; + delete[] buffer2; PTF_ASSERT_TRUE(dhcpLayer->removeAllOptions()); @@ -270,9 +278,9 @@ PTF_TEST_CASE(DhcpEditTest) PTF_ASSERT_EQUAL(dhcpLayer->getOptionsCount(), 2); - PTF_ASSERT_EQUAL(dhcpLayer->getDataLen(), sizeof(pcpp::dhcp_header)+4); + PTF_ASSERT_EQUAL(dhcpLayer->getDataLen(), sizeof(pcpp::dhcp_header) + 4); PTF_ASSERT_EQUAL(dhcpLayer->getMessageType(), pcpp::DHCP_DISCOVER, enum); dhcpPacket.computeCalculateFields(); -} // DhcpEditTest +} // DhcpEditTest diff --git a/Tests/Packet++Test/Tests/DhcpV6Tests.cpp b/Tests/Packet++Test/Tests/DhcpV6Tests.cpp index 0565b3ed8e..103023ef59 100644 --- a/Tests/Packet++Test/Tests/DhcpV6Tests.cpp +++ b/Tests/Packet++Test/Tests/DhcpV6Tests.cpp @@ -5,7 +5,6 @@ #include "DhcpV6Layer.h" #include "SystemUtils.h" - PTF_TEST_CASE(DhcpV6ParsingTest) { timeval time; @@ -22,14 +21,9 @@ PTF_TEST_CASE(DhcpV6ParsingTest) PTF_ASSERT_EQUAL(dhcpv6Layer->getOptionCount(), 6); PTF_ASSERT_EQUAL(dhcpv6Layer->toString(), "DHCPv6 Layer, Solicit message"); - pcpp::DhcpV6OptionType optTypeArr[] = { - pcpp::DHCPV6_OPT_CLIENTID, - pcpp::DHCPV6_OPT_ORO, - pcpp::DHCPV6_OPT_ELAPSED_TIME, - pcpp::DHCPV6_OPT_USER_CLASS, - pcpp::DHCPV6_OPT_VENDOR_CLASS, - pcpp::DHCPV6_OPT_IA_NA - }; + pcpp::DhcpV6OptionType optTypeArr[] = { pcpp::DHCPV6_OPT_CLIENTID, pcpp::DHCPV6_OPT_ORO, + pcpp::DHCPV6_OPT_ELAPSED_TIME, pcpp::DHCPV6_OPT_USER_CLASS, + pcpp::DHCPV6_OPT_VENDOR_CLASS, pcpp::DHCPV6_OPT_IA_NA }; size_t optDataSizeArr[] = { 18, 14, 2, 10, 51, 12 }; std::string optDataAsHexString[] = { "000200000009464745313934373134515300", @@ -50,8 +44,7 @@ PTF_TEST_CASE(DhcpV6ParsingTest) PTF_ASSERT_EQUAL(dhcpOption.getValueAsHexString(), optDataAsHexString[i]); dhcpOption = dhcpv6Layer->getNextOptionData(dhcpOption); } -} // DhcpV6ParsingTest - +} // DhcpV6ParsingTest PTF_TEST_CASE(DhcpV6CreationTest) { @@ -71,41 +64,53 @@ PTF_TEST_CASE(DhcpV6CreationTest) PTF_ASSERT_NOT_NULL(origDhcpV6Layer); // 1st option - pcpp::DhcpV6Option option = newDhcpV6Layer.addOption(pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_IA_NA, "1d00fcea00000000000000000005001820010dba0100000000000000000000300000017700000258")); + pcpp::DhcpV6Option option = newDhcpV6Layer.addOption(pcpp::DhcpV6OptionBuilder( + pcpp::DHCPV6_OPT_IA_NA, "1d00fcea00000000000000000005001820010dba0100000000000000000000300000017700000258")); PTF_ASSERT_EQUAL(option.getType(), pcpp::DHCPV6_OPT_IA_NA); PTF_ASSERT_EQUAL(option.getDataSize(), 40); PTF_ASSERT_EQUAL(newDhcpV6Layer.getOptionCount(), 1); // 4th option - option = newDhcpV6Layer.addOption(pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_DNS_SERVERS, "20010dba010000000000000000000001")); + option = newDhcpV6Layer.addOption( + pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_DNS_SERVERS, "20010dba010000000000000000000001")); PTF_ASSERT_EQUAL(option.getType(), pcpp::DHCPV6_OPT_DNS_SERVERS); PTF_ASSERT_EQUAL(option.getDataSize(), 16); PTF_ASSERT_EQUAL(newDhcpV6Layer.getOptionCount(), 2); // 3rd option - option = newDhcpV6Layer.addOptionBefore(pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_SERVERID, "000100012154eee7000c29703dd8"), pcpp::DHCPV6_OPT_DNS_SERVERS); + option = newDhcpV6Layer.addOptionBefore( + pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_SERVERID, "000100012154eee7000c29703dd8"), + pcpp::DHCPV6_OPT_DNS_SERVERS); PTF_ASSERT_EQUAL(option.getType(), pcpp::DHCPV6_OPT_SERVERID); PTF_ASSERT_EQUAL(option.getDataSize(), 14); PTF_ASSERT_EQUAL(newDhcpV6Layer.getOptionCount(), 3); // 2nd option - option = newDhcpV6Layer.addOptionAfter(pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_CLIENTID, "000200000009464745313934373134515300"), pcpp::DHCPV6_OPT_IA_NA); + option = newDhcpV6Layer.addOptionAfter( + pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_CLIENTID, "000200000009464745313934373134515300"), + pcpp::DHCPV6_OPT_IA_NA); PTF_ASSERT_EQUAL(option.getType(), pcpp::DHCPV6_OPT_CLIENTID); PTF_ASSERT_EQUAL(option.getDataSize(), 18); PTF_ASSERT_EQUAL(newDhcpV6Layer.getOptionCount(), 4); // 6th option - option = newDhcpV6Layer.addOption(pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_BOOTFILE_URL, "687474703a2f2f5b323030313a6462613a3130303a3a315d3a393039302f657868617573746976655f7a74705f7363726970742e7079")); + option = newDhcpV6Layer.addOption(pcpp::DhcpV6OptionBuilder( + pcpp::DHCPV6_OPT_BOOTFILE_URL, "687474703a2f2f5b323030313a6462613a3130303a3a315d3a393039302f6578686175737469766" + "55f7a74705f7363726970742e7079")); PTF_ASSERT_EQUAL(option.getType(), pcpp::DHCPV6_OPT_BOOTFILE_URL); PTF_ASSERT_EQUAL(option.getDataSize(), 54); PTF_ASSERT_EQUAL(newDhcpV6Layer.getOptionCount(), 5); // 5th option - option = newDhcpV6Layer.addOptionAfter(pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_DOMAIN_LIST, "05636973636f056c6f63616c00"), pcpp::DHCPV6_OPT_DNS_SERVERS); + option = newDhcpV6Layer.addOptionAfter( + pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_DOMAIN_LIST, "05636973636f056c6f63616c00"), + pcpp::DHCPV6_OPT_DNS_SERVERS); PTF_ASSERT_EQUAL(option.getType(), pcpp::DHCPV6_OPT_DOMAIN_LIST); PTF_ASSERT_EQUAL(option.getDataSize(), 13); PTF_ASSERT_EQUAL(newDhcpV6Layer.getOptionCount(), 6); pcpp::Logger::getInstance().suppressLogs(); // prev/next option doesn't exist in layer - option = newDhcpV6Layer.addOptionAfter(pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_DOMAIN_LIST, "05"), pcpp::DHCPV6_OPT_ELAPSED_TIME); + option = newDhcpV6Layer.addOptionAfter(pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_DOMAIN_LIST, "05"), + pcpp::DHCPV6_OPT_ELAPSED_TIME); PTF_ASSERT_TRUE(option.isNull()); - option = newDhcpV6Layer.addOptionBefore(pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_DOMAIN_LIST, "05"), pcpp::DHCPV6_OPT_ELAPSED_TIME); + option = newDhcpV6Layer.addOptionBefore(pcpp::DhcpV6OptionBuilder(pcpp::DHCPV6_OPT_DOMAIN_LIST, "05"), + pcpp::DHCPV6_OPT_ELAPSED_TIME); PTF_ASSERT_TRUE(option.isNull()); // string is not a valid hex stream @@ -123,8 +128,7 @@ PTF_TEST_CASE(DhcpV6CreationTest) PTF_ASSERT_EQUAL(dhcpv6Packet.getRawPacket()->getRawDataLen(), bufferLength1); PTF_ASSERT_BUF_COMPARE(dhcpv6Packet.getRawPacket()->getRawData(), origBuffer, bufferLength1); delete origDhcpV6Layer; -} // DhcpV6CreationTest - +} // DhcpV6CreationTest PTF_TEST_CASE(DhcpV6EditTest) { @@ -158,4 +162,4 @@ PTF_TEST_CASE(DhcpV6EditTest) dhcpv6Layer->removeAllOptions(); PTF_ASSERT_EQUAL(dhcpv6Layer->getOptionCount(), 0); PTF_ASSERT_EQUAL(dhcpv6Layer->getDataLen(), 4); -} // DhcpV6EditTest +} // DhcpV6EditTest diff --git a/Tests/Packet++Test/Tests/DnsTests.cpp b/Tests/Packet++Test/Tests/DnsTests.cpp index 5a34fcd2af..59713ec58f 100644 --- a/Tests/Packet++Test/Tests/DnsTests.cpp +++ b/Tests/Packet++Test/Tests/DnsTests.cpp @@ -11,7 +11,6 @@ #include "DnsLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(DnsLayerParsingTest) { timeval time; @@ -57,7 +56,8 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_EQUAL(firstAuthority->getName(), "Yaels-iPhone.local"); PTF_ASSERT_EQUAL(firstAuthority->getDataLength(), 4); PTF_ASSERT_EQUAL(firstAuthority->getData()->toString(), "10.0.0.2"); - PTF_ASSERT_EQUAL(firstAuthority->getData().castAs()->getIpAddress(), pcpp::IPv4Address("10.0.0.2")); + PTF_ASSERT_EQUAL(firstAuthority->getData().castAs()->getIpAddress(), + pcpp::IPv4Address("10.0.0.2")); PTF_ASSERT_EQUAL(firstAuthority->getSize(), 16); pcpp::DnsResource* secondAuthority = dnsLayer->getNextAuthority(firstAuthority); @@ -68,7 +68,8 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_EQUAL(secondAuthority->getName(), "Yaels-iPhone.local"); PTF_ASSERT_EQUAL(secondAuthority->getDataLength(), 16); PTF_ASSERT_EQUAL(secondAuthority->getData()->toString(), "fe80::5a1f:aaff:fe4f:3f9d"); - PTF_ASSERT_EQUAL(secondAuthority->getData().castAs()->getIpAddress(), pcpp::IPv6Address("fe80::5a1f:aaff:fe4f:3f9d")); + PTF_ASSERT_EQUAL(secondAuthority->getData().castAs()->getIpAddress(), + pcpp::IPv6Address("fe80::5a1f:aaff:fe4f:3f9d")); PTF_ASSERT_EQUAL(secondAuthority->getSize(), 28); pcpp::DnsResource* thirdAuthority = dnsLayer->getNextAuthority(secondAuthority); @@ -89,9 +90,8 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_NULL(dnsLayer->getNextAdditionalRecord(additionalRecord)); PTF_ASSERT_EQUAL(dnsLayer->getAdditionalRecord("", true), additionalRecord, ptr); - PTF_ASSERT_EQUAL(dnsLayer->toString(), "DNS query, ID: 0; queries: 2, answers: 0, authorities: 2, additional record: 1"); - - + PTF_ASSERT_EQUAL(dnsLayer->toString(), + "DNS query, ID: 0; queries: 2, answers: 0, authorities: 2, additional record: 1"); READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/Dns1.dat"); @@ -130,7 +130,8 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_EQUAL(curAnswer->getTTL(), 117); PTF_ASSERT_EQUAL(curAnswer->getName(), "www-google-analytics.L.google.com"); PTF_ASSERT_EQUAL(curAnswer->getDataLength(), 4); - PTF_ASSERT_TRUE(curAnswer->getData().castAs()->getIpAddress().matchNetwork(std::string("212.199.219.0/255.255.255.0"))); + PTF_ASSERT_TRUE(curAnswer->getData().castAs()->getIpAddress().matchNetwork( + std::string("212.199.219.0/255.255.255.0"))); curAnswer = dnsLayer->getNextAnswer(curAnswer); answerCount++; @@ -139,11 +140,11 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_EQUAL(answerCount, 18); PTF_ASSERT_EQUAL(dnsLayer->getAnswer("www.google-analytics.com", false), dnsLayer->getFirstAnswer(), ptr); - PTF_ASSERT_EQUAL(dnsLayer->getAnswer("www-google-analytics.L.google.com", true), dnsLayer->getNextAnswer(dnsLayer->getFirstAnswer()), ptr); - - PTF_ASSERT_EQUAL(dnsLayer->toString(), "DNS query response, ID: 11629; queries: 1, answers: 17, authorities: 0, additional record: 0"); - + PTF_ASSERT_EQUAL(dnsLayer->getAnswer("www-google-analytics.L.google.com", true), + dnsLayer->getNextAnswer(dnsLayer->getFirstAnswer()), ptr); + PTF_ASSERT_EQUAL(dnsLayer->toString(), + "DNS query response, ID: 11629; queries: 1, answers: 17, authorities: 0, additional record: 0"); READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/Dns2.dat"); @@ -155,9 +156,8 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_NOT_NULL(queryByName); PTF_ASSERT_EQUAL(queryByName->getDnsClass(), pcpp::DNS_CLASS_IN_QU, enum); - PTF_ASSERT_EQUAL(dnsLayer->toString(), "DNS query, ID: 0; queries: 2, answers: 0, authorities: 2, additional record: 1"); - - + PTF_ASSERT_EQUAL(dnsLayer->toString(), + "DNS query, ID: 0; queries: 2, answers: 0, authorities: 2, additional record: 1"); READ_FILE_AND_CREATE_PACKET(4, "PacketExamples/Dns4.dat"); @@ -171,7 +171,8 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_EQUAL(curAnswer->getDnsClass(), pcpp::DNS_CLASS_IN, enum); PTF_ASSERT_EQUAL(curAnswer->getData()->toString(), "pref: 1; mx: mta5.am0.yahoodns.net"); PTF_ASSERT_EQUAL(curAnswer->getData()->castAs()->getMxData().preference, 1); - PTF_ASSERT_EQUAL(curAnswer->getData()->castAs()->getMxData().mailExchange, "mta5.am0.yahoodns.net"); + PTF_ASSERT_EQUAL(curAnswer->getData()->castAs()->getMxData().mailExchange, + "mta5.am0.yahoodns.net"); curAnswer = dnsLayer->getNextAnswer(curAnswer); PTF_ASSERT_NOT_NULL(curAnswer); @@ -179,7 +180,8 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_EQUAL(curAnswer->getDnsClass(), pcpp::DNS_CLASS_IN, enum); PTF_ASSERT_EQUAL(curAnswer->getData()->toString(), "pref: 1; mx: mta7.am0.yahoodns.net"); PTF_ASSERT_EQUAL(curAnswer->getData()->castAs()->getMxData().preference, 1); - PTF_ASSERT_EQUAL(curAnswer->getData()->castAs()->getMxData().mailExchange, "mta7.am0.yahoodns.net"); + PTF_ASSERT_EQUAL(curAnswer->getData()->castAs()->getMxData().mailExchange, + "mta7.am0.yahoodns.net"); curAnswer = dnsLayer->getNextAnswer(curAnswer); PTF_ASSERT_NOT_NULL(curAnswer); @@ -187,9 +189,8 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_EQUAL(curAnswer->getDnsClass(), pcpp::DNS_CLASS_IN, enum); PTF_ASSERT_EQUAL(curAnswer->getData()->toString(), "pref: 1; mx: mta6.am0.yahoodns.net"); PTF_ASSERT_EQUAL(curAnswer->getData()->castAs()->getMxData().preference, 1); - PTF_ASSERT_EQUAL(curAnswer->getData()->castAs()->getMxData().mailExchange, "mta6.am0.yahoodns.net"); - - + PTF_ASSERT_EQUAL(curAnswer->getData()->castAs()->getMxData().mailExchange, + "mta6.am0.yahoodns.net"); READ_FILE_AND_CREATE_PACKET(5, "PacketExamples/dns_stack_overflow.dat"); @@ -201,12 +202,11 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_EQUAL(dnsLayer->getQueryCount(), 1); firstQuery = dnsLayer->getFirstQuery(); PTF_ASSERT_NOT_NULL(firstQuery); - PTF_ASSERT_EQUAL(firstQuery->getName(), - "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA."); + PTF_ASSERT_EQUAL(firstQuery->getName(), "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA."); PTF_ASSERT_EQUAL(firstQuery->getSize(), 134); PTF_ASSERT_NULL(dnsLayer->getNextQuery(firstQuery)); - // a corner case of malformed packet where the total number of resources overflow uint16 // by less than 300. This fixes the bug: https://github.com/seladb/PcapPlusPlus/issues/441 READ_FILE_AND_CREATE_PACKET(6, "PacketExamples/DnsTooManyResources.dat"); @@ -218,9 +218,7 @@ PTF_TEST_CASE(DnsLayerParsingTest) PTF_ASSERT_NULL(dnsLayer->getFirstAnswer()); PTF_ASSERT_NULL(dnsLayer->getFirstAuthority()); PTF_ASSERT_NULL(dnsLayer->getFirstAdditionalRecord()); -} // DnsLayerParsingTest - - +} // DnsLayerParsingTest PTF_TEST_CASE(DnsLayerQueryCreationTest) { @@ -238,7 +236,8 @@ PTF_TEST_CASE(DnsLayerQueryCreationTest) pcpp::DnsLayer dns2Layer; dns2Layer.getDnsHeader()->recursionDesired = true; dns2Layer.getDnsHeader()->transactionID = htobe16(0xb179); - pcpp::DnsQuery* newQuery = dns2Layer.addQuery("mail-attachment.googleusercontent.com", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN); + pcpp::DnsQuery* newQuery = + dns2Layer.addQuery("mail-attachment.googleusercontent.com", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN); PTF_ASSERT_NOT_NULL(newQuery); PTF_ASSERT_EQUAL(dns2Layer.getQueryCount(), 1); PTF_ASSERT_EQUAL(newQuery->getName(), "mail-attachment.googleusercontent.com"); @@ -255,7 +254,6 @@ PTF_TEST_CASE(DnsLayerQueryCreationTest) PTF_ASSERT_BUF_COMPARE(dnsEdit2Packet.getRawPacket()->getRawData(), buffer2, bufferLength2); - READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/DnsEdit1.dat"); pcpp::Packet dnsEdit1RefPacket(&rawPacket1); @@ -290,9 +288,7 @@ PTF_TEST_CASE(DnsLayerQueryCreationTest) PTF_ASSERT_EQUAL(dnsEdit1Packet.getRawPacket()->getRawDataLen(), bufferLength1); PTF_ASSERT_BUF_COMPARE(dnsEdit1Packet.getRawPacket()->getRawData(), buffer1, bufferLength1); -} // DnsLayerQueryCreationTest - - +} // DnsLayerQueryCreationTest PTF_TEST_CASE(DnsLayerResourceCreationTest) { @@ -314,7 +310,8 @@ PTF_TEST_CASE(DnsLayerResourceCreationTest) dns4Layer.getDnsHeader()->recursionAvailable = 1; pcpp::StringDnsResourceData stringDnsData("assets.pinterest.com.cdngc.net"); - pcpp::DnsResource* firstAnswer = dns4Layer.addAnswer("assets.pinterest.com", pcpp::DNS_TYPE_CNAME, pcpp::DNS_CLASS_IN, 228, &stringDnsData); + pcpp::DnsResource* firstAnswer = + dns4Layer.addAnswer("assets.pinterest.com", pcpp::DNS_TYPE_CNAME, pcpp::DNS_CLASS_IN, 228, &stringDnsData); PTF_ASSERT_NOT_NULL(firstAnswer); PTF_ASSERT_EQUAL(dns4Layer.getFirstAnswer(), firstAnswer, ptr); PTF_ASSERT_EQUAL(firstAnswer->getData()->toString(), "assets.pinterest.com.cdngc.net"); @@ -328,9 +325,11 @@ PTF_TEST_CASE(DnsLayerResourceCreationTest) PTF_ASSERT_EQUAL(dnsEdit4Packet.getLayerOfType()->getFirstAnswer(), firstAnswer, ptr); pcpp::IPv4DnsResourceData ipv4DnsData(std::string("151.249.90.217")); - pcpp::DnsResource* secondAnswer = dns4Layer.addAnswer("assets.pinterest.com.cdngc.net", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN, 3, &ipv4DnsData); + pcpp::DnsResource* secondAnswer = + dns4Layer.addAnswer("assets.pinterest.com.cdngc.net", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN, 3, &ipv4DnsData); PTF_ASSERT_NOT_NULL(secondAnswer); - PTF_ASSERT_EQUAL(secondAnswer->getData()->castAs()->getIpAddress(), ipv4DnsData.getIpAddress()); + PTF_ASSERT_EQUAL(secondAnswer->getData()->castAs()->getIpAddress(), + ipv4DnsData.getIpAddress()); pcpp::DnsQuery* query = dns4Layer.addQuery("assets.pinterest.com", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN); PTF_ASSERT_NOT_NULL(query); @@ -338,7 +337,8 @@ PTF_TEST_CASE(DnsLayerResourceCreationTest) PTF_ASSERT_EQUAL(dnsEdit4Packet.getLayerOfType()->getFirstAnswer(), firstAnswer, ptr); PTF_ASSERT_EQUAL(dnsEdit4Packet.getLayerOfType()->getNextAnswer(firstAnswer), secondAnswer, ptr); - PTF_ASSERT_RAISES(pcpp::IPv4DnsResourceData(std::string("256.249.90.238")), std::invalid_argument, "Not a valid IPv4 address: 256.249.90.238"); + PTF_ASSERT_RAISES(pcpp::IPv4DnsResourceData(std::string("256.249.90.238")), std::invalid_argument, + "Not a valid IPv4 address: 256.249.90.238"); pcpp::DnsResource* thirdAnswer = dns4Layer.addAnswer(secondAnswer); PTF_ASSERT_NOT_NULL(thirdAnswer); @@ -348,8 +348,11 @@ PTF_TEST_CASE(DnsLayerResourceCreationTest) ipv4DnsData = pcpp::IPv4DnsResourceData(std::string("151.249.90.238")); PTF_ASSERT_TRUE(thirdAnswer->setData(&ipv4DnsData)); - PTF_ASSERT_EQUAL(dns4Layer.getAnswer("assets.pinterest.com.cdngc.net", true)->getData()->toString(), "151.249.90.217"); - PTF_ASSERT_EQUAL(dns4Layer.getNextAnswer(dns4Layer.getAnswer("assets.pinterest.com.cdngc.net", false))->getData()->toString(), "151.249.90.238"); + PTF_ASSERT_EQUAL(dns4Layer.getAnswer("assets.pinterest.com.cdngc.net", true)->getData()->toString(), + "151.249.90.217"); + PTF_ASSERT_EQUAL( + dns4Layer.getNextAnswer(dns4Layer.getAnswer("assets.pinterest.com.cdngc.net", false))->getData()->toString(), + "151.249.90.238"); dnsEdit4Packet.computeCalculateFields(); @@ -357,9 +360,6 @@ PTF_TEST_CASE(DnsLayerResourceCreationTest) PTF_ASSERT_BUF_COMPARE(dnsEdit4Packet.getRawPacket()->getRawData(), buffer4, bufferLength4); - - - READ_FILE_AND_CREATE_PACKET(6, "PacketExamples/DnsEdit6.dat"); pcpp::Packet dnsEdit6RefPacket(&rawPacket6); @@ -371,7 +371,8 @@ PTF_TEST_CASE(DnsLayerResourceCreationTest) pcpp::DnsLayer dnsLayer6; ipv4DnsData = pcpp::IPv4DnsResourceData(std::string("10.0.0.2")); - pcpp::DnsResource* authority = dnsLayer6.addAuthority("Yaels-iPhone.local", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN, 120, &ipv4DnsData); + pcpp::DnsResource* authority = + dnsLayer6.addAuthority("Yaels-iPhone.local", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN, 120, &ipv4DnsData); PTF_ASSERT_NOT_NULL(authority); query = dnsLayer6.addQuery(query); @@ -387,7 +388,8 @@ PTF_TEST_CASE(DnsLayerResourceCreationTest) PTF_ASSERT_EQUAL(dnsLayer6.getAuthority("Yaels-iPhone.local", true)->getData()->toString(), "10.0.0.2"); - PTF_ASSERT_RAISES(pcpp::IPv6DnsResourceData(std::string("##80::5a1f:aaff:fe4f:3f9d")), std::invalid_argument, "Not a valid IPv6 address: ##80::5a1f:aaff:fe4f:3f9d"); + PTF_ASSERT_RAISES(pcpp::IPv6DnsResourceData(std::string("##80::5a1f:aaff:fe4f:3f9d")), std::invalid_argument, + "Not a valid IPv6 address: ##80::5a1f:aaff:fe4f:3f9d"); authority = dnsLayer6.addAuthority(authority); pcpp::Logger::getInstance().suppressLogs(); @@ -421,8 +423,6 @@ PTF_TEST_CASE(DnsLayerResourceCreationTest) PTF_ASSERT_BUF_COMPARE(dnsEdit6Packet.getRawPacket()->getRawData(), buffer6, bufferLength6); - - READ_FILE_AND_CREATE_PACKET(7, "PacketExamples/DnsEdit7.dat"); pcpp::Packet dnsEdit7RefPacket(&rawPacket7); @@ -444,7 +444,8 @@ PTF_TEST_CASE(DnsLayerResourceCreationTest) queryNameOffset << "#" << query->getNameOffset(); pcpp::MxDnsResourceData mxDnsData(1, "mta5.am0.yahoodns.net"); - pcpp::DnsResource* answer = dnsLayer7.addAnswer(queryNameOffset.str(), pcpp::DNS_TYPE_MX, pcpp::DNS_CLASS_IN, 187, &mxDnsData); + pcpp::DnsResource* answer = + dnsLayer7.addAnswer(queryNameOffset.str(), pcpp::DNS_TYPE_MX, pcpp::DNS_CLASS_IN, 187, &mxDnsData); PTF_ASSERT_NOT_NULL(answer); std::stringstream firsAnswerMxOffset; @@ -469,19 +470,21 @@ PTF_TEST_CASE(DnsLayerResourceCreationTest) PTF_ASSERT_EQUAL(dnsEdit7Packet.getRawPacket()->getRawDataLen(), bufferLength7); PTF_ASSERT_BUF_COMPARE(dnsEdit7Packet.getRawPacket()->getRawData(), buffer7, bufferLength7); -} // DnsLayerResourceCreationTest +} // DnsLayerResourceCreationTest PTF_TEST_CASE(DnsLayerAddDnsKeyTest) { // data length overflow 256 - const std::string dnskey = "AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQ \ + const std::string dnskey = + "AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQ \ lNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+Sr \ DK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU="; pcpp::DnsLayer dnsLayer; pcpp::GenericDnsResourceData genericData(reinterpret_cast(dnskey.c_str()), dnskey.size()); - const auto* additional = dnsLayer.addAnswer("github.com", pcpp::DNS_TYPE_DNSKEY, pcpp::DNS_CLASS_IN, 32, &genericData); + const auto* additional = + dnsLayer.addAnswer("github.com", pcpp::DNS_TYPE_DNSKEY, pcpp::DNS_CLASS_IN, 32, &genericData); PTF_ASSERT_NOT_NULL(additional); } @@ -516,9 +519,7 @@ PTF_TEST_CASE(DnsLayerEditTest) PTF_ASSERT_TRUE(dnsLayer5->getFirstQuery()->setName("assets.pinterest.com")); PTF_ASSERT_EQUAL(dnsLayer3->getHeaderLen(), dnsLayer5->getHeaderLen()); PTF_ASSERT_BUF_COMPARE(dnsLayer3->getData(), dnsLayer5->getData(), dnsLayer3->getHeaderLen()); -} // DnsLayerEditTest - - +} // DnsLayerEditTest PTF_TEST_CASE(DnsLayerRemoveResourceTest) { @@ -547,9 +548,11 @@ PTF_TEST_CASE(DnsLayerRemoveResourceTest) PTF_ASSERT_EQUAL(dnsLayer6->getFirstAuthority()->getData()->toString(), "10.0.0.2"); PTF_ASSERT_EQUAL(dnsLayer6->getFirstAdditionalRecord()->getDnsType(), pcpp::DNS_TYPE_OPT, enum); - PTF_ASSERT_EQUAL(dnsLayer6->getHeaderLen(), origDnsLayer6.getHeaderLen()-firstQuerySize); + PTF_ASSERT_EQUAL(dnsLayer6->getHeaderLen(), origDnsLayer6.getHeaderLen() - firstQuerySize); - PTF_ASSERT_BUF_COMPARE(dnsLayer6->getData() + sizeof(pcpp::dnshdr), origDnsLayer6.getData() + sizeof(pcpp::dnshdr)+firstQuerySize , dnsLayer6->getHeaderLen() - sizeof(pcpp::dnshdr)); + PTF_ASSERT_BUF_COMPARE(dnsLayer6->getData() + sizeof(pcpp::dnshdr), + origDnsLayer6.getData() + sizeof(pcpp::dnshdr) + firstQuerySize, + dnsLayer6->getHeaderLen() - sizeof(pcpp::dnshdr)); pcpp::DnsResource* firstAuthority = dnsLayer6->getFirstAuthority(); pcpp::DnsResource* secondAuthority = dnsLayer6->getNextAuthority(firstAuthority); @@ -563,7 +566,7 @@ PTF_TEST_CASE(DnsLayerRemoveResourceTest) PTF_ASSERT_EQUAL(firstAuthority->getTTL(), 120); PTF_ASSERT_EQUAL(dnsLayer6->getFirstAdditionalRecord()->getDnsType(), pcpp::DNS_TYPE_OPT, enum); PTF_ASSERT_EQUAL(dnsLayer6->getFirstAdditionalRecord()->getDataLength(), 12); - PTF_ASSERT_EQUAL(dnsLayer6->getHeaderLen(), origDnsLayer6.getHeaderLen()-firstQuerySize-secondAuthoritySize); + PTF_ASSERT_EQUAL(dnsLayer6->getHeaderLen(), origDnsLayer6.getHeaderLen() - firstQuerySize - secondAuthoritySize); PTF_ASSERT_FALSE(dnsLayer6->removeQuery("BlaBla", true)); PTF_ASSERT_FALSE(dnsLayer6->removeAuthority(secondAuthority)); @@ -574,10 +577,8 @@ PTF_TEST_CASE(DnsLayerRemoveResourceTest) PTF_ASSERT_EQUAL(dnsLayer6->getAdditionalRecordCount(), 0); PTF_ASSERT_NULL(dnsLayer6->getFirstAdditionalRecord()); PTF_ASSERT_EQUAL(dnsLayer6->getFirstAuthority()->getData()->toString(), "10.0.0.2"); - PTF_ASSERT_EQUAL(dnsLayer6->getHeaderLen(), origDnsLayer6.getHeaderLen()-firstQuerySize-secondAuthoritySize-additionalRecordSize); - - - + PTF_ASSERT_EQUAL(dnsLayer6->getHeaderLen(), + origDnsLayer6.getHeaderLen() - firstQuerySize - secondAuthoritySize - additionalRecordSize); READ_FILE_AND_CREATE_PACKET(4, "PacketExamples/DnsEdit4.dat"); @@ -591,7 +592,7 @@ PTF_TEST_CASE(DnsLayerRemoveResourceTest) firstQuerySize = dnsLayer4->getFirstQuery()->getSize(); PTF_ASSERT_TRUE(dnsLayer4->removeQuery("pinter", false)); PTF_ASSERT_EQUAL(dnsLayer4->getQueryCount(), 0); - PTF_ASSERT_EQUAL(dnsLayer4->getHeaderLen(), origDnsLayer4.getHeaderLen()-firstQuerySize); + PTF_ASSERT_EQUAL(dnsLayer4->getHeaderLen(), origDnsLayer4.getHeaderLen() - firstQuerySize); pcpp::DnsResource* firstAnswer = dnsLayer4->getFirstAnswer(); PTF_ASSERT_NOT_NULL(firstAnswer); @@ -609,20 +610,19 @@ PTF_TEST_CASE(DnsLayerRemoveResourceTest) PTF_ASSERT_EQUAL(dnsLayer4->getAnswerCount(), 2); PTF_ASSERT_EQUAL(dnsLayer4->getFirstAnswer(), firstAnswer, ptr); PTF_ASSERT_EQUAL(dnsLayer4->getNextAnswer(dnsLayer4->getFirstAnswer()), thirdAnswer, ptr); - PTF_ASSERT_EQUAL(dnsLayer4->getHeaderLen(), origDnsLayer4.getHeaderLen()-firstQuerySize-secondAnswerSize); + PTF_ASSERT_EQUAL(dnsLayer4->getHeaderLen(), origDnsLayer4.getHeaderLen() - firstQuerySize - secondAnswerSize); PTF_ASSERT_TRUE(dnsLayer4->removeAnswer(firstAnswer)); PTF_ASSERT_EQUAL(dnsLayer4->getAnswerCount(), 1); PTF_ASSERT_EQUAL(dnsLayer4->getFirstAnswer(), thirdAnswer, ptr); PTF_ASSERT_EQUAL(dnsLayer4->getFirstAnswer()->getData()->toString(), "151.249.90.238"); - PTF_ASSERT_EQUAL(dnsLayer4->getHeaderLen(), origDnsLayer4.getHeaderLen()-firstQuerySize-secondAnswerSize-firstAnswerSize); + PTF_ASSERT_EQUAL(dnsLayer4->getHeaderLen(), + origDnsLayer4.getHeaderLen() - firstQuerySize - secondAnswerSize - firstAnswerSize); PTF_ASSERT_TRUE(dnsLayer4->removeAnswer(thirdAnswer)); PTF_ASSERT_FALSE(dnsLayer4->removeAdditionalRecord("blabla", false)); PTF_ASSERT_EQUAL(dnsLayer4->getHeaderLen(), sizeof(pcpp::dnshdr)); -} // DnsLayerRemoveResourceTest - - +} // DnsLayerRemoveResourceTest PTF_TEST_CASE(DnsOverTcpParsingTest) { @@ -652,7 +652,6 @@ PTF_TEST_CASE(DnsOverTcpParsingTest) PTF_ASSERT_EQUAL(additionalRecord->getDnsType(), pcpp::DNS_TYPE_OPT, enum); PTF_ASSERT_EQUAL(additionalRecord->getName(), ""); - READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/dns_over_tcp_response.dat"); pcpp::Packet dnsPacket2(&rawPacket2); @@ -666,37 +665,28 @@ PTF_TEST_CASE(DnsOverTcpParsingTest) PTF_ASSERT_EQUAL(be16toh(dnsLayer->getDnsHeader()->transactionID), 0x6165, hex); PTF_ASSERT_EQUAL(dnsOverTcpLayer->getTcpMessageLength(), 1133); - std::string expectedNames[8] = { - "net", - "net", - "A1RT98BS5QGC9NFI51S9HCI47ULJG6JH.net", - "A1RT98BS5QGC9NFI51S9HCI47ULJG6JH.net", - "QT8SCE02D5ONC5NBTQUNBEIDMFJE7GL8.net", - "QT8SCE02D5ONC5NBTQUNBEIDMFJE7GL8.net", - "EEQ3CIFFULOPN4J3E5MKEGKVDJKIGVBP.net", - "EEQ3CIFFULOPN4J3E5MKEGKVDJKIGVBP.net" - }; - - pcpp::DnsType expectedTypes[8] = { - pcpp::DNS_TYPE_SOA, - pcpp::DNS_TYPE_RRSIG, - pcpp::DNS_TYPE_NSEC3, - pcpp::DNS_TYPE_RRSIG, - pcpp::DNS_TYPE_NSEC3, - pcpp::DNS_TYPE_RRSIG, - pcpp::DNS_TYPE_NSEC3, - pcpp::DNS_TYPE_RRSIG - }; + std::string expectedNames[8] = { "net", + "net", + "A1RT98BS5QGC9NFI51S9HCI47ULJG6JH.net", + "A1RT98BS5QGC9NFI51S9HCI47ULJG6JH.net", + "QT8SCE02D5ONC5NBTQUNBEIDMFJE7GL8.net", + "QT8SCE02D5ONC5NBTQUNBEIDMFJE7GL8.net", + "EEQ3CIFFULOPN4J3E5MKEGKVDJKIGVBP.net", + "EEQ3CIFFULOPN4J3E5MKEGKVDJKIGVBP.net" }; + + pcpp::DnsType expectedTypes[8] = { pcpp::DNS_TYPE_SOA, pcpp::DNS_TYPE_RRSIG, pcpp::DNS_TYPE_NSEC3, + pcpp::DNS_TYPE_RRSIG, pcpp::DNS_TYPE_NSEC3, pcpp::DNS_TYPE_RRSIG, + pcpp::DNS_TYPE_NSEC3, pcpp::DNS_TYPE_RRSIG }; int i = 0; - for (pcpp::DnsResource* authority = dnsLayer->getFirstAuthority(); authority != nullptr; authority = dnsLayer->getNextAuthority(authority)) + for (pcpp::DnsResource* authority = dnsLayer->getFirstAuthority(); authority != nullptr; + authority = dnsLayer->getNextAuthority(authority)) { PTF_ASSERT_EQUAL(authority->getName(), expectedNames[i]); PTF_ASSERT_EQUAL(authority->getDnsType(), expectedTypes[i], enum); i++; } - READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/dns_over_tcp_answer.dat"); pcpp::Packet dnsPacket3(&rawPacket3); @@ -712,10 +702,9 @@ PTF_TEST_CASE(DnsOverTcpParsingTest) pcpp::DnsResource* answer = dnsLayer->getFirstAnswer(); PTF_ASSERT_EQUAL(answer->getName(), "github.com"); - PTF_ASSERT_EQUAL(answer->getData().castAs()->getIpAddress().toString(), "192.30.255.113"); -} // DnsOverTcpParsingTest - - + PTF_ASSERT_EQUAL(answer->getData().castAs()->getIpAddress().toString(), + "192.30.255.113"); +} // DnsOverTcpParsingTest PTF_TEST_CASE(DnsOverTcpCreationTest) { @@ -741,7 +730,7 @@ PTF_TEST_CASE(DnsOverTcpCreationTest) PTF_ASSERT_EQUAL(bufferLength1, dnsPacket.getRawPacket()->getRawDataLen()); PTF_ASSERT_BUF_COMPARE(dnsPacket.getRawPacket()->getRawData(), buffer1, bufferLength1); -} // DnsOverTcpCreationTest +} // DnsOverTcpCreationTest PTF_TEST_CASE(DnsNXDomainTest) { @@ -754,4 +743,4 @@ PTF_TEST_CASE(DnsNXDomainTest) pcpp::DnsLayer* dnsLayer = dnsPacket.getLayerOfType(); PTF_ASSERT_EQUAL(1, dnsLayer->getDnsHeader()->queryOrResponse); -} // DnsNXDomainTest +} // DnsNXDomainTest diff --git a/Tests/Packet++Test/Tests/EthAndArpTests.cpp b/Tests/Packet++Test/Tests/EthAndArpTests.cpp index 906ad73fea..74138ef055 100644 --- a/Tests/Packet++Test/Tests/EthAndArpTests.cpp +++ b/Tests/Packet++Test/Tests/EthAndArpTests.cpp @@ -13,7 +13,8 @@ PTF_TEST_CASE(OUILookup) { pcpp::OUILookup lookupEngineJson; - PTF_ASSERT_GREATER_THAN(lookupEngineJson.initOUIDatabaseFromJson("../../3rdParty/OUIDataset/PCPP_OUIDataset.json"), 0); + PTF_ASSERT_GREATER_THAN(lookupEngineJson.initOUIDatabaseFromJson("../../3rdParty/OUIDataset/PCPP_OUIDataset.json"), + 0); PTF_ASSERT_EQUAL(lookupEngineJson.getVendorName("aa:aa:aa:aa:aa:aa"), "Unknown"); // CIDR 36 @@ -50,9 +51,10 @@ PTF_TEST_CASE(EthPacketCreation) PTF_ASSERT_NOT_NULL(rawPacket); PTF_ASSERT_EQUAL(rawPacket->getRawDataLen(), 18); - uint8_t expectedBuffer[18] = { 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x08, 0x00, 0x01, 0x02, 0x03, 0x04 }; + uint8_t expectedBuffer[18] = { 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xaa, 0xaa, 0xaa, + 0xaa, 0xaa, 0xaa, 0x08, 0x00, 0x01, 0x02, 0x03, 0x04 }; PTF_ASSERT_BUF_COMPARE(rawPacket->getRawData(), expectedBuffer, 18); -} // EthPacketCreation +} // EthPacketCreation PTF_TEST_CASE(EthPacketPointerCreation) { @@ -72,17 +74,18 @@ PTF_TEST_CASE(EthPacketPointerCreation) PTF_ASSERT_EQUAL(ethPacket->getLayerOfType(), ethLayer, ptr); PTF_ASSERT_EQUAL(ethPacket->getLayerOfType()->getDestMac(), dstMac); PTF_ASSERT_EQUAL(ethPacket->getLayerOfType()->getSourceMac(), srcMac); - PTF_ASSERT_EQUAL(ethPacket->getLayerOfType()->getEthHeader()->etherType, be16toh(PCPP_ETHERTYPE_IP)); + PTF_ASSERT_EQUAL(ethPacket->getLayerOfType()->getEthHeader()->etherType, + be16toh(PCPP_ETHERTYPE_IP)); pcpp::RawPacket* rawPacket = ethPacket->getRawPacket(); PTF_ASSERT_NOT_NULL(rawPacket); PTF_ASSERT_EQUAL(rawPacket->getRawDataLen(), 18); - uint8_t expectedBuffer[18] = { 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0x08, 0x00, 0x01, 0x02, 0x03, 0x04 }; + uint8_t expectedBuffer[18] = { 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xaa, 0xaa, 0xaa, + 0xaa, 0xaa, 0xaa, 0x08, 0x00, 0x01, 0x02, 0x03, 0x04 }; PTF_ASSERT_BUF_COMPARE(rawPacket->getRawData(), expectedBuffer, 18); - delete(ethPacket); -} // EthPacketPointerCreation - + delete (ethPacket); +} // EthPacketPointerCreation PTF_TEST_CASE(EthAndArpPacketParsing) { @@ -113,8 +116,7 @@ PTF_TEST_CASE(EthAndArpPacketParsing) PTF_ASSERT_EQUAL(arpLayer->isRequest(), false); PTF_ASSERT_EQUAL(arpLayer->getSenderIpAddr(), pcpp::IPv4Address("10.0.0.138")); PTF_ASSERT_EQUAL(arpLayer->getTargetMacAddress(), pcpp::MacAddress("6c:f0:49:b2:de:6e")); -} // EthAndArpPacketParsing - +} // EthAndArpPacketParsing PTF_TEST_CASE(ArpPacketCreation) { @@ -122,7 +124,8 @@ PTF_TEST_CASE(ArpPacketCreation) pcpp::MacAddress dstMac("ff:ff:ff:ff:ff:ff"); pcpp::EthLayer ethLayer(srcMac, dstMac, PCPP_ETHERTYPE_ARP); - pcpp::ArpLayer arpLayer(pcpp::ARP_REQUEST, srcMac, srcMac, pcpp::IPv4Address("10.0.0.1"), pcpp::IPv4Address("10.0.0.138")); + pcpp::ArpLayer arpLayer(pcpp::ARP_REQUEST, srcMac, srcMac, pcpp::IPv4Address("10.0.0.1"), + pcpp::IPv4Address("10.0.0.138")); pcpp::Packet arpRequestPacket(1); PTF_ASSERT_TRUE(arpRequestPacket.addLayer(ðLayer)); @@ -142,9 +145,8 @@ PTF_TEST_CASE(ArpPacketCreation) PTF_ASSERT_EQUAL(bufferLength1, arpRequestPacket.getRawPacket()->getRawDataLen()); PTF_ASSERT_BUF_COMPARE(arpRequestPacket.getRawPacket()->getRawData(), buffer1, bufferLength1); - delete [] buffer1; -} // ArpPacketCreation - + delete[] buffer1; +} // ArpPacketCreation PTF_TEST_CASE(EthDot3LayerParsingTest) { @@ -164,8 +166,7 @@ PTF_TEST_CASE(EthDot3LayerParsingTest) PTF_ASSERT_NOT_NULL(ethDot3Layer->getNextLayer()); PTF_ASSERT_EQUAL(ethDot3Layer->getNextLayer()->getProtocol(), pcpp::LLC, enum); -} // EthDot3LayerParsingTest - +} // EthDot3LayerParsingTest PTF_TEST_CASE(EthDot3LayerCreateEditTest) { @@ -181,7 +182,8 @@ PTF_TEST_CASE(EthDot3LayerCreateEditTest) pcpp::MacAddress dstAddr("01:80:c2:00:00:00"); pcpp::EthDot3Layer ethDot3NewLayer(srcAddr, dstAddr, 38); - pcpp::PayloadLayer newPayloadLayer("424203000000000000000013f71edff00000271080000013f7115ec0801b0100140002000f000000000000000000"); + pcpp::PayloadLayer newPayloadLayer( + "424203000000000000000013f71edff00000271080000013f7115ec0801b0100140002000f000000000000000000"); PTF_ASSERT_EQUAL(newPayloadLayer.getDataLen(), 46); pcpp::Packet newEthDot3Packet; @@ -191,15 +193,16 @@ PTF_TEST_CASE(EthDot3LayerCreateEditTest) PTF_ASSERT_BUF_COMPARE(newEthDot3Packet.getRawPacket()->getRawData(), buffer1, bufferLength1); - // edit an EthDot3 packet ethDot3NewLayer.setSourceMac(pcpp::MacAddress("00:1a:a1:97:d1:85")); ethDot3NewLayer.getEthHeader()->length = htobe16(121); - auto newPayloadLayer2 = new pcpp::PayloadLayer("424203000003027c8000000c305dd100000000008000000c305dd10080050000140002000f000000500000000" - "00000000000000000000000000000000000000000000000000000000000000055bf4e8a44b25d442868549c1bf7720f00030d408000001a" - "a197d180137c8005000c305dd10000030d40808013"); + auto newPayloadLayer2 = new pcpp::PayloadLayer( + "424203000003027c8000000c305dd100000000008000000c305dd10080050000140002000f000000500000000" + "00000000000000000000000000000000000000000000000000000000000000055bf4e8a44b25d442868549c1bf7720f00030d408000001" + "a" + "a197d180137c8005000c305dd10000030d40808013"); PTF_ASSERT_TRUE(newEthDot3Packet.detachLayer(&newPayloadLayer)); PTF_ASSERT_TRUE(newEthDot3Packet.addLayer(newPayloadLayer2, true)); @@ -207,7 +210,7 @@ PTF_TEST_CASE(EthDot3LayerCreateEditTest) PTF_ASSERT_BUF_COMPARE(newEthDot3Packet.getRawPacket()->getRawData(), buffer2, bufferLength2); - delete [] buffer1; - delete [] buffer2; + delete[] buffer1; + delete[] buffer2; -} // EthDot3LayerCreateEditTest +} // EthDot3LayerCreateEditTest diff --git a/Tests/Packet++Test/Tests/FtpTests.cpp b/Tests/Packet++Test/Tests/FtpTests.cpp index 7f7612e3dd..0b309221e8 100644 --- a/Tests/Packet++Test/Tests/FtpTests.cpp +++ b/Tests/Packet++Test/Tests/FtpTests.cpp @@ -18,7 +18,7 @@ PTF_TEST_CASE(FtpParsingTests) READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ftpIpv4Req.dat"); pcpp::Packet ftpPacket1(&rawPacket1); - pcpp::FtpRequestLayer *ftpLayer1 = ftpPacket1.getLayerOfType(); + pcpp::FtpRequestLayer* ftpLayer1 = ftpPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpLayer1); PTF_ASSERT_EQUAL(int(ftpLayer1->getCommand()), int(pcpp::FtpRequestLayer::FtpCommand::USER)); @@ -30,7 +30,7 @@ PTF_TEST_CASE(FtpParsingTests) READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/ftpIpv4Resp.dat"); pcpp::Packet ftpPacket2(&rawPacket2); - pcpp::FtpResponseLayer *ftpLayer2 = ftpPacket2.getLayerOfType(); + pcpp::FtpResponseLayer* ftpLayer2 = ftpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpLayer2); PTF_ASSERT_EQUAL(int(ftpLayer2->getStatusCode()), int(pcpp::FtpResponseLayer::FtpStatusCode::REQ_FILE_OK_COMPLETE)); @@ -42,7 +42,7 @@ PTF_TEST_CASE(FtpParsingTests) READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/ftpIpv4RespHyphen.dat"); pcpp::Packet ftpPacket3(&rawPacket3); - pcpp::FtpResponseLayer *ftpLayer3 = ftpPacket3.getLayerOfType(); + pcpp::FtpResponseLayer* ftpLayer3 = ftpPacket3.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpLayer3); PTF_ASSERT_EQUAL(int(ftpLayer3->getStatusCode()), int(pcpp::FtpResponseLayer::FtpStatusCode::SYSTEM_STATUS)); @@ -55,7 +55,7 @@ PTF_TEST_CASE(FtpParsingTests) READ_FILE_AND_CREATE_PACKET(4, "PacketExamples/ftpIpv6Req.dat"); pcpp::Packet ftpPacket4(&rawPacket4); - pcpp::FtpRequestLayer *ftpLayer4 = ftpPacket4.getLayerOfType(); + pcpp::FtpRequestLayer* ftpLayer4 = ftpPacket4.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpLayer4); PTF_ASSERT_EQUAL(int(ftpLayer4->getCommand()), int(pcpp::FtpRequestLayer::FtpCommand::PASS)); @@ -67,11 +67,11 @@ PTF_TEST_CASE(FtpParsingTests) READ_FILE_AND_CREATE_PACKET(5, "PacketExamples/ftpIpv6Resp.dat"); pcpp::Packet ftpPacket5(&rawPacket5); - pcpp::FtpResponseLayer *ftpLayer5 = ftpPacket5.getLayerOfType(); + pcpp::FtpResponseLayer* ftpLayer5 = ftpPacket5.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpLayer5); PTF_ASSERT_EQUAL(int(ftpLayer5->getStatusCode()), - int(pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_NOT_IMPLEMENTED)); + int(pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_NOT_IMPLEMENTED)); PTF_ASSERT_EQUAL(ftpLayer5->getStatusCodeString(), "502"); PTF_ASSERT_EQUAL(ftpLayer5->getStatusOption(), "Unknown command 'utf8'."); PTF_ASSERT_EQUAL(ftpLayer5->toString(), "FTP Response: 502"); @@ -81,7 +81,7 @@ PTF_TEST_CASE(FtpParsingTests) READ_FILE_AND_CREATE_PACKET(6, "PacketExamples/ftp-data.dat"); pcpp::Packet ftpDataPacket(&rawPacket6); - pcpp::FtpDataLayer *ftpDataLayer = ftpDataPacket.getLayerOfType(); + pcpp::FtpDataLayer* ftpDataLayer = ftpDataPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpDataLayer); @@ -90,174 +90,179 @@ PTF_TEST_CASE(FtpParsingTests) // Command codes std::vector> possibleCommandCodes = { - {static_cast(0), "Unknown command"}, - {pcpp::FtpRequestLayer::FtpCommand::ABOR, "Abort an active file transfer"}, - {pcpp::FtpRequestLayer::FtpCommand::ACCT, "Account information"}, - {pcpp::FtpRequestLayer::FtpCommand::ADAT, "Authentication/Security Data"}, - {pcpp::FtpRequestLayer::FtpCommand::ALLO, "Allocate sufficient disk space to receive a file"}, - {pcpp::FtpRequestLayer::FtpCommand::APPE, "Append (with create)"}, - {pcpp::FtpRequestLayer::FtpCommand::AUTH, "Authentication/Security Mechanism"}, - {pcpp::FtpRequestLayer::FtpCommand::AVBL, "Get the available space"}, - {pcpp::FtpRequestLayer::FtpCommand::CCC, "Clear Command Channel"}, - {pcpp::FtpRequestLayer::FtpCommand::CDUP, "Change to Parent Directory"}, - {pcpp::FtpRequestLayer::FtpCommand::CONF, "Confidentiality Protection Command"}, - {pcpp::FtpRequestLayer::FtpCommand::CSID, "Client / Server Identification"}, - {pcpp::FtpRequestLayer::FtpCommand::CWD, "Change working directory"}, - {pcpp::FtpRequestLayer::FtpCommand::DELE, "Delete file"}, - {pcpp::FtpRequestLayer::FtpCommand::DSIZ, "Get the directory size"}, - {pcpp::FtpRequestLayer::FtpCommand::ENC, "Privacy Protected Channel"}, - {pcpp::FtpRequestLayer::FtpCommand::EPRT, - "Specifies an extended address and port to which the server should connect"}, - {pcpp::FtpRequestLayer::FtpCommand::EPSV, "Enter extended passive mode"}, - {pcpp::FtpRequestLayer::FtpCommand::FEAT, "Get the feature list implemented by the server"}, - {pcpp::FtpRequestLayer::FtpCommand::HELP, - "Returns usage documentation on a command if specified, else a general help document is returned"}, - {pcpp::FtpRequestLayer::FtpCommand::HOST, "Identify desired virtual host on server, by name"}, - {pcpp::FtpRequestLayer::FtpCommand::LANG, "Language Negotiation"}, - {pcpp::FtpRequestLayer::FtpCommand::LIST, "Returns information of a file or directory if specified, else " - "information of the current working directory is returned"}, - {pcpp::FtpRequestLayer::FtpCommand::LPRT, - "Specifies a long address and port to which the server should connect"}, - {pcpp::FtpRequestLayer::FtpCommand::LPSV, "Enter long passive mode"}, - {pcpp::FtpRequestLayer::FtpCommand::MDTM, "Return the last-modified time of a specified file"}, - {pcpp::FtpRequestLayer::FtpCommand::MFCT, "Modify the creation time of a file"}, - {pcpp::FtpRequestLayer::FtpCommand::MFF, - "Modify fact (the last modification time, creation time, UNIX group/owner/mode of a file)"}, - {pcpp::FtpRequestLayer::FtpCommand::MFMT, "Modify the last modification time of a file"}, - {pcpp::FtpRequestLayer::FtpCommand::MIC, "Integrity Protected Command"}, - {pcpp::FtpRequestLayer::FtpCommand::MKD, "Make directory"}, - {pcpp::FtpRequestLayer::FtpCommand::MLSD, - "Lists the contents of a directory in a standardized machine-readable format"}, - {pcpp::FtpRequestLayer::FtpCommand::MLST, - "Provides data about exactly the object named on its command line in a standardized machine-readable format"}, - {pcpp::FtpRequestLayer::FtpCommand::MODE, "Sets the transfer mode (Stream, Block, or Compressed)"}, - {pcpp::FtpRequestLayer::FtpCommand::NLST, "Returns a list of file names in a specified directory"}, - {pcpp::FtpRequestLayer::FtpCommand::NOOP, "No operation (dummy packet; used mostly on keepalives)"}, - {pcpp::FtpRequestLayer::FtpCommand::OPTS, "Select options for a feature (for example OPTS UTF8 ON)"}, - {pcpp::FtpRequestLayer::FtpCommand::PASS, "Authentication password"}, - {pcpp::FtpRequestLayer::FtpCommand::PASV, "Enter passive mode"}, - {pcpp::FtpRequestLayer::FtpCommand::PBSZ, "Protection Buffer Size"}, - {pcpp::FtpRequestLayer::FtpCommand::PORT, "Specifies an address and port to which the server should connect"}, - {pcpp::FtpRequestLayer::FtpCommand::PROT, "Data Channel Protection Level"}, - {pcpp::FtpRequestLayer::FtpCommand::PWD, "Print working directory. Returns the current directory of the host"}, - {pcpp::FtpRequestLayer::FtpCommand::QUIT, "Disconnect"}, - {pcpp::FtpRequestLayer::FtpCommand::REIN, "Re initializes the connection"}, - {pcpp::FtpRequestLayer::FtpCommand::REST, "Restart transfer from the specified point"}, - {pcpp::FtpRequestLayer::FtpCommand::RETR, "Retrieve a copy of the file"}, - {pcpp::FtpRequestLayer::FtpCommand::RMD, "Remove a directory"}, - {pcpp::FtpRequestLayer::FtpCommand::RMDA, "Remove a directory tree"}, - {pcpp::FtpRequestLayer::FtpCommand::RNFR, "Rename from"}, - {pcpp::FtpRequestLayer::FtpCommand::RNTO, "Rename to"}, - {pcpp::FtpRequestLayer::FtpCommand::SITE, - "Sends site specific commands to remote server (like SITE IDLE 60 or SITE UMASK 002). Inspect SITE HELP " - "output for complete list of supported commands"}, - {pcpp::FtpRequestLayer::FtpCommand::SIZE, "Return the size of a file"}, - {pcpp::FtpRequestLayer::FtpCommand::SMNT, "Mount file structure"}, - {pcpp::FtpRequestLayer::FtpCommand::SPSV, "Use single port passive mode (only one TCP port number for both " - "control connections and passive-mode data connections)"}, - {pcpp::FtpRequestLayer::FtpCommand::STAT, - "Returns information on the server status, including the status of the current connection"}, - {pcpp::FtpRequestLayer::FtpCommand::STOR, "Accept the data and to store the data as a file at the server site"}, - {pcpp::FtpRequestLayer::FtpCommand::STOU, "Store file uniquely"}, - {pcpp::FtpRequestLayer::FtpCommand::STRU, "Set file transfer structure"}, - {pcpp::FtpRequestLayer::FtpCommand::SYST, "Return system type"}, - {pcpp::FtpRequestLayer::FtpCommand::THMB, "Get a thumbnail of a remote image file"}, - {pcpp::FtpRequestLayer::FtpCommand::TYPE, "Sets the transfer mode (ASCII/Binary)"}, - {pcpp::FtpRequestLayer::FtpCommand::USER, "Authentication username"}, - {pcpp::FtpRequestLayer::FtpCommand::XCUP, "Change to the parent of the current working directory"}, - {pcpp::FtpRequestLayer::FtpCommand::XMKD, "Make a directory"}, - {pcpp::FtpRequestLayer::FtpCommand::XPWD, "Print the current working directory"}, - {pcpp::FtpRequestLayer::FtpCommand::XRCP, ""}, - {pcpp::FtpRequestLayer::FtpCommand::XRMD, "Remove the directory"}, - {pcpp::FtpRequestLayer::FtpCommand::XRSQ, ""}, - {pcpp::FtpRequestLayer::FtpCommand::XSEM, "Send, mail if cannot"}, - {pcpp::FtpRequestLayer::FtpCommand::XSEN, "Send to terminal"}}; - - for (const auto &entry : possibleCommandCodes) + { static_cast(0), "Unknown command" }, + { pcpp::FtpRequestLayer::FtpCommand::ABOR, "Abort an active file transfer" }, + { pcpp::FtpRequestLayer::FtpCommand::ACCT, "Account information" }, + { pcpp::FtpRequestLayer::FtpCommand::ADAT, "Authentication/Security Data" }, + { pcpp::FtpRequestLayer::FtpCommand::ALLO, "Allocate sufficient disk space to receive a file" }, + { pcpp::FtpRequestLayer::FtpCommand::APPE, "Append (with create)" }, + { pcpp::FtpRequestLayer::FtpCommand::AUTH, "Authentication/Security Mechanism" }, + { pcpp::FtpRequestLayer::FtpCommand::AVBL, "Get the available space" }, + { pcpp::FtpRequestLayer::FtpCommand::CCC, "Clear Command Channel" }, + { pcpp::FtpRequestLayer::FtpCommand::CDUP, "Change to Parent Directory" }, + { pcpp::FtpRequestLayer::FtpCommand::CONF, "Confidentiality Protection Command" }, + { pcpp::FtpRequestLayer::FtpCommand::CSID, "Client / Server Identification" }, + { pcpp::FtpRequestLayer::FtpCommand::CWD, "Change working directory" }, + { pcpp::FtpRequestLayer::FtpCommand::DELE, "Delete file" }, + { pcpp::FtpRequestLayer::FtpCommand::DSIZ, "Get the directory size" }, + { pcpp::FtpRequestLayer::FtpCommand::ENC, "Privacy Protected Channel" }, + { pcpp::FtpRequestLayer::FtpCommand::EPRT, + "Specifies an extended address and port to which the server should connect" }, + { pcpp::FtpRequestLayer::FtpCommand::EPSV, "Enter extended passive mode" }, + { pcpp::FtpRequestLayer::FtpCommand::FEAT, "Get the feature list implemented by the server" }, + { pcpp::FtpRequestLayer::FtpCommand::HELP, + "Returns usage documentation on a command if specified, else a general help document is returned" }, + { pcpp::FtpRequestLayer::FtpCommand::HOST, "Identify desired virtual host on server, by name" }, + { pcpp::FtpRequestLayer::FtpCommand::LANG, "Language Negotiation" }, + { pcpp::FtpRequestLayer::FtpCommand::LIST, "Returns information of a file or directory if specified, else " + "information of the current working directory is returned" }, + { pcpp::FtpRequestLayer::FtpCommand::LPRT, + "Specifies a long address and port to which the server should connect" }, + { pcpp::FtpRequestLayer::FtpCommand::LPSV, "Enter long passive mode" }, + { pcpp::FtpRequestLayer::FtpCommand::MDTM, "Return the last-modified time of a specified file" }, + { pcpp::FtpRequestLayer::FtpCommand::MFCT, "Modify the creation time of a file" }, + { pcpp::FtpRequestLayer::FtpCommand::MFF, + "Modify fact (the last modification time, creation time, UNIX group/owner/mode of a file)" }, + { pcpp::FtpRequestLayer::FtpCommand::MFMT, "Modify the last modification time of a file" }, + { pcpp::FtpRequestLayer::FtpCommand::MIC, "Integrity Protected Command" }, + { pcpp::FtpRequestLayer::FtpCommand::MKD, "Make directory" }, + { pcpp::FtpRequestLayer::FtpCommand::MLSD, + "Lists the contents of a directory in a standardized machine-readable format" }, + { pcpp::FtpRequestLayer::FtpCommand::MLST, "Provides data about exactly the object named on its command line " + "in a standardized machine-readable format" }, + { pcpp::FtpRequestLayer::FtpCommand::MODE, "Sets the transfer mode (Stream, Block, or Compressed)"}, + { pcpp::FtpRequestLayer::FtpCommand::NLST, "Returns a list of file names in a specified directory" }, + { pcpp::FtpRequestLayer::FtpCommand::NOOP, "No operation (dummy packet; used mostly on keepalives)"}, + { pcpp::FtpRequestLayer::FtpCommand::OPTS, "Select options for a feature (for example OPTS UTF8 ON)" }, + { pcpp::FtpRequestLayer::FtpCommand::PASS, "Authentication password"}, + { pcpp::FtpRequestLayer::FtpCommand::PASV, "Enter passive mode" }, + { pcpp::FtpRequestLayer::FtpCommand::PBSZ, "Protection Buffer Size"}, + { pcpp::FtpRequestLayer::FtpCommand::PORT, "Specifies an address and port to which the server should connect" }, + { pcpp::FtpRequestLayer::FtpCommand::PROT, "Data Channel Protection Level"}, + { pcpp::FtpRequestLayer::FtpCommand::PWD, + "Print working directory. Returns the current directory of the host" }, + { pcpp::FtpRequestLayer::FtpCommand::QUIT, "Disconnect"}, + { pcpp::FtpRequestLayer::FtpCommand::REIN, "Re initializes the connection" }, + { pcpp::FtpRequestLayer::FtpCommand::REST, "Restart transfer from the specified point"}, + { pcpp::FtpRequestLayer::FtpCommand::RETR, "Retrieve a copy of the file" }, + { pcpp::FtpRequestLayer::FtpCommand::RMD, "Remove a directory"}, + { pcpp::FtpRequestLayer::FtpCommand::RMDA, "Remove a directory tree" }, + { pcpp::FtpRequestLayer::FtpCommand::RNFR, "Rename from"}, + { pcpp::FtpRequestLayer::FtpCommand::RNTO, "Rename to" }, + { pcpp::FtpRequestLayer::FtpCommand::SITE, + "Sends site specific commands to remote server (like SITE IDLE 60 or SITE UMASK 002). Inspect SITE HELP " + "output for complete list of supported commands"}, + { pcpp::FtpRequestLayer::FtpCommand::SIZE, "Return the size of a file" }, + { pcpp::FtpRequestLayer::FtpCommand::SMNT, "Mount file structure"}, + { pcpp::FtpRequestLayer::FtpCommand::SPSV, "Use single port passive mode (only one TCP port number for both " + "control connections and passive-mode data connections)" }, + { pcpp::FtpRequestLayer::FtpCommand::STAT, + "Returns information on the server status, including the status of the current connection"}, + { pcpp::FtpRequestLayer::FtpCommand::STOR, + "Accept the data and to store the data as a file at the server site" }, + { pcpp::FtpRequestLayer::FtpCommand::STOU, "Store file uniquely"}, + { pcpp::FtpRequestLayer::FtpCommand::STRU, "Set file transfer structure" }, + { pcpp::FtpRequestLayer::FtpCommand::SYST, "Return system type"}, + { pcpp::FtpRequestLayer::FtpCommand::THMB, "Get a thumbnail of a remote image file" }, + { pcpp::FtpRequestLayer::FtpCommand::TYPE, "Sets the transfer mode (ASCII/Binary)"}, + { pcpp::FtpRequestLayer::FtpCommand::USER, "Authentication username" }, + { pcpp::FtpRequestLayer::FtpCommand::XCUP, "Change to the parent of the current working directory"}, + { pcpp::FtpRequestLayer::FtpCommand::XMKD, "Make a directory" }, + { pcpp::FtpRequestLayer::FtpCommand::XPWD, "Print the current working directory"}, + { pcpp::FtpRequestLayer::FtpCommand::XRCP, "" }, + { pcpp::FtpRequestLayer::FtpCommand::XRMD, "Remove the directory"}, + { pcpp::FtpRequestLayer::FtpCommand::XRSQ, "" }, + { pcpp::FtpRequestLayer::FtpCommand::XSEM, "Send, mail if cannot"}, + { pcpp::FtpRequestLayer::FtpCommand::XSEN, "Send to terminal" } + }; + + for (const auto& entry : possibleCommandCodes) { PTF_ASSERT_EQUAL(pcpp::FtpRequestLayer::getCommandInfo(entry.first), entry.second); } // Status codes std::vector> possibleStatusCodes = { - {static_cast(0), "Unknown Status Code"}, - {pcpp::FtpResponseLayer::FtpStatusCode::RESTART_MARKER, "Restart marker reply"}, - {pcpp::FtpResponseLayer::FtpStatusCode::SERVICE_READY_IN_MIN, "Service ready in nnn minutes"}, - {pcpp::FtpResponseLayer::FtpStatusCode::DATA_ALREADY_OPEN_START_TRANSFER, - "Data connection already open; transfer starting"}, - {pcpp::FtpResponseLayer::FtpStatusCode::FILE_OK, "File status okay; about to open data connection"}, - {pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_OK, "Command okay"}, - {pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_NOT_IMPLEMENTED_SUPERFLUOUS, - "Command not implemented, superfluous at this site"}, - {pcpp::FtpResponseLayer::FtpStatusCode::SYSTEM_STATUS, "System status, or system help reply"}, - {pcpp::FtpResponseLayer::FtpStatusCode::DIR_STATUS, "Directory status"}, - {pcpp::FtpResponseLayer::FtpStatusCode::FILE_STATUS, "File status"}, - {pcpp::FtpResponseLayer::FtpStatusCode::HELP_MESSAGE, "Help message"}, - {pcpp::FtpResponseLayer::FtpStatusCode::NAME_SYSTEM_TYPE, "NAME system type"}, - {pcpp::FtpResponseLayer::FtpStatusCode::SERVICE_READY_FOR_USER, "Service ready for new user"}, - {pcpp::FtpResponseLayer::FtpStatusCode::SERVICE_CLOSING_CONTROL, "Service closing control connection"}, - {pcpp::FtpResponseLayer::FtpStatusCode::DATA_OPEN_NO_TRANSFER, "Data connection open; no transfer in progress"}, - {pcpp::FtpResponseLayer::FtpStatusCode::CLOSING_DATA, "Closing data connection"}, - {pcpp::FtpResponseLayer::FtpStatusCode::ENTERING_PASSIVE, "Entering Passive Mode"}, - {pcpp::FtpResponseLayer::FtpStatusCode::ENTERING_EXTENDED_PASSIVE, "Entering Extended Passive Mode"}, - {pcpp::FtpResponseLayer::FtpStatusCode::USER_LOG_IN_PROCEED, "User logged in, proceed"}, - {pcpp::FtpResponseLayer::FtpStatusCode::USER_LOG_IN_AUTHORIZED, - "User logged in, authorized by security data exchange"}, - {pcpp::FtpResponseLayer::FtpStatusCode::SEC_DATA_EXCHANGE_COMPLETE, "Security data exchange complete"}, - {pcpp::FtpResponseLayer::FtpStatusCode::SEC_DATA_EXCHANGE_COMPLETE_SUCCESS, - "Security data exchange completed successfully"}, - {pcpp::FtpResponseLayer::FtpStatusCode::REQ_FILE_OK_COMPLETE, "Requested file action okay, completed"}, - {pcpp::FtpResponseLayer::FtpStatusCode::PATHNAME_CREATED, "PATHNAME created"}, - {pcpp::FtpResponseLayer::FtpStatusCode::USER_OK_NEED_PASSWORD, "User name okay, need password"}, - {pcpp::FtpResponseLayer::FtpStatusCode::NEED_ACCOUNT, "Need account for login"}, - {pcpp::FtpResponseLayer::FtpStatusCode::REQ_SEC_MECHANISM_OK, "Requested security mechanism is ok"}, - {pcpp::FtpResponseLayer::FtpStatusCode::SEC_IS_ACCEPTABLE, "Security data is acceptable, more is required"}, - {pcpp::FtpResponseLayer::FtpStatusCode::USER_OK_NEED_PASS_CHALLENGE, - "Username okay, need password. Challenge is ..."}, - {pcpp::FtpResponseLayer::FtpStatusCode::FILE_PENDING_ACTION, - "Requested file action pending further information"}, - {pcpp::FtpResponseLayer::FtpStatusCode::SERVICE_NOT_AVAILABLE, - "Service not available, closing control connection"}, - {pcpp::FtpResponseLayer::FtpStatusCode::CANT_OPEN_DATA_CONNECTION, "Can't open data connection"}, - {pcpp::FtpResponseLayer::FtpStatusCode::CONNECTION_CLOSED, "Connection closed; transfer aborted"}, - {pcpp::FtpResponseLayer::FtpStatusCode::NEED_UNAVAILABLE_RESOURCE_TO_SEC, - "Need some unavailable resource to process security"}, - {pcpp::FtpResponseLayer::FtpStatusCode::REQ_FILE_ACTION_NOT_TAKEN, "Requested file action not taken"}, - {pcpp::FtpResponseLayer::FtpStatusCode::REQ_ACTION_ABORTED, - "Requested action aborted: local error in processing"}, - {pcpp::FtpResponseLayer::FtpStatusCode::REQ_ACTION_NOT_TAKEN, - "Requested action not taken. Insufficient storage space in system"}, - {pcpp::FtpResponseLayer::FtpStatusCode::SYNTAX_ERROR_COMMAND_UNRECOGNIZED, - "Syntax error, command unrecognized"}, - {pcpp::FtpResponseLayer::FtpStatusCode::SYNTAX_ERROR_PARAMETER_OR_ARGUMENT, - "Syntax error in parameters or arguments"}, - {pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_NOT_IMPLEMENTED, "Command not implemented"}, - {pcpp::FtpResponseLayer::FtpStatusCode::BAD_SEQUENCE_COMMANDS, "Bad sequence of commands"}, - {pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_NOT_IMPLEMENTED_FOR_PARAMETER, - "Command not implemented for that parameter"}, - {pcpp::FtpResponseLayer::FtpStatusCode::NETWORK_PROTOCOL_NOT_SUPPORTED, "Network protocol not supported"}, - {pcpp::FtpResponseLayer::FtpStatusCode::NOT_LOGGED_IN, "Not logged in"}, - {pcpp::FtpResponseLayer::FtpStatusCode::NEED_ACCOUNT_FOR_STORE_FILE, "Need account for storing files"}, - {pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_PROTECTION_DENIED, - "Command protection level denied for policy reasons"}, - {pcpp::FtpResponseLayer::FtpStatusCode::REQUEST_DENIED, "Request denied for policy reasons"}, - {pcpp::FtpResponseLayer::FtpStatusCode::FAILED_SEC_CHECK, "Failed security check (hash, sequence, etc)"}, - {pcpp::FtpResponseLayer::FtpStatusCode::REQ_PROT_LEVEL_NOT_SUPPORTED, - "Requested PROT level not supported by mechanism"}, - {pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_PROTECTION_LEVEL_NOT_SUPPORTED, - "Command protection level not supported by security mechanism"}, - {pcpp::FtpResponseLayer::FtpStatusCode::FILE_UNAVAILABLE, "Requested action not taken: File unavailable"}, - {pcpp::FtpResponseLayer::FtpStatusCode::PAGE_TYPE_UNKNOWN, "Requested action aborted: page type unknown"}, - {pcpp::FtpResponseLayer::FtpStatusCode::EXCEED_STORAGE_ALLOCATION, - "Requested file action aborted: Exceeded storage allocation"}, - {pcpp::FtpResponseLayer::FtpStatusCode::FILENAME_NOT_ALLOWED, - "Requested action not taken: File name not allowed"}, - {pcpp::FtpResponseLayer::FtpStatusCode::INTEGRITY_PROTECTED, "Integrity protected reply"}, - {pcpp::FtpResponseLayer::FtpStatusCode::CONFIDENTIALITY_AND_INTEGRITY_PROTECTED, - "Confidentiality and integrity protected reply"}, - {pcpp::FtpResponseLayer::FtpStatusCode::CONFIDENTIALITY_PROTECTED, "Confidentiality protected reply"}}; - - for (const auto &entry : possibleStatusCodes) + { static_cast(0), "Unknown Status Code" }, + { pcpp::FtpResponseLayer::FtpStatusCode::RESTART_MARKER, "Restart marker reply" }, + { pcpp::FtpResponseLayer::FtpStatusCode::SERVICE_READY_IN_MIN, "Service ready in nnn minutes" }, + { pcpp::FtpResponseLayer::FtpStatusCode::DATA_ALREADY_OPEN_START_TRANSFER, + "Data connection already open; transfer starting" }, + { pcpp::FtpResponseLayer::FtpStatusCode::FILE_OK, "File status okay; about to open data connection" }, + { pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_OK, "Command okay" }, + { pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_NOT_IMPLEMENTED_SUPERFLUOUS, + "Command not implemented, superfluous at this site" }, + { pcpp::FtpResponseLayer::FtpStatusCode::SYSTEM_STATUS, "System status, or system help reply" }, + { pcpp::FtpResponseLayer::FtpStatusCode::DIR_STATUS, "Directory status" }, + { pcpp::FtpResponseLayer::FtpStatusCode::FILE_STATUS, "File status" }, + { pcpp::FtpResponseLayer::FtpStatusCode::HELP_MESSAGE, "Help message" }, + { pcpp::FtpResponseLayer::FtpStatusCode::NAME_SYSTEM_TYPE, "NAME system type" }, + { pcpp::FtpResponseLayer::FtpStatusCode::SERVICE_READY_FOR_USER, "Service ready for new user" }, + { pcpp::FtpResponseLayer::FtpStatusCode::SERVICE_CLOSING_CONTROL, "Service closing control connection" }, + { pcpp::FtpResponseLayer::FtpStatusCode::DATA_OPEN_NO_TRANSFER, + "Data connection open; no transfer in progress" }, + { pcpp::FtpResponseLayer::FtpStatusCode::CLOSING_DATA, "Closing data connection" }, + { pcpp::FtpResponseLayer::FtpStatusCode::ENTERING_PASSIVE, "Entering Passive Mode" }, + { pcpp::FtpResponseLayer::FtpStatusCode::ENTERING_EXTENDED_PASSIVE, "Entering Extended Passive Mode" }, + { pcpp::FtpResponseLayer::FtpStatusCode::USER_LOG_IN_PROCEED, "User logged in, proceed" }, + { pcpp::FtpResponseLayer::FtpStatusCode::USER_LOG_IN_AUTHORIZED, + "User logged in, authorized by security data exchange" }, + { pcpp::FtpResponseLayer::FtpStatusCode::SEC_DATA_EXCHANGE_COMPLETE, "Security data exchange complete" }, + { pcpp::FtpResponseLayer::FtpStatusCode::SEC_DATA_EXCHANGE_COMPLETE_SUCCESS, + "Security data exchange completed successfully" }, + { pcpp::FtpResponseLayer::FtpStatusCode::REQ_FILE_OK_COMPLETE, "Requested file action okay, completed" }, + { pcpp::FtpResponseLayer::FtpStatusCode::PATHNAME_CREATED, "PATHNAME created" }, + { pcpp::FtpResponseLayer::FtpStatusCode::USER_OK_NEED_PASSWORD, "User name okay, need password" }, + { pcpp::FtpResponseLayer::FtpStatusCode::NEED_ACCOUNT, "Need account for login" }, + { pcpp::FtpResponseLayer::FtpStatusCode::REQ_SEC_MECHANISM_OK, "Requested security mechanism is ok" }, + { pcpp::FtpResponseLayer::FtpStatusCode::SEC_IS_ACCEPTABLE, "Security data is acceptable, more is required" }, + { pcpp::FtpResponseLayer::FtpStatusCode::USER_OK_NEED_PASS_CHALLENGE, + "Username okay, need password. Challenge is ..." }, + { pcpp::FtpResponseLayer::FtpStatusCode::FILE_PENDING_ACTION, + "Requested file action pending further information" }, + { pcpp::FtpResponseLayer::FtpStatusCode::SERVICE_NOT_AVAILABLE, + "Service not available, closing control connection" }, + { pcpp::FtpResponseLayer::FtpStatusCode::CANT_OPEN_DATA_CONNECTION, "Can't open data connection" }, + { pcpp::FtpResponseLayer::FtpStatusCode::CONNECTION_CLOSED, "Connection closed; transfer aborted" }, + { pcpp::FtpResponseLayer::FtpStatusCode::NEED_UNAVAILABLE_RESOURCE_TO_SEC, + "Need some unavailable resource to process security" }, + { pcpp::FtpResponseLayer::FtpStatusCode::REQ_FILE_ACTION_NOT_TAKEN, "Requested file action not taken" }, + { pcpp::FtpResponseLayer::FtpStatusCode::REQ_ACTION_ABORTED, + "Requested action aborted: local error in processing" }, + { pcpp::FtpResponseLayer::FtpStatusCode::REQ_ACTION_NOT_TAKEN, + "Requested action not taken. Insufficient storage space in system" }, + { pcpp::FtpResponseLayer::FtpStatusCode::SYNTAX_ERROR_COMMAND_UNRECOGNIZED, + "Syntax error, command unrecognized" }, + { pcpp::FtpResponseLayer::FtpStatusCode::SYNTAX_ERROR_PARAMETER_OR_ARGUMENT, + "Syntax error in parameters or arguments" }, + { pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_NOT_IMPLEMENTED, "Command not implemented" }, + { pcpp::FtpResponseLayer::FtpStatusCode::BAD_SEQUENCE_COMMANDS, "Bad sequence of commands" }, + { pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_NOT_IMPLEMENTED_FOR_PARAMETER, + "Command not implemented for that parameter" }, + { pcpp::FtpResponseLayer::FtpStatusCode::NETWORK_PROTOCOL_NOT_SUPPORTED, "Network protocol not supported" }, + { pcpp::FtpResponseLayer::FtpStatusCode::NOT_LOGGED_IN, "Not logged in" }, + { pcpp::FtpResponseLayer::FtpStatusCode::NEED_ACCOUNT_FOR_STORE_FILE, "Need account for storing files" }, + { pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_PROTECTION_DENIED, + "Command protection level denied for policy reasons" }, + { pcpp::FtpResponseLayer::FtpStatusCode::REQUEST_DENIED, "Request denied for policy reasons" }, + { pcpp::FtpResponseLayer::FtpStatusCode::FAILED_SEC_CHECK, "Failed security check (hash, sequence, etc)" }, + { pcpp::FtpResponseLayer::FtpStatusCode::REQ_PROT_LEVEL_NOT_SUPPORTED, + "Requested PROT level not supported by mechanism" }, + { pcpp::FtpResponseLayer::FtpStatusCode::COMMAND_PROTECTION_LEVEL_NOT_SUPPORTED, + "Command protection level not supported by security mechanism" }, + { pcpp::FtpResponseLayer::FtpStatusCode::FILE_UNAVAILABLE, "Requested action not taken: File unavailable" }, + { pcpp::FtpResponseLayer::FtpStatusCode::PAGE_TYPE_UNKNOWN, "Requested action aborted: page type unknown" }, + { pcpp::FtpResponseLayer::FtpStatusCode::EXCEED_STORAGE_ALLOCATION, + "Requested file action aborted: Exceeded storage allocation" }, + { pcpp::FtpResponseLayer::FtpStatusCode::FILENAME_NOT_ALLOWED, + "Requested action not taken: File name not allowed" }, + { pcpp::FtpResponseLayer::FtpStatusCode::INTEGRITY_PROTECTED, "Integrity protected reply" }, + { pcpp::FtpResponseLayer::FtpStatusCode::CONFIDENTIALITY_AND_INTEGRITY_PROTECTED, + "Confidentiality and integrity protected reply" }, + { pcpp::FtpResponseLayer::FtpStatusCode::CONFIDENTIALITY_PROTECTED, "Confidentiality protected reply" } + }; + + for (const auto& entry : possibleStatusCodes) { PTF_ASSERT_EQUAL(pcpp::FtpResponseLayer::getStatusCodeAsString(entry.first), entry.second); } @@ -318,12 +323,12 @@ PTF_TEST_CASE(FtpEditTests) // Modify existing request packets READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ftpIpv4Req.dat"); pcpp::Packet ftpPacket1(&rawPacket1); - pcpp::FtpRequestLayer *ftpLayer1 = ftpPacket1.getLayerOfType(); + pcpp::FtpRequestLayer* ftpLayer1 = ftpPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpLayer1); READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/ftpReqEdited1.dat"); pcpp::Packet ftpReqEdited1(&rawPacket2); - pcpp::FtpRequestLayer *ftpReqEditedLayer1 = ftpReqEdited1.getLayerOfType(); + pcpp::FtpRequestLayer* ftpReqEditedLayer1 = ftpReqEdited1.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpReqEditedLayer1); ftpLayer1->setCommand(pcpp::FtpRequestLayer::FtpCommand::FEAT); @@ -332,7 +337,7 @@ PTF_TEST_CASE(FtpEditTests) READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/ftpReqEdited2.dat"); pcpp::Packet ftpReqEdited2(&rawPacket3); - pcpp::FtpRequestLayer *ftpReqEditedLayer2 = ftpReqEdited2.getLayerOfType(); + pcpp::FtpRequestLayer* ftpReqEditedLayer2 = ftpReqEdited2.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpReqEditedLayer2); ftpLayer1->setCommandOption("Test option"); @@ -342,12 +347,12 @@ PTF_TEST_CASE(FtpEditTests) // Modify existing response packets READ_FILE_AND_CREATE_PACKET(4, "PacketExamples/ftpIpv4Resp.dat"); pcpp::Packet ftpPacket2(&rawPacket4); - pcpp::FtpResponseLayer *ftpLayer2 = ftpPacket2.getLayerOfType(); + pcpp::FtpResponseLayer* ftpLayer2 = ftpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpLayer2); READ_FILE_AND_CREATE_PACKET(5, "PacketExamples/ftpRespEdited1.dat"); pcpp::Packet ftpRespEdited1(&rawPacket5); - pcpp::FtpResponseLayer *ftpRespEditedLayer1 = ftpRespEdited1.getLayerOfType(); + pcpp::FtpResponseLayer* ftpRespEditedLayer1 = ftpRespEdited1.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpRespEditedLayer1); ftpLayer2->setStatusCode(pcpp::FtpResponseLayer::FtpStatusCode::CLOSING_DATA); @@ -356,7 +361,7 @@ PTF_TEST_CASE(FtpEditTests) READ_FILE_AND_CREATE_PACKET(6, "PacketExamples/ftpRespEdited2.dat"); pcpp::Packet ftpRespEdited2(&rawPacket6); - pcpp::FtpResponseLayer *ftpRespEditedLayer2 = ftpRespEdited2.getLayerOfType(); + pcpp::FtpResponseLayer* ftpRespEditedLayer2 = ftpRespEdited2.getLayerOfType(); PTF_ASSERT_NOT_NULL(ftpRespEditedLayer2); ftpLayer2->setStatusOption("Test option"); diff --git a/Tests/Packet++Test/Tests/GreTests.cpp b/Tests/Packet++Test/Tests/GreTests.cpp index e359fe74ea..9c587f38c8 100644 --- a/Tests/Packet++Test/Tests/GreTests.cpp +++ b/Tests/Packet++Test/Tests/GreTests.cpp @@ -12,7 +12,6 @@ #include "Packet.h" #include "SystemUtils.h" - PTF_TEST_CASE(GreParsingTest) { timeval time; @@ -155,9 +154,7 @@ PTF_TEST_CASE(GreParsingTest) PTF_ASSERT_EQUAL(tcpLayer->getSrcPort(), 1232); grev0Layer = nullptr; tcpLayer = nullptr; -} // GreParsingTest - - +} // GreParsingTest PTF_TEST_CASE(GreCreationTest) { @@ -194,7 +191,6 @@ PTF_TEST_CASE(GreCreationTest) PTF_ASSERT_EQUAL(grev1Packet.getRawPacket()->getRawDataLen(), bufferLength1); PTF_ASSERT_BUF_COMPARE(grev1Packet.getRawPacket()->getRawData(), buffer1, bufferLength1); - // GREv0 packet creation pcpp::EthLayer ethLayer2(pcpp::MacAddress("00:01:01:00:00:01"), pcpp::MacAddress("00:01:01:00:00:02")); @@ -218,15 +214,12 @@ PTF_TEST_CASE(GreCreationTest) PTF_ASSERT_TRUE(grev0Packet.addLayer(&grev0Layer2)); grev0Packet.computeCalculateFields(); - PTF_ASSERT_EQUAL(grev0Packet.getRawPacket()->getRawDataLen(), bufferLength2); PTF_ASSERT_BUF_COMPARE(grev0Packet.getRawPacket()->getRawData(), buffer2, bufferLength2); - delete [] buffer1; - delete [] buffer2; -} // GreCreationTest - - + delete[] buffer1; + delete[] buffer2; +} // GreCreationTest PTF_TEST_CASE(GreEditTest) { @@ -246,7 +239,6 @@ PTF_TEST_CASE(GreEditTest) PTF_ASSERT_TRUE(grev0Layer->setKey(2341)); grev0Packet.computeCalculateFields(); - uint16_t value16 = 0; uint32_t value32 = 0; grev0Layer = grev0Packet.getLayerOfType(); @@ -328,7 +320,6 @@ PTF_TEST_CASE(GreEditTest) PTF_ASSERT_TRUE(grev0Layer->getChecksum(value16)); PTF_ASSERT_EQUAL(value16, 30719); - // GREv1 packet edit READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/GREv1_2.dat"); @@ -399,11 +390,12 @@ PTF_TEST_CASE(GreEditTest) PTF_ASSERT_EQUAL(pppLayer->getPPP_PPTPHeader()->protocol, 0); - auto ipv6Layer = new pcpp::IPv6Layer(pcpp::IPv6Address("2402:f000:1:8e01::5555"), pcpp::IPv6Address("2607:fcd0:100:2300::b108:2a6b")); + auto ipv6Layer = new pcpp::IPv6Layer(pcpp::IPv6Address("2402:f000:1:8e01::5555"), + pcpp::IPv6Address("2607:fcd0:100:2300::b108:2a6b")); PTF_ASSERT_TRUE(grev1Packet.addLayer(ipv6Layer, true)); grev1Packet.computeCalculateFields(); PTF_ASSERT_NOT_NULL(pppLayer->getNextLayer()); PTF_ASSERT_EQUAL(pppLayer->getNextLayer()->getProtocol(), pcpp::IPv6, enum); PTF_ASSERT_EQUAL(pppLayer->getPPP_PPTPHeader()->protocol, htobe16(PCPP_PPP_IPV6)); -} // GreEditTest +} // GreEditTest diff --git a/Tests/Packet++Test/Tests/GtpTests.cpp b/Tests/Packet++Test/Tests/GtpTests.cpp index e5cf2352d0..b782c65e10 100644 --- a/Tests/Packet++Test/Tests/GtpTests.cpp +++ b/Tests/Packet++Test/Tests/GtpTests.cpp @@ -10,7 +10,6 @@ #include "IcmpLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(GtpLayerParsingTest) { timeval time; @@ -26,7 +25,6 @@ PTF_TEST_CASE(GtpLayerParsingTest) pcpp::Packet gtpPacket3(&rawPacket3); pcpp::Packet gtpPacket4(&rawPacket4); - // GTP-U packet 1 PTF_ASSERT_TRUE(gtpPacket1.isPacketOfType(pcpp::GTPv1)); PTF_ASSERT_TRUE(gtpPacket1.isPacketOfType(pcpp::GTP)); @@ -65,8 +63,6 @@ PTF_TEST_CASE(GtpLayerParsingTest) PTF_ASSERT_FALSE(gtpLayer->isGTPCMessage()); PTF_ASSERT_TRUE(gtpLayer->isGTPUMessage()); - - // GTP-U packet 2 (with GTP header extension) gtpLayer = gtpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(gtpLayer); @@ -108,8 +104,6 @@ PTF_TEST_CASE(GtpLayerParsingTest) PTF_ASSERT_FALSE(gtpLayer->isGTPCMessage()); PTF_ASSERT_TRUE(gtpLayer->isGTPUMessage()); - - // GTP-U IPv6 packet gtpLayer = gtpPacket4.getLayerOfType(); PTF_ASSERT_NOT_NULL(gtpLayer); @@ -137,8 +131,6 @@ PTF_TEST_CASE(GtpLayerParsingTest) PTF_ASSERT_FALSE(gtpLayer->isGTPCMessage()); PTF_ASSERT_TRUE(gtpLayer->isGTPUMessage()); - - // GTP-C packet PTF_ASSERT_TRUE(gtpPacket3.isPacketOfType(pcpp::GTP)); PTF_ASSERT_TRUE(gtpPacket3.isPacketOfType(pcpp::GTPv1)); @@ -167,9 +159,7 @@ PTF_TEST_CASE(GtpLayerParsingTest) PTF_ASSERT_TRUE(gtpLayer->isGTPCMessage()); PTF_ASSERT_FALSE(gtpLayer->isGTPUMessage()); -} // GtpLayerParsingTest - - +} // GtpLayerParsingTest PTF_TEST_CASE(GtpLayerCreationTest) { @@ -186,7 +176,8 @@ PTF_TEST_CASE(GtpLayerCreationTest) pcpp::IPv4Layer ip4Layer(*gtpPacket1.getLayerOfType()); pcpp::UdpLayer udpLayer(*gtpPacket1.getLayerOfType()); pcpp::GtpV1Layer gtpLayer(pcpp::GtpV1_GPDU, 1, true, 10461, false, 0); - pcpp::IPv4Layer ip4Layer2(*gtpPacket1.getNextLayerOfType(gtpPacket1.getLayerOfType())); + pcpp::IPv4Layer ip4Layer2( + *gtpPacket1.getNextLayerOfType(gtpPacket1.getLayerOfType())); pcpp::IcmpLayer icmpLayer(*gtpPacket1.getLayerOfType()); pcpp::Packet newGtpPacket; @@ -199,15 +190,16 @@ PTF_TEST_CASE(GtpLayerCreationTest) newGtpPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(bufferLength1, newGtpPacket.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(newGtpPacket.getRawPacket()->getRawData(), buffer1, newGtpPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(newGtpPacket.getRawPacket()->getRawData(), buffer1, + newGtpPacket.getRawPacket()->getRawDataLen()); pcpp::GtpV1Layer* newGtpLayer = newGtpPacket.getLayerOfType(); pcpp::GtpV1Layer::GtpExtension newExt1 = newGtpLayer->addExtension(0xc0, 2308); PTF_ASSERT_FALSE(newExt1.isNull()); PTF_ASSERT_EQUAL(newExt1.getExtensionType(), 0xc0); - PTF_ASSERT_EQUAL(newExt1.getTotalLength(), 4*sizeof(uint8_t)); - PTF_ASSERT_EQUAL(newExt1.getContentLength(), 2*sizeof(uint8_t)); + PTF_ASSERT_EQUAL(newExt1.getTotalLength(), 4 * sizeof(uint8_t)); + PTF_ASSERT_EQUAL(newExt1.getContentLength(), 2 * sizeof(uint8_t)); uint16_t* content = reinterpret_cast(newExt1.getContent()); PTF_ASSERT_EQUAL(be16toh(content[0]), 2308); PTF_ASSERT_TRUE(newExt1.getNextExtension().isNull()); @@ -215,13 +207,14 @@ PTF_TEST_CASE(GtpLayerCreationTest) newGtpPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(bufferLength2, newGtpPacket.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(newGtpPacket.getRawPacket()->getRawData(), buffer2, newGtpPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(newGtpPacket.getRawPacket()->getRawData(), buffer2, + newGtpPacket.getRawPacket()->getRawDataLen()); pcpp::GtpV1Layer::GtpExtension newExt2 = newGtpLayer->addExtension(0x40, 1308); PTF_ASSERT_FALSE(newExt2.isNull()); PTF_ASSERT_EQUAL(newExt2.getExtensionType(), 0x40); - PTF_ASSERT_EQUAL(newExt2.getTotalLength(), 4*sizeof(uint8_t)); - PTF_ASSERT_EQUAL(newExt2.getContentLength(), 2*sizeof(uint8_t)); + PTF_ASSERT_EQUAL(newExt2.getTotalLength(), 4 * sizeof(uint8_t)); + PTF_ASSERT_EQUAL(newExt2.getContentLength(), 2 * sizeof(uint8_t)); content = reinterpret_cast(newExt2.getContent()); PTF_ASSERT_EQUAL(be16toh(content[0]), 1308); PTF_ASSERT_TRUE(newExt2.getNextExtension().isNull()); @@ -233,10 +226,9 @@ PTF_TEST_CASE(GtpLayerCreationTest) PTF_ASSERT_EQUAL(newGtpLayer->getNextExtension().getNextExtensionHeaderType(), 0x40); PTF_ASSERT_EQUAL(bufferLength3, newGtpPacket.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(newGtpPacket.getRawPacket()->getRawData(), buffer3, newGtpPacket.getRawPacket()->getRawDataLen()); -} // GtpLayerCreationTest - - + PTF_ASSERT_BUF_COMPARE(newGtpPacket.getRawPacket()->getRawData(), buffer3, + newGtpPacket.getRawPacket()->getRawDataLen()); +} // GtpLayerCreationTest PTF_TEST_CASE(GtpLayerEditTest) { @@ -285,7 +277,8 @@ PTF_TEST_CASE(GtpLayerEditTest) gtpPacket1.computeCalculateFields(); PTF_ASSERT_EQUAL(bufferLength2, gtpPacket1.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(gtpPacket1.getRawPacket()->getRawData(), buffer2, gtpPacket1.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(gtpPacket1.getRawPacket()->getRawData(), buffer2, + gtpPacket1.getRawPacket()->getRawDataLen()); - delete [] buffer2; -} // GtpLayerEditTest + delete[] buffer2; +} // GtpLayerEditTest diff --git a/Tests/Packet++Test/Tests/HttpTests.cpp b/Tests/Packet++Test/Tests/HttpTests.cpp index 63897c410d..299a03d51f 100644 --- a/Tests/Packet++Test/Tests/HttpTests.cpp +++ b/Tests/Packet++Test/Tests/HttpTests.cpp @@ -12,33 +12,36 @@ #include PTF_TEST_CASE(HttpRequestParseMethodTest) { - PTF_ASSERT_EQUAL(pcpp::HttpRequestFirstLine::parseMethod(nullptr, 0), pcpp::HttpRequestLayer::HttpMethod::HttpMethodUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpRequestFirstLine::parseMethod(std::string("GET").c_str(), 3), pcpp::HttpRequestLayer::HttpMethod::HttpMethodUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::HttpRequestFirstLine::parseMethod(nullptr, 0), + pcpp::HttpRequestLayer::HttpMethod::HttpMethodUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::HttpRequestFirstLine::parseMethod(std::string("GET").c_str(), 3), + pcpp::HttpRequestLayer::HttpMethod::HttpMethodUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpRequestFirstLine::parseMethod(std::string("OPTIONS").c_str(), 7), pcpp::HttpRequestLayer::HttpMethod::HttpMethodUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::HttpRequestFirstLine::parseMethod(std::string("OPTIONS").c_str(), 7), + pcpp::HttpRequestLayer::HttpMethod::HttpMethodUnknown, enum); std::vector> possibleMethods = { - {"GET", pcpp::HttpRequestLayer::HttpMethod::HttpGET }, - {"HEAD", pcpp::HttpRequestLayer::HttpMethod::HttpHEAD }, - {"POST", pcpp::HttpRequestLayer::HttpMethod::HttpPOST }, - {"PUT", pcpp::HttpRequestLayer::HttpMethod::HttpPUT }, - {"DELETE", pcpp::HttpRequestLayer::HttpMethod::HttpDELETE }, - {"TRACE", pcpp::HttpRequestLayer::HttpMethod::HttpTRACE }, - {"OPTIONS", pcpp::HttpRequestLayer::HttpMethod::HttpOPTIONS }, - {"CONNECT", pcpp::HttpRequestLayer::HttpMethod::HttpCONNECT }, - {"PATCH", pcpp::HttpRequestLayer::HttpMethod::HttpPATCH } + { "GET", pcpp::HttpRequestLayer::HttpMethod::HttpGET }, + { "HEAD", pcpp::HttpRequestLayer::HttpMethod::HttpHEAD }, + { "POST", pcpp::HttpRequestLayer::HttpMethod::HttpPOST }, + { "PUT", pcpp::HttpRequestLayer::HttpMethod::HttpPUT }, + { "DELETE", pcpp::HttpRequestLayer::HttpMethod::HttpDELETE }, + { "TRACE", pcpp::HttpRequestLayer::HttpMethod::HttpTRACE }, + { "OPTIONS", pcpp::HttpRequestLayer::HttpMethod::HttpOPTIONS }, + { "CONNECT", pcpp::HttpRequestLayer::HttpMethod::HttpCONNECT }, + { "PATCH", pcpp::HttpRequestLayer::HttpMethod::HttpPATCH } }; - for (const std::pair &method : possibleMethods ) + for (const std::pair& method : possibleMethods) { std::string firstLine = method.first + " "; - PTF_ASSERT_EQUAL(pcpp::HttpRequestFirstLine::parseMethod(firstLine.c_str(), firstLine.length()), method.second, enum); + PTF_ASSERT_EQUAL(pcpp::HttpRequestFirstLine::parseMethod(firstLine.c_str(), firstLine.length()), method.second, + enum); } - PTF_ASSERT_EQUAL(pcpp::HttpRequestFirstLine::parseMethod(std::string("UNKNOWN ").c_str(), 8), pcpp::HttpRequestLayer::HttpMethod::HttpMethodUnknown, enum); -} // HttpRequestParseMethodTest - - + PTF_ASSERT_EQUAL(pcpp::HttpRequestFirstLine::parseMethod(std::string("UNKNOWN ").c_str(), 8), + pcpp::HttpRequestLayer::HttpMethod::HttpMethodUnknown, enum); +} // HttpRequestParseMethodTest PTF_TEST_CASE(HttpRequestLayerParsingTest) { @@ -67,7 +70,6 @@ PTF_TEST_CASE(HttpRequestLayerParsingTest) PTF_ASSERT_EQUAL(requestLayer->getUrl(), "www.ynet.co.il/home/0,7340,L-8,00.html"); - READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/PartialHttpRequest.dat"); pcpp::Packet httpPacket2(&rawPacket2); @@ -92,9 +94,7 @@ PTF_TEST_CASE(HttpRequestLayerParsingTest) PTF_ASSERT_EQUAL(requestLayer->getFieldCount(), 8); PTF_ASSERT_FALSE(requestLayer->isHeaderComplete()); -} // HttpRequestLayerParsingTest - - +} // HttpRequestLayerParsingTest PTF_TEST_CASE(HttpRequestLayerCreationTest) { @@ -111,12 +111,15 @@ PTF_TEST_CASE(HttpRequestLayerCreationTest) pcpp::TcpLayer tcpLayer = *(sampleHttpPacket.getLayerOfType()); pcpp::HttpRequestLayer httpLayer(pcpp::HttpRequestLayer::HttpOPTIONS, "/home/0,7340,L-8,00", pcpp::OneDotOne); - PTF_ASSERT_NOT_NULL(httpLayer.addField(PCPP_HTTP_ACCEPT_FIELD, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")); + PTF_ASSERT_NOT_NULL(httpLayer.addField( + PCPP_HTTP_ACCEPT_FIELD, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")); PTF_ASSERT_NOT_NULL(httpLayer.addField("Dummy-Field", "some value")); pcpp::HeaderField* hostField = httpLayer.insertField(nullptr, PCPP_HTTP_HOST_FIELD, "www.ynet-ynet.co.il"); PTF_ASSERT_NOT_NULL(hostField); PTF_ASSERT_NOT_NULL(httpLayer.insertField(hostField, PCPP_HTTP_CONNECTION_FIELD, "keep-alive")); - pcpp::HeaderField* userAgentField = httpLayer.addField(PCPP_HTTP_USER_AGENT_FIELD, "(Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36"); + pcpp::HeaderField* userAgentField = httpLayer.addField( + PCPP_HTTP_USER_AGENT_FIELD, + "(Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36"); httpLayer.getFirstLine()->setUri("bla.php"); PTF_ASSERT_NOT_NULL(userAgentField); PTF_ASSERT_NOT_NULL(httpLayer.addField(PCPP_HTTP_ACCEPT_LANGUAGE_FIELD, "en-US,en;q=0.8")); @@ -145,16 +148,15 @@ PTF_TEST_CASE(HttpRequestLayerCreationTest) PTF_ASSERT_EQUAL(httpLayer.getFirstLine()->getVersion(), pcpp::OneDotOne, enum); httpLayer.getFirstLine()->setUri("/home/0,7340,L-8,00.html"); PTF_ASSERT_TRUE(httpLayer.removeField("Dummy-Field2")); - userAgentField->setFieldValue("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36"); + userAgentField->setFieldValue( + "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36"); httpPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(bufferLength1, httpPacket.getRawPacket()->getRawDataLen()); PTF_ASSERT_BUF_COMPARE(buffer1, httpPacket.getRawPacket()->getRawData(), bufferLength1); -} // HttpRequestLayerCreationTest - - +} // HttpRequestLayerCreationTest PTF_TEST_CASE(HttpRequestLayerEditTest) { @@ -175,7 +177,8 @@ PTF_TEST_CASE(HttpRequestLayerEditTest) tcpLayer->getTcpHeader()->windowSize = htobe16(16660); pcpp::HttpRequestLayer* httpReqLayer = httpRequest.getLayerOfType(); - PTF_ASSERT_TRUE(httpReqLayer->getFirstLine()->setUri("/Common/Api/Video/CmmLightboxPlayerJs/0,14153,061014181713,00.js")); + PTF_ASSERT_TRUE( + httpReqLayer->getFirstLine()->setUri("/Common/Api/Video/CmmLightboxPlayerJs/0,14153,061014181713,00.js")); pcpp::HeaderField* acceptField = httpReqLayer->getFieldByName(PCPP_HTTP_ACCEPT_FIELD); PTF_ASSERT_NOT_NULL(acceptField); acceptField->setFieldValue("*/*"); @@ -191,16 +194,16 @@ PTF_TEST_CASE(HttpRequestLayerEditTest) PTF_ASSERT_BUF_COMPARE(buffer2, httpRequest.getRawPacket()->getRawData(), bufferLength2); - delete [] buffer2; - -} // HttpRequestLayerEditTest - + delete[] buffer2; +} // HttpRequestLayerEditTest PTF_TEST_CASE(HttpResponseParseStatusCodeTest) { - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(nullptr, 0), pcpp::HttpResponseLayer::HttpResponseStatusCode::HttpStatusCodeUnknown); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("abc").c_str(), 3), pcpp::HttpResponseLayer::HttpResponseStatusCode::HttpStatusCodeUnknown); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(nullptr, 0), + pcpp::HttpResponseLayer::HttpResponseStatusCode::HttpStatusCodeUnknown); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("abc").c_str(), 3), + pcpp::HttpResponseLayer::HttpResponseStatusCode::HttpStatusCodeUnknown); std::vector possibleStatusCodes = { pcpp::HttpResponseStatusCode::Http100Continue, @@ -288,71 +291,98 @@ PTF_TEST_CASE(HttpResponseParseStatusCodeTest) pcpp::HttpResponseStatusCode::Http599NetworkConnectTimeoutError, }; - for (const auto &statusCode : possibleStatusCodes ) + for (const auto& statusCode : possibleStatusCodes) { std::string firstLine = "HTTP/x.y " + statusCode.toString() + " " + statusCode.getMessage() + "\n"; - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(firstLine.c_str(), firstLine.length()), statusCode, enum); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(firstLine.c_str(), firstLine.length()), + statusCode, enum); } - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 001 any message\n").c_str(), 26), pcpp::HttpResponseStatusCode::HttpStatusCodeUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 199 any message\n").c_str(), 26), pcpp::HttpResponseStatusCode::HttpStatus1xxCodeUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 299 any message\n").c_str(), 26), pcpp::HttpResponseStatusCode::HttpStatus2xxCodeUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 399 any message\n").c_str(), 26), pcpp::HttpResponseStatusCode::HttpStatus3xxCodeUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 477 any message\n").c_str(), 26), pcpp::HttpResponseStatusCode::HttpStatus4xxCodeUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 577 any message\n").c_str(), 26), pcpp::HttpResponseStatusCode::HttpStatus5xxCodeUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 600 any message\n").c_str(), 26), pcpp::HttpResponseStatusCode::HttpStatusCodeUnknown, enum); - + PTF_ASSERT_EQUAL( + pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 001 any message\n").c_str(), 26), + pcpp::HttpResponseStatusCode::HttpStatusCodeUnknown, enum); + PTF_ASSERT_EQUAL( + pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 199 any message\n").c_str(), 26), + pcpp::HttpResponseStatusCode::HttpStatus1xxCodeUnknown, enum); + PTF_ASSERT_EQUAL( + pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 299 any message\n").c_str(), 26), + pcpp::HttpResponseStatusCode::HttpStatus2xxCodeUnknown, enum); + PTF_ASSERT_EQUAL( + pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 399 any message\n").c_str(), 26), + pcpp::HttpResponseStatusCode::HttpStatus3xxCodeUnknown, enum); + PTF_ASSERT_EQUAL( + pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 477 any message\n").c_str(), 26), + pcpp::HttpResponseStatusCode::HttpStatus4xxCodeUnknown, enum); + PTF_ASSERT_EQUAL( + pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 577 any message\n").c_str(), 26), + pcpp::HttpResponseStatusCode::HttpStatus5xxCodeUnknown, enum); + PTF_ASSERT_EQUAL( + pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 600 any message\n").c_str(), 26), + pcpp::HttpResponseStatusCode::HttpStatusCodeUnknown, enum); // test getMessage() - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 200 OK\n").c_str(), 17).getMessage(), "OK"); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 404 Not Found\n").c_str(), 24).getMessage(), "Not Found"); + PTF_ASSERT_EQUAL( + pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 200 OK\n").c_str(), 17).getMessage(), "OK"); + PTF_ASSERT_EQUAL( + pcpp::HttpResponseFirstLine::parseStatusCode(std::string("HTTP/x.y 404 Not Found\n").c_str(), 24).getMessage(), + "Not Found"); std::string testLine; testLine = "HTTP/x.y 404 My Not Found\r\n"; - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(testLine.c_str(), testLine.size()).getMessage(), "My Not Found"); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(testLine.c_str(), testLine.size()).getMessage(), + "My Not Found"); testLine = "HTTP/x.y 404 My Not Found 2\n"; - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(testLine.c_str(), testLine.size()).getMessage(), "My Not Found 2"); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(testLine.c_str(), testLine.size()).getMessage(), + "My Not Found 2"); testLine = "HTTP/x.y 404 Unfinished Line Here"; - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(testLine.c_str(), testLine.size()), pcpp::HttpResponseStatusCode::HttpStatusCodeUnknown); - - testLine = "HTTP/x.y 404\n"; // no status message - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(testLine.c_str(), testLine.size()), pcpp::HttpResponseStatusCode::HttpStatusCodeUnknown); - - testLine = "HTTP/x.y 404 \n"; // no status message - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(testLine.c_str(), testLine.size()), pcpp::HttpResponseStatusCode::HttpStatusCodeUnknown); -} // HttpResponseParseStatusCodeTest + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(testLine.c_str(), testLine.size()), + pcpp::HttpResponseStatusCode::HttpStatusCodeUnknown); + testLine = "HTTP/x.y 404\n"; // no status message + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(testLine.c_str(), testLine.size()), + pcpp::HttpResponseStatusCode::HttpStatusCodeUnknown); + testLine = "HTTP/x.y 404 \n"; // no status message + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseStatusCode(testLine.c_str(), testLine.size()), + pcpp::HttpResponseStatusCode::HttpStatusCodeUnknown); +} // HttpResponseParseStatusCodeTest PTF_TEST_CASE(HttpResponseParseVersionTest) { - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(nullptr, 0), pcpp::HttpVersion::HttpVersionUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("1.1").c_str(), 3), pcpp::HttpVersion::HttpVersionUnknown, enum); - - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("XTTP/1.1").c_str(), 8), pcpp::HttpVersion::HttpVersionUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("HXTP/1.1").c_str(), 8), pcpp::HttpVersion::HttpVersionUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("HTXP/1.1").c_str(), 8), pcpp::HttpVersion::HttpVersionUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("HTTX/1.1").c_str(), 8), pcpp::HttpVersion::HttpVersionUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("HTTP 1.1").c_str(), 8), pcpp::HttpVersion::HttpVersionUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(nullptr, 0), pcpp::HttpVersion::HttpVersionUnknown, + enum); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("1.1").c_str(), 3), + pcpp::HttpVersion::HttpVersionUnknown, enum); + + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("XTTP/1.1").c_str(), 8), + pcpp::HttpVersion::HttpVersionUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("HXTP/1.1").c_str(), 8), + pcpp::HttpVersion::HttpVersionUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("HTXP/1.1").c_str(), 8), + pcpp::HttpVersion::HttpVersionUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("HTTX/1.1").c_str(), 8), + pcpp::HttpVersion::HttpVersionUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("HTTP 1.1").c_str(), 8), + pcpp::HttpVersion::HttpVersionUnknown, enum); std::vector> possibleVersions = { { "0.9", pcpp::HttpVersion::ZeroDotNine }, - { "1.0", pcpp::HttpVersion::OneDotZero }, - { "1.1", pcpp::HttpVersion::OneDotOne } + { "1.0", pcpp::HttpVersion::OneDotZero }, + { "1.1", pcpp::HttpVersion::OneDotOne } }; - for (const std::pair &version : possibleVersions ) + for (const std::pair& version : possibleVersions) { std::string firstLine = "HTTP/" + version.first; - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(firstLine.c_str(), firstLine.length()), version.second, enum); + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(firstLine.c_str(), firstLine.length()), + version.second, enum); } - PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("HTTP/2.0 ").c_str(), 8), pcpp::HttpVersion::HttpVersionUnknown, enum); -} // HttpResponseParseVersionTest - - + PTF_ASSERT_EQUAL(pcpp::HttpResponseFirstLine::parseVersion(std::string("HTTP/2.0 ").c_str(), 8), + pcpp::HttpVersion::HttpVersionUnknown, enum); +} // HttpResponseParseVersionTest PTF_TEST_CASE(HttpResponseLayerParsingTest) { @@ -382,9 +412,7 @@ PTF_TEST_CASE(HttpResponseLayerParsingTest) pcpp::HeaderField* contentTypeField = responseLayer->getFieldByName(PCPP_HTTP_CONTENT_TYPE_FIELD); PTF_ASSERT_NOT_NULL(contentTypeField); PTF_ASSERT_EQUAL(contentTypeField->getFieldValue(), "application/x-javascript"); -} // HttpResponseLayerParsingTest - - +} // HttpResponseLayerParsingTest PTF_TEST_CASE(HttpResponseLayerCreationTest) { @@ -405,11 +433,15 @@ PTF_TEST_CASE(HttpResponseLayerCreationTest) PTF_ASSERT_NULL(httpResponse.addField(PCPP_HTTP_SERVER_FIELD, "Microsoft-IIS/6.0")); pcpp::Logger::getInstance().enableLogs(); PTF_ASSERT_NOT_NULL(httpResponse.addField(PCPP_HTTP_CONTENT_ENCODING_FIELD, "gzip")); - PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName(PCPP_HTTP_SERVER_FIELD), PCPP_HTTP_CONTENT_TYPE_FIELD, "application/x-javascript")); - PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName(PCPP_HTTP_CONTENT_TYPE_FIELD), "Accept-Ranges", "bytes")); + PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName(PCPP_HTTP_SERVER_FIELD), + PCPP_HTTP_CONTENT_TYPE_FIELD, "application/x-javascript")); + PTF_ASSERT_NOT_NULL( + httpResponse.insertField(httpResponse.getFieldByName(PCPP_HTTP_CONTENT_TYPE_FIELD), "Accept-Ranges", "bytes")); PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName("Accept-Ranges"), "KuKu", "BlaBla")); - PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName("kuku"), "Last-Modified", "Wed, 19 Dec 2012 14:06:29 GMT")); - PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName("last-Modified"), "ETag", "\"3b846daf2ddcd1:e29\"")); + PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName("kuku"), "Last-Modified", + "Wed, 19 Dec 2012 14:06:29 GMT")); + PTF_ASSERT_NOT_NULL( + httpResponse.insertField(httpResponse.getFieldByName("last-Modified"), "ETag", "\"3b846daf2ddcd1:e29\"")); PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName("etag"), "Vary", "Accept-Encoding")); PTF_ASSERT_NOT_NULL(httpResponse.setContentLength(1616, PCPP_HTTP_CONTENT_ENCODING_FIELD)); PTF_ASSERT_NOT_NULL(httpResponse.addField("Kuku2", "blibli2")); @@ -427,26 +459,27 @@ PTF_TEST_CASE(HttpResponseLayerCreationTest) PTF_ASSERT_NOT_NULL(httpResponse.addField(PCPP_HTTP_CONNECTION_FIELD, "keep-alive")); PTF_ASSERT_NOT_NULL(httpResponse.addEndOfHeader()); - PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName("Cache-Control"), "Expires", "Mon, 20 Oct 2014 13:34:26 GMT")); + PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName("Cache-Control"), "Expires", + "Mon, 20 Oct 2014 13:34:26 GMT")); pcpp::Logger::getInstance().suppressLogs(); PTF_ASSERT_NULL(httpResponse.addField("kuku3", "kuka")); pcpp::Logger::getInstance().enableLogs(); - PTF_ASSERT_NOT_NULL(httpResponse.insertField(httpResponse.getFieldByName("ExpIRes"), "Date", "Sun, 19 Oct 2014 19:12:09 GMT")); + PTF_ASSERT_NOT_NULL( + httpResponse.insertField(httpResponse.getFieldByName("ExpIRes"), "Date", "Sun, 19 Oct 2014 19:12:09 GMT")); pcpp::Logger::getInstance().suppressLogs(); PTF_ASSERT_FALSE(httpResponse.removeField("kuku5")); pcpp::Logger::getInstance().enableLogs(); PTF_ASSERT_TRUE(httpResponse.removeField("kuku2")); - httpPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(httpResponse.getHeaderLen(), 382); - PTF_ASSERT_BUF_COMPARE(buffer1, httpPacket.getRawPacket()->getRawData(), ethLayer.getHeaderLen()+ip4Layer.getHeaderLen()+tcpLayer.getHeaderLen()+httpResponse.getHeaderLen()); - -} // HttpResponseLayerCreationTest - + PTF_ASSERT_BUF_COMPARE(buffer1, httpPacket.getRawPacket()->getRawData(), + ethLayer.getHeaderLen() + ip4Layer.getHeaderLen() + tcpLayer.getHeaderLen() + + httpResponse.getHeaderLen()); +} // HttpResponseLayerCreationTest PTF_TEST_CASE(HttpResponseLayerEditTest) { @@ -465,8 +498,10 @@ PTF_TEST_CASE(HttpResponseLayerEditTest) responseLayer->getFirstLine()->setVersion(pcpp::OneDotOne); // original status code is 404 Not Found - PTF_ASSERT_TRUE(responseLayer->getFirstLine()->setStatusCode(pcpp::HttpResponseStatusCode::Http505HTTPVersionNotSupported)); - PTF_ASSERT_EQUAL(responseLayer->getFirstLine()->getStatusCode(), pcpp::HttpResponseStatusCode::Http505HTTPVersionNotSupported, enum); + PTF_ASSERT_TRUE( + responseLayer->getFirstLine()->setStatusCode(pcpp::HttpResponseStatusCode::Http505HTTPVersionNotSupported)); + PTF_ASSERT_EQUAL(responseLayer->getFirstLine()->getStatusCode(), + pcpp::HttpResponseStatusCode::Http505HTTPVersionNotSupported, enum); PTF_ASSERT_EQUAL(responseLayer->getFirstLine()->getStatusCodeAsInt(), 505); PTF_ASSERT_EQUAL(responseLayer->getFirstLine()->getStatusCodeString(), "HTTP Version Not Supported"); @@ -476,15 +511,14 @@ PTF_TEST_CASE(HttpResponseLayerEditTest) PTF_ASSERT_BUF_COMPARE(expectedHttpResponse.c_str(), responseLayer->getData(), expectedHttpResponse.length()); - PTF_ASSERT_TRUE(responseLayer->getFirstLine()->setStatusCode(pcpp::HttpResponseStatusCode(pcpp::HttpResponseStatusCode::Http413RequestEntityTooLarge, "This is a test"))); + PTF_ASSERT_TRUE(responseLayer->getFirstLine()->setStatusCode( + pcpp::HttpResponseStatusCode(pcpp::HttpResponseStatusCode::Http413RequestEntityTooLarge, "This is a test"))); PTF_ASSERT_EQUAL(responseLayer->getFirstLine()->getStatusCodeAsInt(), 413); PTF_ASSERT_EQUAL(responseLayer->getFirstLine()->getStatusCodeString(), "This is a test"); expectedHttpResponse = "HTTP/1.1 413 This is a test\r\nContent-Length: 345\r\n"; PTF_ASSERT_BUF_COMPARE(expectedHttpResponse.c_str(), responseLayer->getData(), expectedHttpResponse.length()); -} // HttpResponseLayerEditTest - - +} // HttpResponseLayerEditTest /// In this test the first HTTP header field is malformed - it only has header name but not an header value PTF_TEST_CASE(HttpMalformedResponseTest) @@ -498,13 +532,20 @@ PTF_TEST_CASE(HttpMalformedResponseTest) pcpp::HttpResponseLayer* httpResp = httpPacket.getLayerOfType(); PTF_ASSERT_EQUAL(httpResp->getFieldCount(), 6); - std::string fieldNames[] = {"x-amz-request-id2 CA4DB8F36423461F\r\n", "x-amz-id-2", PCPP_HTTP_CONTENT_TYPE_FIELD, PCPP_HTTP_TRANSFER_ENCODING_FIELD, "Date", PCPP_HTTP_SERVER_FIELD}; - std::string fieldValues[] = {"", "xcjboWLTcibyztI2kdnRoUvPdimtSPdYQYsQ4pHAebH4miKlux4Am0SBZrvVxsHN", "application/xml", "chunked", "Thu, 21 Feb 2013 06:27:11 GMT", "AmazonS3"}; + std::string fieldNames[] = { "x-amz-request-id2 CA4DB8F36423461F\r\n", "x-amz-id-2", PCPP_HTTP_CONTENT_TYPE_FIELD, + PCPP_HTTP_TRANSFER_ENCODING_FIELD, "Date", PCPP_HTTP_SERVER_FIELD }; + std::string fieldValues[] = { "", + "xcjboWLTcibyztI2kdnRoUvPdimtSPdYQYsQ4pHAebH4miKlux4Am0SBZrvVxsHN", + "application/xml", + "chunked", + "Thu, 21 Feb 2013 06:27:11 GMT", + "AmazonS3" }; int index = 0; - for (pcpp::HeaderField* field = httpResp->getFirstField(); field != nullptr && !field->isEndOfHeader(); field = httpResp->getNextField(field)) + for (pcpp::HeaderField* field = httpResp->getFirstField(); field != nullptr && !field->isEndOfHeader(); + field = httpResp->getNextField(field)) { PTF_ASSERT_EQUAL(field->getFieldName(), fieldNames[index]); PTF_ASSERT_EQUAL(field->getFieldValue(), fieldValues[index]); index++; } -} // HttpMalformedResponseTest +} // HttpMalformedResponseTest diff --git a/Tests/Packet++Test/Tests/IPSecTests.cpp b/Tests/Packet++Test/Tests/IPSecTests.cpp index 3963449e9c..331eed8b50 100644 --- a/Tests/Packet++Test/Tests/IPSecTests.cpp +++ b/Tests/Packet++Test/Tests/IPSecTests.cpp @@ -4,7 +4,6 @@ #include "IPSecLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(IPSecParsingTest) { timeval time; @@ -58,4 +57,4 @@ PTF_TEST_CASE(IPSecParsingTest) PTF_ASSERT_NOT_NULL(espLayer); PTF_ASSERT_EQUAL(espLayer->getSPI(), 0x49507636); PTF_ASSERT_EQUAL(espLayer->getSequenceNumber(), 541414224); -} // IPSecParsingTest +} // IPSecParsingTest diff --git a/Tests/Packet++Test/Tests/IPv4Tests.cpp b/Tests/Packet++Test/Tests/IPv4Tests.cpp index 28a119be43..ba5573ad05 100644 --- a/Tests/Packet++Test/Tests/IPv4Tests.cpp +++ b/Tests/Packet++Test/Tests/IPv4Tests.cpp @@ -23,11 +23,9 @@ PTF_TEST_CASE(IPv4PacketCreation) pcpp::IPv4Layer ip4Layer(ipSrc, ipDst); ip4Layer.getIPv4Header()->protocol = pcpp::PACKETPP_IPPROTO_TCP; - uint8_t payload[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xa }; pcpp::PayloadLayer payloadLayer(payload, 10); - pcpp::Packet ip4Packet(1); PTF_ASSERT_TRUE(ip4Packet.addLayer(ðLayer)); @@ -55,9 +53,7 @@ PTF_TEST_CASE(IPv4PacketCreation) PTF_ASSERT_EQUAL(ipHeader->totalLength, htobe16(30)); PTF_ASSERT_EQUAL(ipHeader->protocol, (uint8_t)pcpp::PACKETPP_IPPROTO_TCP); PTF_ASSERT_EQUAL(ipHeader->headerChecksum, htobe16(0x90b1)); -} // Ipv4PacketCreation - - +} // Ipv4PacketCreation PTF_TEST_CASE(IPv4PacketParsing) { @@ -87,7 +83,6 @@ PTF_TEST_CASE(IPv4PacketParsing) PTF_ASSERT_TRUE(ipv4Layer->getOption(pcpp::IPV4OPT_CommercialSecurity).isNull()); PTF_ASSERT_EQUAL(ipv4Layer->getOptionCount(), 0); - READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/IPv4-TSO.dat"); pcpp::Packet ip4TSO(&rawPacket2); @@ -100,7 +95,6 @@ PTF_TEST_CASE(IPv4PacketParsing) PTF_ASSERT_NOT_NULL(ipv4Layer->getNextLayer()); PTF_ASSERT_EQUAL(ipv4Layer->getNextLayer()->getProtocol(), pcpp::ICMP, enum); - READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/IPv4-bad.dat"); pcpp::Packet bogusPkt(&rawPacket3, pcpp::IPv4); @@ -108,16 +102,13 @@ PTF_TEST_CASE(IPv4PacketParsing) ipv4Layer = bogusPkt.getLayerOfType(); PTF_ASSERT_NULL(ipv4Layer); - READ_FILE_AND_CREATE_PACKET(4, "PacketExamples/IPv4-encapsulated-IPv6.dat"); pcpp::Packet encapsulatedPkt(&rawPacket4, pcpp::IPv6); - pcpp::IPv6Layer *ipv6Layer = encapsulatedPkt.getLayerOfType(); + pcpp::IPv6Layer* ipv6Layer = encapsulatedPkt.getLayerOfType(); PTF_ASSERT_NOT_NULL(ipv6Layer); -} // Ipv4PacketParsing - - +} // Ipv4PacketParsing PTF_TEST_CASE(IPv4FragmentationTest) { @@ -142,7 +133,6 @@ PTF_TEST_CASE(IPv4FragmentationTest) PTF_ASSERT_NOT_NULL(ipLayer->getNextLayer()); PTF_ASSERT_EQUAL(ipLayer->getNextLayer()->getProtocol(), pcpp::GenericPayload, enum); - ipLayer = frag2.getLayerOfType(); PTF_ASSERT_NOT_NULL(ipLayer); PTF_ASSERT_TRUE(ipLayer->isFragment()); @@ -162,9 +152,7 @@ PTF_TEST_CASE(IPv4FragmentationTest) PTF_ASSERT_EQUAL(ipLayer->getFragmentFlags(), 0); PTF_ASSERT_NOT_NULL(ipLayer->getNextLayer()) PTF_ASSERT_EQUAL(ipLayer->getNextLayer()->getProtocol(), pcpp::GenericPayload, enum); -} // Ipv4FragmentationTest - - +} // Ipv4FragmentationTest PTF_TEST_CASE(IPv4OptionsParsingTest) { @@ -319,9 +307,7 @@ PTF_TEST_CASE(IPv4OptionsParsingTest) PTF_ASSERT_TRUE(opt2 == opt); opt = ipLayer->getNextOption(opt); PTF_ASSERT_TRUE(opt.isNull()); -} // Ipv4OptionsParsingTest - - +} // Ipv4OptionsParsingTest PTF_TEST_CASE(IPv4OptionsEditTest) { @@ -352,13 +338,17 @@ PTF_TEST_CASE(IPv4OptionsEditTest) pcpp::Packet ipOpt7(&rawPacket7); pcpp::IPv4Layer* ipLayer = ipOpt1.getLayerOfType(); - uint8_t commSecOptionData[] = { 0x00, 0x00, 0x00, 0x02, 0x02, 0x10, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x04, 0x00, 0x05, 0x00, 0x06, 0x00, 0xef }; - PTF_ASSERT_FALSE(ipLayer->addOption(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_CommercialSecurity, commSecOptionData, 20)).isNull()); + uint8_t commSecOptionData[] = { 0x00, 0x00, 0x00, 0x02, 0x02, 0x10, 0x00, 0x02, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x04, 0x00, 0x05, 0x00, 0x06, 0x00, 0xef }; + PTF_ASSERT_FALSE( + ipLayer->addOption(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_CommercialSecurity, commSecOptionData, 20)).isNull()); PTF_ASSERT_FALSE(ipLayer->addOption(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_EndOfOptionsList, nullptr, 0)).isNull()); - PTF_ASSERT_FALSE(ipLayer->addOptionAfter(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_EndOfOptionsList, nullptr, 0), pcpp::IPV4OPT_CommercialSecurity).isNull()); + PTF_ASSERT_FALSE(ipLayer + ->addOptionAfter(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_EndOfOptionsList, nullptr, 0), + pcpp::IPV4OPT_CommercialSecurity) + .isNull()); ipOpt1.computeCalculateFields(); - PTF_ASSERT_EQUAL(ipOpt1.getRawPacket()->getRawDataLen(), bufferLength11); PTF_ASSERT_BUF_COMPARE(ipOpt1.getRawPacket()->getRawData(), buffer11, ipOpt1.getRawPacket()->getRawDataLen()); @@ -375,15 +365,14 @@ PTF_TEST_CASE(IPv4OptionsEditTest) PTF_ASSERT_EQUAL(ipOpt2.getRawPacket()->getRawDataLen(), bufferLength22); PTF_ASSERT_BUF_COMPARE(ipOpt2.getRawPacket()->getRawData(), buffer22, ipOpt2.getRawPacket()->getRawDataLen()); - ipLayer = ipOpt3.getLayerOfType(); uint16_t routerAlerVal = 0; - PTF_ASSERT_FALSE(ipLayer->addOption(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_RouterAlert, (uint16_t)routerAlerVal)).isNull()); + PTF_ASSERT_FALSE( + ipLayer->addOption(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_RouterAlert, (uint16_t)routerAlerVal)).isNull()); ipOpt3.computeCalculateFields(); PTF_ASSERT_EQUAL(ipOpt3.getRawPacket()->getRawDataLen(), bufferLength33); PTF_ASSERT_BUF_COMPARE(ipOpt3.getRawPacket()->getRawData(), buffer33, ipOpt3.getRawPacket()->getRawDataLen()); - ipLayer = ipOpt4.getLayerOfType(); std::vector ipListValue; ipListValue.push_back(pcpp::IPv4Address("1.2.3.4")); @@ -397,7 +386,6 @@ PTF_TEST_CASE(IPv4OptionsEditTest) PTF_ASSERT_EQUAL(ipOpt4.getRawPacket()->getRawDataLen(), bufferLength44); PTF_ASSERT_BUF_COMPARE(ipOpt4.getRawPacket()->getRawData(), buffer44, ipOpt4.getRawPacket()->getRawDataLen()); - ipLayer = ipOpt5.getLayerOfType(); tsOption.clear(); pcpp::Logger::getInstance().suppressLogs(); @@ -464,7 +452,8 @@ PTF_TEST_CASE(IPv4OptionsEditTest) tsOption.timestamps.push_back(70037668); tsOption.timestamps.push_back(70037669); PTF_ASSERT_FALSE(ipLayer->addOptionAfter(pcpp::IPv4OptionBuilder(tsOption), pcpp::IPV4OPT_NOP).isNull()); - PTF_ASSERT_FALSE(ipLayer->addOptionAfter(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_RouterAlert, (uint16_t)routerAlerVal)).isNull()); + PTF_ASSERT_FALSE( + ipLayer->addOptionAfter(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_RouterAlert, (uint16_t)routerAlerVal)).isNull()); PTF_ASSERT_EQUAL(ipLayer->getOptionCount(), 4); ipOpt7.computeCalculateFields(); tsOption.clear(); @@ -473,7 +462,8 @@ PTF_TEST_CASE(IPv4OptionsEditTest) PTF_ASSERT_FALSE(ipLayer->addOption(pcpp::IPv4OptionBuilder(tsOption)).isNull()); PTF_ASSERT_EQUAL(ipLayer->getOptionCount(), 5); pcpp::Logger::getInstance().suppressLogs(); - PTF_ASSERT_TRUE(ipLayer->addOption(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_RouterAlert, (uint16_t)routerAlerVal)).isNull()); + PTF_ASSERT_TRUE( + ipLayer->addOption(pcpp::IPv4OptionBuilder(pcpp::IPV4OPT_RouterAlert, (uint16_t)routerAlerVal)).isNull()); pcpp::Logger::getInstance().enableLogs(); ipOpt7.computeCalculateFields(); PTF_ASSERT_EQUAL(ipLayer->getOptionCount(), 5); @@ -495,20 +485,18 @@ PTF_TEST_CASE(IPv4OptionsEditTest) ipLayer = ipOpt7.getLayerOfType(); PTF_ASSERT_EQUAL(ipLayer->getOptionCount(), 0); - delete [] buffer11; - delete [] buffer22; - delete [] buffer33; - delete [] buffer44; - delete [] buffer55; - delete [] buffer66; - delete [] buffer77; -} // Ipv4OptionsEditTest - - + delete[] buffer11; + delete[] buffer22; + delete[] buffer33; + delete[] buffer44; + delete[] buffer55; + delete[] buffer66; + delete[] buffer77; +} // Ipv4OptionsEditTest PTF_TEST_CASE(IPv4UdpChecksum) { - for (int i = 1; i<6; i++) + for (int i = 1; i < 6; i++) { std::stringstream strStream; strStream << "PacketExamples/UdpPacket4Checksum" << i << ".dat"; @@ -526,4 +514,4 @@ PTF_TEST_CASE(IPv4UdpChecksum) udpLayer->computeCalculateFields(); PTF_ASSERT_EQUAL(udpLayer->getUdpHeader()->headerChecksum, packetChecksum, hex); } -} // Ipv4UdpChecksum +} // Ipv4UdpChecksum diff --git a/Tests/Packet++Test/Tests/IPv6Tests.cpp b/Tests/Packet++Test/Tests/IPv6Tests.cpp index e019c33d65..e70af8a96b 100644 --- a/Tests/Packet++Test/Tests/IPv6Tests.cpp +++ b/Tests/Packet++Test/Tests/IPv6Tests.cpp @@ -40,7 +40,7 @@ PTF_TEST_CASE(IPv6UdpPacketParseAndCreate) PTF_ASSERT_EQUAL(pUdpLayer->getUdpHeader()->length, htobe16(154)); PTF_ASSERT_EQUAL(pUdpLayer->getUdpHeader()->headerChecksum, htobe16(0x5fea)); - pcpp::EthLayer ethLayer(pcpp::MacAddress("6c:f0:49:b2:de:6e"), pcpp::MacAddress ("33:33:00:00:00:0c")); + pcpp::EthLayer ethLayer(pcpp::MacAddress("6c:f0:49:b2:de:6e"), pcpp::MacAddress("33:33:00:00:00:0c")); pcpp::IPv6Layer ip6Layer(srcIP, dstIP); pcpp::ip6_hdr* ip6Header = ip6Layer.getIPv6Header(); @@ -72,9 +72,7 @@ PTF_TEST_CASE(IPv6UdpPacketParseAndCreate) PTF_ASSERT_EQUAL(ipv6LayerEmpty.getDstIPv6Address(), dstIP); delete[] payloadData; -} // IPv6UdpPacketParseAndCreate - - +} // IPv6UdpPacketParseAndCreate PTF_TEST_CASE(IPv6FragmentationTest) { @@ -153,10 +151,9 @@ PTF_TEST_CASE(IPv6FragmentationTest) newFrag.computeCalculateFields(); PTF_ASSERT_EQUAL(frag4.getRawPacket()->getRawDataLen(), newFrag.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(frag4.getRawPacket()->getRawData(), newFrag.getRawPacket()->getRawData(), frag4.getRawPacket()->getRawDataLen()); -} // IPv6FragmentationTest - - + PTF_ASSERT_BUF_COMPARE(frag4.getRawPacket()->getRawData(), newFrag.getRawPacket()->getRawData(), + frag4.getRawPacket()->getRawDataLen()); +} // IPv6FragmentationTest PTF_TEST_CASE(IPv6ExtensionsTest) { @@ -177,7 +174,6 @@ PTF_TEST_CASE(IPv6ExtensionsTest) pcpp::Packet ipv6AuthHdr(&rawPacket5); pcpp::Packet ipv6MultipleOptions(&rawPacket6); - // parsing of Destination extension pcpp::IPv6Layer* ipv6Layer = ipv6Dest.getLayerOfType(); PTF_ASSERT_EQUAL(ipv6Layer->getExtensionCount(), 1); @@ -207,7 +203,6 @@ PTF_TEST_CASE(IPv6ExtensionsTest) PTF_ASSERT_TRUE(destExt->getOption(12).isNull()); PTF_ASSERT_TRUE(destExt->getOption(0).isNull()); - // parsing of Hop-By-Hop extension ipv6Layer = ipv6HopByHop.getLayerOfType(); hopByHopExt = ipv6Layer->getExtensionOfType(); @@ -232,7 +227,6 @@ PTF_TEST_CASE(IPv6ExtensionsTest) option = hopByHopExt->getNextOption(option); PTF_ASSERT_TRUE(option.isNull()); - // parsing of routing extension #1 ipv6Layer = ipv6Routing1.getLayerOfType(); hopByHopExt = ipv6Layer->getExtensionOfType(); @@ -247,7 +241,6 @@ PTF_TEST_CASE(IPv6ExtensionsTest) PTF_ASSERT_EQUAL(routingExt->getRoutingAdditionalDataAsIPv6Address(4), pcpp::IPv6Address("2200::210:2:0:0:4")); PTF_ASSERT_EQUAL(routingExt->getRoutingAdditionalDataAsIPv6Address(20), pcpp::IPv6Address("2200::240:2:0:0:4")); - // parsing of routing extension #2 ipv6Layer = ipv6Routing2.getLayerOfType(); routingExt = ipv6Layer->getExtensionOfType(); @@ -259,7 +252,6 @@ PTF_TEST_CASE(IPv6ExtensionsTest) PTF_ASSERT_EQUAL(routingExt->getRoutingAdditionalDataAsIPv6Address(4), pcpp::IPv6Address("2200::210:2:0:0:4")); PTF_ASSERT_EQUAL(routingExt->getRoutingAdditionalDataAsIPv6Address(20), pcpp::IPv6Address::Zero); - // parsing of authentication header extension ipv6Layer = ipv6AuthHdr.getLayerOfType(); pcpp::IPv6AuthenticationHeader* authHdrExt = ipv6Layer->getExtensionOfType(); @@ -269,14 +261,16 @@ PTF_TEST_CASE(IPv6ExtensionsTest) PTF_ASSERT_EQUAL(authHdrExt->getAuthHeader()->sequenceNumber, htobe32(32)); PTF_ASSERT_EQUAL(authHdrExt->getIntegrityCheckValueLength(), 12); uint8_t expectedICV[12] = { 0x35, 0x48, 0x21, 0x48, 0xb2, 0x43, 0x5a, 0x23, 0xdc, 0xdd, 0x55, 0x36 }; - PTF_ASSERT_BUF_COMPARE(expectedICV, authHdrExt->getIntegrityCheckValue(), authHdrExt->getIntegrityCheckValueLength()); - + PTF_ASSERT_BUF_COMPARE(expectedICV, authHdrExt->getIntegrityCheckValue(), + authHdrExt->getIntegrityCheckValueLength()); // parsing of multiple options in one IPv6 layer ipv6Layer = ipv6MultipleOptions.getLayerOfType(); PTF_ASSERT_EQUAL(ipv6Layer->getExtensionCount(), 4); PTF_ASSERT_NOT_NULL(ipv6Layer->getExtensionOfType()); - PTF_ASSERT_EQUAL(ipv6Layer->getExtensionOfType()->getAuthHeader()->securityParametersIndex, be32toh(0x100)); + PTF_ASSERT_EQUAL( + ipv6Layer->getExtensionOfType()->getAuthHeader()->securityParametersIndex, + be32toh(0x100)); PTF_ASSERT_NOT_NULL(ipv6Layer->getExtensionOfType()); PTF_ASSERT_EQUAL(ipv6Layer->getExtensionOfType()->getFirstOption().getType(), 11); PTF_ASSERT_NOT_NULL(ipv6Layer->getExtensionOfType()); @@ -284,7 +278,6 @@ PTF_TEST_CASE(IPv6ExtensionsTest) PTF_ASSERT_NOT_NULL(ipv6Layer->getExtensionOfType()); PTF_ASSERT_EQUAL(ipv6Layer->getExtensionOfType()->getRoutingHeader()->routingType, 0); - // creation of Destination extension pcpp::EthLayer newEthLayer(*ipv6Dest.getLayerOfType()); @@ -310,8 +303,8 @@ PTF_TEST_CASE(IPv6ExtensionsTest) newPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(ipv6Dest.getRawPacket()->getRawDataLen(), newPacket.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(ipv6Dest.getRawPacket()->getRawData(), newPacket.getRawPacket()->getRawData(), ipv6Dest.getRawPacket()->getRawDataLen()); - + PTF_ASSERT_BUF_COMPARE(ipv6Dest.getRawPacket()->getRawData(), newPacket.getRawPacket()->getRawData(), + ipv6Dest.getRawPacket()->getRawDataLen()); // creation of hop-by-hop extension pcpp::EthLayer newEthLayer2(*ipv6HopByHop.getLayerOfType()); @@ -336,8 +329,8 @@ PTF_TEST_CASE(IPv6ExtensionsTest) newPacket2.computeCalculateFields(); PTF_ASSERT_EQUAL(ipv6HopByHop.getRawPacket()->getRawDataLen(), newPacket2.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(ipv6HopByHop.getRawPacket()->getRawData(), newPacket2.getRawPacket()->getRawData(), ipv6HopByHop.getRawPacket()->getRawDataLen()); - + PTF_ASSERT_BUF_COMPARE(ipv6HopByHop.getRawPacket()->getRawData(), newPacket2.getRawPacket()->getRawData(), + ipv6HopByHop.getRawPacket()->getRawDataLen()); // creation of routing extension pcpp::EthLayer newEthLayer3(*ipv6Routing2.getLayerOfType()); @@ -353,7 +346,7 @@ PTF_TEST_CASE(IPv6ExtensionsTest) ip6Addr.copyTo(routingAdditionalData + 4); pcpp::IPv6RoutingHeader newRoutingHeader(0, 1, routingAdditionalData, 20); newIPv6Layer3.addExtension(newRoutingHeader); - delete [] routingAdditionalData; + delete[] routingAdditionalData; pcpp::UdpLayer newUdpLayer3(*ipv6Routing2.getLayerOfType()); @@ -363,8 +356,8 @@ PTF_TEST_CASE(IPv6ExtensionsTest) newPacket3.addLayer(&newUdpLayer3); PTF_ASSERT_EQUAL(ipv6Routing2.getRawPacket()->getRawDataLen(), newPacket3.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(ipv6Routing2.getRawPacket()->getRawData(), newPacket3.getRawPacket()->getRawData(), ipv6Routing2.getRawPacket()->getRawDataLen()); - + PTF_ASSERT_BUF_COMPARE(ipv6Routing2.getRawPacket()->getRawData(), newPacket3.getRawPacket()->getRawData(), + ipv6Routing2.getRawPacket()->getRawDataLen()); // creation of AH extension pcpp::EthLayer newEthLayer4(*ipv6AuthHdr.getLayerOfType()); @@ -386,8 +379,8 @@ PTF_TEST_CASE(IPv6ExtensionsTest) newPacket4.computeCalculateFields(); PTF_ASSERT_EQUAL(ipv6AuthHdr.getRawPacket()->getRawDataLen(), newPacket4.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(ipv6AuthHdr.getRawPacket()->getRawData(), newPacket4.getRawPacket()->getRawData(), ipv6AuthHdr.getRawPacket()->getRawDataLen()); - + PTF_ASSERT_BUF_COMPARE(ipv6AuthHdr.getRawPacket()->getRawData(), newPacket4.getRawPacket()->getRawData(), + ipv6AuthHdr.getRawPacket()->getRawDataLen()); // creation of packet with several extensions pcpp::EthLayer newEthLayer5(*ipv6AuthHdr.getLayerOfType()); @@ -409,5 +402,6 @@ PTF_TEST_CASE(IPv6ExtensionsTest) newPacket5.computeCalculateFields(); PTF_ASSERT_EQUAL(ipv6MultipleOptions.getRawPacket()->getRawDataLen(), newPacket5.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(ipv6MultipleOptions.getRawPacket()->getRawData(), newPacket5.getRawPacket()->getRawData(), ipv6MultipleOptions.getRawPacket()->getRawDataLen()); -} // IPv6ExtensionsTest + PTF_ASSERT_BUF_COMPARE(ipv6MultipleOptions.getRawPacket()->getRawData(), newPacket5.getRawPacket()->getRawData(), + ipv6MultipleOptions.getRawPacket()->getRawDataLen()); +} // IPv6ExtensionsTest diff --git a/Tests/Packet++Test/Tests/IcmpTests.cpp b/Tests/Packet++Test/Tests/IcmpTests.cpp index 4e75774a3b..1060580340 100644 --- a/Tests/Packet++Test/Tests/IcmpTests.cpp +++ b/Tests/Packet++Test/Tests/IcmpTests.cpp @@ -9,7 +9,6 @@ #include "UdpLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(IcmpParsingTest) { timeval time; @@ -65,7 +64,6 @@ PTF_TEST_CASE(IcmpParsingTest) PTF_ASSERT_TRUE(icmpAddrMaskReq.isPacketOfType(pcpp::ICMP)); PTF_ASSERT_TRUE(icmpAddrMaskRep.isPacketOfType(pcpp::ICMP)); - // Echo request icmpLayer = icmpEchoRequest.getLayerOfType(); PTF_ASSERT_NOT_NULL(icmpLayer); @@ -256,9 +254,7 @@ PTF_TEST_CASE(IcmpParsingTest) PTF_ASSERT_NOT_NULL(routerAddr); PTF_ASSERT_EQUAL(pcpp::IPv4Address(routerAddr->routerAddress), pcpp::IPv4Address("14.80.84.66")); PTF_ASSERT_EQUAL(routerAddr->preferenceLevel, 0); -} // IcmpParsingTest - - +} // IcmpParsingTest PTF_TEST_CASE(IcmpCreationTest) { @@ -285,9 +281,11 @@ PTF_TEST_CASE(IcmpCreationTest) pcpp::IPv4Layer ipLayer(pcpp::IPv4Address("1.1.1.1"), pcpp::IPv4Address("2.2.2.2")); - uint8_t data[48] = { 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, - 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 }; + uint8_t data[48] = { + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 + }; // Echo request creation pcpp::IcmpLayer echoReqLayer; @@ -298,7 +296,7 @@ PTF_TEST_CASE(IcmpCreationTest) PTF_ASSERT_TRUE(echoRequestPacket.addLayer(&echoReqLayer)); echoRequestPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(echoRequestPacket.getRawPacket()->getRawDataLen(), bufferLength1); - PTF_ASSERT_BUF_COMPARE(echoRequestPacket.getRawPacket()->getRawData()+34, buffer1+34, bufferLength1-34); + PTF_ASSERT_BUF_COMPARE(echoRequestPacket.getRawPacket()->getRawData() + 34, buffer1 + 34, bufferLength1 - 34); // Echo reply creation pcpp::EthLayer ethLayer2(ethLayer); @@ -311,7 +309,7 @@ PTF_TEST_CASE(IcmpCreationTest) PTF_ASSERT_NOT_NULL(echoRepLayer.setEchoReplyData(0xd73b, 0, 0xe45104007dd6a751ULL, data, 48)); echoReplyPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(echoReplyPacket.getRawPacket()->getRawDataLen(), bufferLength2); - PTF_ASSERT_BUF_COMPARE(echoReplyPacket.getRawPacket()->getRawData()+34, buffer2+34, bufferLength2-34); + PTF_ASSERT_BUF_COMPARE(echoReplyPacket.getRawPacket()->getRawData() + 34, buffer2 + 34, bufferLength2 - 34); // Time exceeded creation pcpp::EthLayer ethLayer3(ethLayer); @@ -333,7 +331,7 @@ PTF_TEST_CASE(IcmpCreationTest) PTF_ASSERT_NOT_NULL(timeExceededLayer.setTimeExceededData(0, &ipLayerForTimeExceeded, &icmpLayerForTimeExceeded)); timeExceededPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(timeExceededPacket.getRawPacket()->getRawDataLen(), bufferLength11); - PTF_ASSERT_BUF_COMPARE(timeExceededPacket.getRawPacket()->getRawData()+34, buffer11+34, bufferLength11-34); + PTF_ASSERT_BUF_COMPARE(timeExceededPacket.getRawPacket()->getRawData() + 34, buffer11 + 34, bufferLength11 - 34); // Dest unreachable creation pcpp::EthLayer ethLayer4(ethLayer); @@ -350,10 +348,11 @@ PTF_TEST_CASE(IcmpCreationTest) PTF_ASSERT_TRUE(destUnreachablePacket.addLayer(ðLayer4)); PTF_ASSERT_TRUE(destUnreachablePacket.addLayer(&ipLayer4)); PTF_ASSERT_TRUE(destUnreachablePacket.addLayer(&destUnreachableLayer)); - PTF_ASSERT_NOT_NULL(destUnreachableLayer.setDestUnreachableData(pcpp::IcmpPortUnreachable, 0, &ipLayerForDestUnreachable, &udpLayerForDestUnreachable)); + PTF_ASSERT_NOT_NULL(destUnreachableLayer.setDestUnreachableData( + pcpp::IcmpPortUnreachable, 0, &ipLayerForDestUnreachable, &udpLayerForDestUnreachable)); destUnreachablePacket.computeCalculateFields(); PTF_ASSERT_EQUAL(destUnreachablePacket.getRawPacket()->getRawDataLen(), bufferLength10); - PTF_ASSERT_BUF_COMPARE(destUnreachablePacket.getRawPacket()->getRawData()+34, buffer10+34, bufferLength10-34); + PTF_ASSERT_BUF_COMPARE(destUnreachablePacket.getRawPacket()->getRawData() + 34, buffer10 + 34, bufferLength10 - 34); // Timestamp reply pcpp::EthLayer ethLayer5(ethLayer); @@ -368,7 +367,7 @@ PTF_TEST_CASE(IcmpCreationTest) PTF_ASSERT_TRUE(timestampReplyPacket.addLayer(&ipLayer5)); PTF_ASSERT_TRUE(timestampReplyPacket.addLayer(×tampReplyLayer)); timestampReplyPacket.computeCalculateFields(); - PTF_ASSERT_EQUAL(timestampReplyPacket.getRawPacket()->getRawDataLen(), bufferLength4-6); + PTF_ASSERT_EQUAL(timestampReplyPacket.getRawPacket()->getRawDataLen(), bufferLength4 - 6); // Address mask request pcpp::EthLayer ethLayer6(ethLayer); @@ -381,7 +380,8 @@ PTF_TEST_CASE(IcmpCreationTest) PTF_ASSERT_TRUE(addressMaskRequestPacket.addLayer(&addressMaskRequestLayer)); addressMaskRequestPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(addressMaskRequestPacket.getRawPacket()->getRawDataLen(), bufferLength14 - 14); - PTF_ASSERT_BUF_COMPARE(addressMaskRequestPacket.getRawPacket()->getRawData() + 34, buffer14 + 34, bufferLength14 - 34 - 14); + PTF_ASSERT_BUF_COMPARE(addressMaskRequestPacket.getRawPacket()->getRawData() + 34, buffer14 + 34, + bufferLength14 - 34 - 14); // Redirect creation pcpp::EthLayer ethLayer7(ethLayer); @@ -399,9 +399,10 @@ PTF_TEST_CASE(IcmpCreationTest) PTF_ASSERT_TRUE(redirectPacket.addLayer(ðLayer7)); PTF_ASSERT_TRUE(redirectPacket.addLayer(&ipLayer7)); PTF_ASSERT_TRUE(redirectPacket.addLayer(&redirectLayer)); - PTF_ASSERT_NOT_NULL(redirectLayer.setRedirectData(1, pcpp::IPv4Address("10.2.99.98"), &ipLayerForRedirect, &icmpLayerForRedirect)); + PTF_ASSERT_NOT_NULL( + redirectLayer.setRedirectData(1, pcpp::IPv4Address("10.2.99.98"), &ipLayerForRedirect, &icmpLayerForRedirect)); redirectPacket.computeCalculateFields(); - PTF_ASSERT_EQUAL(redirectPacket.getRawPacket()->getRawDataLen(), bufferLength5+8); + PTF_ASSERT_EQUAL(redirectPacket.getRawPacket()->getRawDataLen(), bufferLength5 + 8); // Router advertisement creation pcpp::EthLayer ethLayer8(ethLayer); @@ -424,27 +425,24 @@ PTF_TEST_CASE(IcmpCreationTest) PTF_ASSERT_NOT_NULL(routerAdvLayer.setRouterAdvertisementData(16, 200, routerAddresses)); routerAdvPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(routerAdvLayer.getHeaderLen(), 32); - PTF_ASSERT_EQUAL(routerAdvPacket.getRawPacket()->getRawDataLen(), bufferLength6-18); - - - delete [] buffer1; - delete [] buffer2; - delete [] buffer3; - delete [] buffer4; - delete [] buffer5; - delete [] buffer6; - delete [] buffer7; - delete [] buffer8; - delete [] buffer9; - delete [] buffer10; - delete [] buffer11; - delete [] buffer12; - delete [] buffer13; - delete [] buffer14; - delete [] buffer15; -} // IcmpCreationTest - - + PTF_ASSERT_EQUAL(routerAdvPacket.getRawPacket()->getRawDataLen(), bufferLength6 - 18); + + delete[] buffer1; + delete[] buffer2; + delete[] buffer3; + delete[] buffer4; + delete[] buffer5; + delete[] buffer6; + delete[] buffer7; + delete[] buffer8; + delete[] buffer9; + delete[] buffer10; + delete[] buffer11; + delete[] buffer12; + delete[] buffer13; + delete[] buffer14; + delete[] buffer15; +} // IcmpCreationTest PTF_TEST_CASE(IcmpEditTest) { @@ -464,9 +462,11 @@ PTF_TEST_CASE(IcmpEditTest) pcpp::IcmpLayer* icmpLayer = icmpRouterAdv1.getLayerOfType(); PTF_ASSERT_NOT_NULL(icmpLayer); - uint8_t data[48] = { 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, - 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 }; + uint8_t data[48] = { + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 + }; PTF_ASSERT_NOT_NULL(icmpLayer->getRouterAdvertisementData()); PTF_ASSERT_NULL(icmpLayer->getEchoRequestData()); @@ -477,8 +477,7 @@ PTF_TEST_CASE(IcmpEditTest) PTF_ASSERT_EQUAL(echoReq->dataLength, 48); icmpRouterAdv1.computeCalculateFields(); PTF_ASSERT_NULL(icmpLayer->getRouterAdvertisementData()); - PTF_ASSERT_BUF_COMPARE(icmpRouterAdv1.getRawPacket()->getRawData()+34, buffer2+34, bufferLength2-34); - + PTF_ASSERT_BUF_COMPARE(icmpRouterAdv1.getRawPacket()->getRawData() + 34, buffer2 + 34, bufferLength2 - 34); // convert echo request to echo reply @@ -486,8 +485,7 @@ PTF_TEST_CASE(IcmpEditTest) PTF_ASSERT_NULL(icmpLayer->getEchoRequestData()); icmpRouterAdv1.computeCalculateFields(); PTF_ASSERT_EQUAL(echoReply->header->checksum, htobe16(0xc3b3)); - PTF_ASSERT_BUF_COMPARE(icmpRouterAdv1.getRawPacket()->getRawData()+34, buffer3+34, bufferLength3-34); - + PTF_ASSERT_BUF_COMPARE(icmpRouterAdv1.getRawPacket()->getRawData() + 34, buffer3 + 34, bufferLength3 - 34); // convert time exceeded to echo request @@ -513,12 +511,12 @@ PTF_TEST_CASE(IcmpEditTest) PTF_ASSERT_EQUAL(echoReq->header->id, htobe16(55099)); PTF_ASSERT_EQUAL(echoReq->dataLength, 48); icmpTimeExceededUdp.computeCalculateFields(); - PTF_ASSERT_BUF_COMPARE(icmpTimeExceededUdp.getRawPacket()->getRawData()+34, buffer2+34, bufferLength2-34); - + PTF_ASSERT_BUF_COMPARE(icmpTimeExceededUdp.getRawPacket()->getRawData() + 34, buffer2 + 34, bufferLength2 - 34); // convert echo request to dest unreachable - pcpp::icmp_destination_unreachable* destUnreachable = icmpLayer->setDestUnreachableData(pcpp::IcmpHostUnreachable, 0, &ipLayerForDestUnreachable, &icmpLayerForDestUnreachable); + pcpp::icmp_destination_unreachable* destUnreachable = icmpLayer->setDestUnreachableData( + pcpp::IcmpHostUnreachable, 0, &ipLayerForDestUnreachable, &icmpLayerForDestUnreachable); PTF_ASSERT_NOT_NULL(destUnreachable); PTF_ASSERT_EQUAL(icmpLayer->getHeaderLen(), 8); PTF_ASSERT_EQUAL(destUnreachable->code, (uint8_t)pcpp::IcmpHostUnreachable); @@ -534,9 +532,9 @@ PTF_TEST_CASE(IcmpEditTest) PTF_ASSERT_NOT_NULL(echoReq); PTF_ASSERT_EQUAL(echoReq->header->sequence, htobe16(4)); icmpTimeExceededUdp.computeCalculateFields(); - PTF_ASSERT_BUF_COMPARE(icmpTimeExceededUdp.getRawPacket()->getRawData()+34, buffer5+34, bufferLength5-34); + PTF_ASSERT_BUF_COMPARE(icmpTimeExceededUdp.getRawPacket()->getRawData() + 34, buffer5 + 34, bufferLength5 - 34); - delete [] buffer2; - delete [] buffer3; - delete [] buffer5; -} // IcmpEditTest + delete[] buffer2; + delete[] buffer3; + delete[] buffer5; +} // IcmpEditTest diff --git a/Tests/Packet++Test/Tests/IcmpV6Tests.cpp b/Tests/Packet++Test/Tests/IcmpV6Tests.cpp index 75c598c671..ce547e6355 100644 --- a/Tests/Packet++Test/Tests/IcmpV6Tests.cpp +++ b/Tests/Packet++Test/Tests/IcmpV6Tests.cpp @@ -34,7 +34,7 @@ PTF_TEST_CASE(IcmpV6ParsingTest) // Echo request PTF_ASSERT_TRUE(echoRequestPacket.isPacketOfType(pcpp::ICMPv6)); - pcpp::ICMPv6EchoLayer *echoRequestLayer = echoRequestPacket.getLayerOfType(); + pcpp::ICMPv6EchoLayer* echoRequestLayer = echoRequestPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(echoRequestLayer); PTF_ASSERT_TRUE(echoRequestLayer->isMessageOfType(pcpp::ICMPv6MessageType::ICMPv6_ECHO_REQUEST)); PTF_ASSERT_EQUAL(echoRequestLayer->getMessageType(), pcpp::ICMPv6MessageType::ICMPv6_ECHO_REQUEST, enumclass); @@ -44,12 +44,12 @@ PTF_TEST_CASE(IcmpV6ParsingTest) PTF_ASSERT_EQUAL(echoRequestLayer->getSequenceNr(), 20); PTF_ASSERT_EQUAL(echoRequestLayer->getEchoDataLen(), 56); - uint8_t data[] = {0xbd, 0xce, 0xcb, 0x62}; + uint8_t data[] = { 0xbd, 0xce, 0xcb, 0x62 }; PTF_ASSERT_BUF_COMPARE(echoRequestLayer->getEchoDataPtr(), data, 4); // Echo reply PTF_ASSERT_TRUE(echoReplyPacket.isPacketOfType(pcpp::ICMPv6)); - pcpp::ICMPv6EchoLayer *echoReplyLayer = echoReplyPacket.getLayerOfType(); + pcpp::ICMPv6EchoLayer* echoReplyLayer = echoReplyPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(echoReplyLayer); PTF_ASSERT_TRUE(echoReplyLayer->isMessageOfType(pcpp::ICMPv6MessageType::ICMPv6_ECHO_REPLY)); PTF_ASSERT_EQUAL(echoReplyLayer->getMessageType(), pcpp::ICMPv6MessageType::ICMPv6_ECHO_REPLY, enumclass); @@ -63,10 +63,12 @@ PTF_TEST_CASE(IcmpV6ParsingTest) // Neighbor solicitation with source link-layer option PTF_ASSERT_TRUE(neighSoliPacket.isPacketOfType(pcpp::ICMPv6)); - pcpp::NDPNeighborSolicitationLayer *neighSoliLayer = neighSoliPacket.getLayerOfType(); + pcpp::NDPNeighborSolicitationLayer* neighSoliLayer = + neighSoliPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(neighSoliLayer); PTF_ASSERT_EQUAL(neighSoliLayer->getHeaderLen(), 32); - PTF_ASSERT_EQUAL(neighSoliLayer->getMessageType(), pcpp::ICMPv6MessageType::ICMPv6_NEIGHBOR_SOLICITATION, enumclass); + PTF_ASSERT_EQUAL(neighSoliLayer->getMessageType(), pcpp::ICMPv6MessageType::ICMPv6_NEIGHBOR_SOLICITATION, + enumclass); PTF_ASSERT_EQUAL(neighSoliLayer->getCode(), 0); PTF_ASSERT_EQUAL(neighSoliLayer->getChecksum(), 0xfe98); PTF_ASSERT_EQUAL(neighSoliLayer->getTargetIP(), pcpp::IPv6Address("fd53:7cb8:383:2::1:117")); @@ -74,26 +76,31 @@ PTF_TEST_CASE(IcmpV6ParsingTest) PTF_ASSERT_EQUAL(neighSoliLayer->getLinkLayerAddress(), pcpp::MacAddress("00:54:af:e9:4d:80")); PTF_ASSERT_EQUAL(neighSoliLayer->getNdpOptionCount(), 1); - pcpp::NdpOption sourceLinkLayerOption = neighSoliLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_SOURCE_LINK_LAYER); + pcpp::NdpOption sourceLinkLayerOption = + neighSoliLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_SOURCE_LINK_LAYER); PTF_ASSERT_TRUE(sourceLinkLayerOption.isNotNull()); PTF_ASSERT_EQUAL((int)sourceLinkLayerOption.getNdpOptionType(), 1); PTF_ASSERT_EQUAL(sourceLinkLayerOption.getDataSize(), 6); PTF_ASSERT_EQUAL(sourceLinkLayerOption.getTotalSize(), 8); PTF_ASSERT_EQUAL(pcpp::MacAddress(sourceLinkLayerOption.getValue()), pcpp::MacAddress("00:54:af:e9:4d:80")); - pcpp::NdpOption targetLinkLayerOption2 = neighSoliLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_TARGET_LINK_LAYER); + pcpp::NdpOption targetLinkLayerOption2 = + neighSoliLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_TARGET_LINK_LAYER); PTF_ASSERT_TRUE(targetLinkLayerOption2.isNull()); - pcpp::IcmpV6Layer *icmpNeighSoliLayer = neighSoliPacket.getLayerOfType(); + pcpp::IcmpV6Layer* icmpNeighSoliLayer = neighSoliPacket.getLayerOfType(); PTF_ASSERT_EQUAL(icmpNeighSoliLayer->getHeaderLen(), 32); - PTF_ASSERT_EQUAL(icmpNeighSoliLayer->getMessageType(), pcpp::ICMPv6MessageType::ICMPv6_NEIGHBOR_SOLICITATION, enumclass); + PTF_ASSERT_EQUAL(icmpNeighSoliLayer->getMessageType(), pcpp::ICMPv6MessageType::ICMPv6_NEIGHBOR_SOLICITATION, + enumclass); PTF_ASSERT_EQUAL(icmpNeighSoliLayer->getCode(), 0); PTF_ASSERT_EQUAL(icmpNeighSoliLayer->getChecksum(), 0xfe98); // Neighbor advertisement with target link-layer option PTF_ASSERT_TRUE(neighAdvPacket.isPacketOfType(pcpp::ICMPv6)); - pcpp::NDPNeighborAdvertisementLayer *neighAdvLayer = neighAdvPacket.getLayerOfType(); + pcpp::NDPNeighborAdvertisementLayer* neighAdvLayer = + neighAdvPacket.getLayerOfType(); PTF_ASSERT_EQUAL(neighAdvLayer->getHeaderLen(), 32); - PTF_ASSERT_EQUAL(neighAdvLayer->getMessageType(), pcpp::ICMPv6MessageType::ICMPv6_NEIGHBOR_ADVERTISEMENT, enumclass); + PTF_ASSERT_EQUAL(neighAdvLayer->getMessageType(), pcpp::ICMPv6MessageType::ICMPv6_NEIGHBOR_ADVERTISEMENT, + enumclass); PTF_ASSERT_EQUAL(neighAdvLayer->getCode(), 0); PTF_ASSERT_EQUAL(neighAdvLayer->getChecksum(), 0x9abb); PTF_ASSERT_TRUE(neighAdvLayer->getRouterFlag()); @@ -104,14 +111,15 @@ PTF_TEST_CASE(IcmpV6ParsingTest) PTF_ASSERT_EQUAL(neighAdvLayer->getTargetMac(), pcpp::MacAddress("c2:00:54:f5:00:00")); PTF_ASSERT_EQUAL(neighAdvLayer->getNdpOptionCount(), 1); - pcpp::NdpOption targetLinkLayerOption = neighAdvLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_TARGET_LINK_LAYER); + pcpp::NdpOption targetLinkLayerOption = + neighAdvLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_TARGET_LINK_LAYER); PTF_ASSERT_TRUE(targetLinkLayerOption.isNotNull()); PTF_ASSERT_EQUAL((int)targetLinkLayerOption.getNdpOptionType(), 2); PTF_ASSERT_EQUAL(targetLinkLayerOption.getDataSize(), 6); PTF_ASSERT_EQUAL(targetLinkLayerOption.getTotalSize(), 8); PTF_ASSERT_EQUAL(pcpp::MacAddress(targetLinkLayerOption.getValue()), pcpp::MacAddress("c2:00:54:f5:00:00")); - pcpp::IcmpV6Layer *icmpNeighAdv = neighAdvPacket.getLayerOfType(); + pcpp::IcmpV6Layer* icmpNeighAdv = neighAdvPacket.getLayerOfType(); PTF_ASSERT_EQUAL(icmpNeighAdv->getHeaderLen(), 32); PTF_ASSERT_EQUAL(icmpNeighAdv->getMessageType(), pcpp::ICMPv6MessageType::ICMPv6_NEIGHBOR_ADVERTISEMENT, enumclass); PTF_ASSERT_EQUAL(icmpNeighAdv->getCode(), 0); @@ -119,7 +127,8 @@ PTF_TEST_CASE(IcmpV6ParsingTest) // Neighbor advertisement without target link-layer option PTF_ASSERT_TRUE(neighAdvPacketNoOpt.isPacketOfType(pcpp::ICMPv6)); - pcpp::NDPNeighborAdvertisementLayer *neighAdvNoOptLayer = neighAdvPacketNoOpt.getLayerOfType(); + pcpp::NDPNeighborAdvertisementLayer* neighAdvNoOptLayer = + neighAdvPacketNoOpt.getLayerOfType(); PTF_ASSERT_EQUAL(neighAdvNoOptLayer->getHeaderLen(), 24); PTF_ASSERT_FALSE(neighAdvNoOptLayer->getRouterFlag()); PTF_ASSERT_TRUE(neighAdvNoOptLayer->getUnicastFlag()); @@ -128,22 +137,26 @@ PTF_TEST_CASE(IcmpV6ParsingTest) PTF_ASSERT_FALSE(neighAdvNoOptLayer->hasTargetMacInfo()); PTF_ASSERT_EQUAL(neighAdvNoOptLayer->getTargetMac(), pcpp::MacAddress()); PTF_ASSERT_EQUAL(neighAdvNoOptLayer->getNdpOptionCount(), 0); - pcpp::NdpOption targetLinkLayerNoOptOption = neighAdvNoOptLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_TARGET_LINK_LAYER); + pcpp::NdpOption targetLinkLayerNoOptOption = + neighAdvNoOptLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_TARGET_LINK_LAYER); PTF_ASSERT_TRUE(targetLinkLayerNoOptOption.isNull()); // Generic ICMPv6 packet PTF_ASSERT_TRUE(icmpV6GenericPacket.isPacketOfType(pcpp::ICMPv6)); - pcpp::IcmpV6Layer *icmpV6Layer = icmpV6GenericPacket.getLayerOfType(); + pcpp::IcmpV6Layer* icmpV6Layer = icmpV6GenericPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(icmpV6Layer); PTF_ASSERT_EQUAL(icmpV6Layer->getHeaderLen(), 48); PTF_ASSERT_TRUE(icmpV6Layer->isMessageOfType(pcpp::ICMPv6MessageType::ICMPv6_MULTICAST_LISTENER_DISCOVERY_REPORTS)); - PTF_ASSERT_EQUAL(icmpV6Layer->getMessageType(), pcpp::ICMPv6MessageType::ICMPv6_MULTICAST_LISTENER_DISCOVERY_REPORTS, enumclass); + PTF_ASSERT_EQUAL(icmpV6Layer->getMessageType(), + pcpp::ICMPv6MessageType::ICMPv6_MULTICAST_LISTENER_DISCOVERY_REPORTS, enumclass); PTF_ASSERT_EQUAL(icmpV6Layer->getCode(), 0); PTF_ASSERT_EQUAL(icmpV6Layer->getChecksum(), 0x2b5a); PTF_ASSERT_EQUAL(icmpV6Layer->toString(), "ICMPv6 Layer, Message type: 143"); PTF_ASSERT_NULL(icmpV6Layer->getNextLayer()); - std::string expectedPayloadString = "0000000204000000ff05000000000000000000000001000304000000ff020000000000000000000000010002"; - PTF_ASSERT_EQUAL(pcpp::byteArrayToHexString(icmpV6Layer->getDataPtr(4), icmpV6Layer->getDataLen() - 4), expectedPayloadString); + std::string expectedPayloadString = + "0000000204000000ff05000000000000000000000001000304000000ff020000000000000000000000010002"; + PTF_ASSERT_EQUAL(pcpp::byteArrayToHexString(icmpV6Layer->getDataPtr(4), icmpV6Layer->getDataLen() - 4), + expectedPayloadString); } PTF_TEST_CASE(IcmpV6CreationTest) @@ -158,13 +171,14 @@ PTF_TEST_CASE(IcmpV6CreationTest) READ_FILE_INTO_BUFFER(5, "PacketExamples/IcmpV6_NeighAdvNoOption.dat"); READ_FILE_INTO_BUFFER(6, "PacketExamples/IcmpV6_Generic.dat"); - uint8_t data[56] = {0xbd, 0xce, 0xcb, 0x62, 0x00, 0x00, 0x00, 0x00, 0xf3, 0xa1, 0x09, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, - 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, - 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37}; + uint8_t data[56] = { 0xbd, 0xce, 0xcb, 0x62, 0x00, 0x00, 0x00, 0x00, 0xf3, 0xa1, 0x09, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, + 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, + 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 }; pcpp::EthLayer ethLayer(pcpp::MacAddress("11:22:33:44:55:66"), pcpp::MacAddress("66:55:44:33:22:11")); - pcpp::IPv6Layer ipv6Layer(pcpp::IPv6Address(std::string("fe80::215:5dff:fea5:c4c5")), pcpp::IPv6Address(std::string("fe80::dd05:dae0:74bc:7341"))); + pcpp::IPv6Layer ipv6Layer(pcpp::IPv6Address(std::string("fe80::215:5dff:fea5:c4c5")), + pcpp::IPv6Address(std::string("fe80::dd05:dae0:74bc:7341"))); // Create ICMPv6 layer with type, code and data pcpp::IcmpV6Layer icmpv6Layer(pcpp::ICMPv6MessageType::ICMPv6_ECHO_REQUEST, 0, data, 56); @@ -173,8 +187,11 @@ PTF_TEST_CASE(IcmpV6CreationTest) PTF_ASSERT_TRUE(icmpv6LayerPacket.addLayer(&ipv6Layer)); PTF_ASSERT_TRUE(icmpv6LayerPacket.addLayer(&icmpv6Layer)); icmpv6LayerPacket.computeCalculateFields(); - PTF_ASSERT_EQUAL(icmpv6LayerPacket.getRawPacket()->getRawDataLen(), bufferLength1-4); // comparing with IcmpV6_EchoRequest frame which has the same data but an additional echo header - PTF_ASSERT_BUF_COMPARE(icmpv6LayerPacket.getRawPacket()->getRawData()+58, buffer1+62, bufferLength1-62); + PTF_ASSERT_EQUAL( + icmpv6LayerPacket.getRawPacket()->getRawDataLen(), + bufferLength1 - + 4); // comparing with IcmpV6_EchoRequest frame which has the same data but an additional echo header + PTF_ASSERT_BUF_COMPARE(icmpv6LayerPacket.getRawPacket()->getRawData() + 58, buffer1 + 62, bufferLength1 - 62); // Echo request creation pcpp::EthLayer ethLayer1(ethLayer); @@ -186,7 +203,7 @@ PTF_TEST_CASE(IcmpV6CreationTest) PTF_ASSERT_TRUE(echoRequestPacket.addLayer(&echoReqLayer)); echoRequestPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(echoRequestPacket.getRawPacket()->getRawDataLen(), bufferLength1); - PTF_ASSERT_BUF_COMPARE(echoRequestPacket.getRawPacket()->getRawData()+54, buffer1+54, bufferLength1-54); + PTF_ASSERT_BUF_COMPARE(echoRequestPacket.getRawPacket()->getRawData() + 54, buffer1 + 54, bufferLength1 - 54); // Echo reply creation pcpp::EthLayer ethLayer2(ethLayer); @@ -198,19 +215,25 @@ PTF_TEST_CASE(IcmpV6CreationTest) PTF_ASSERT_TRUE(echoReplyPacket.addLayer(&echoRepLayer)); echoReplyPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(echoReplyPacket.getRawPacket()->getRawDataLen(), bufferLength2); - PTF_ASSERT_BUF_COMPARE(echoReplyPacket.getRawPacket()->getRawData()+54, buffer2+54, bufferLength2-54); + PTF_ASSERT_BUF_COMPARE(echoReplyPacket.getRawPacket()->getRawData() + 54, buffer2 + 54, bufferLength2 - 54); // Neighbor solicitation with source link-layer option - pcpp::IPv6Layer *ipv6SoliLayer = new pcpp::IPv6Layer(pcpp::IPv6Address("fd53:7cb8:383:4::67"), pcpp::IPv6Address("fd53:7cb8:383:2::1:117")); + pcpp::IPv6Layer* ipv6SoliLayer = + new pcpp::IPv6Layer(pcpp::IPv6Address("fd53:7cb8:383:4::67"), pcpp::IPv6Address("fd53:7cb8:383:2::1:117")); ipv6SoliLayer->getIPv6Header()->hopLimit = 255; - pcpp::NDPNeighborSolicitationLayer *ndpSoliLayer = new pcpp::NDPNeighborSolicitationLayer(0, pcpp::IPv6Address("fd53:7cb8:383:2::1:117"), pcpp::MacAddress("00:54:af:e9:4d:80")); + pcpp::NDPNeighborSolicitationLayer* ndpSoliLayer = new pcpp::NDPNeighborSolicitationLayer( + 0, pcpp::IPv6Address("fd53:7cb8:383:2::1:117"), pcpp::MacAddress("00:54:af:e9:4d:80")); pcpp::Packet neighSoliPacket(100); PTF_ASSERT_TRUE(neighSoliPacket.addLayer(ipv6SoliLayer, true)); PTF_ASSERT_TRUE(neighSoliPacket.addLayer(ndpSoliLayer, true)); neighSoliPacket.computeCalculateFields(); - PTF_ASSERT_BUF_COMPARE(neighSoliPacket.getRawPacket()->getRawData()+6, buffer3+24, bufferLength3-28); // dat file contains frame with eth + vlan layer (14 + 4 bytes) and trailing bytes (4 bytes) + PTF_ASSERT_BUF_COMPARE( + neighSoliPacket.getRawPacket()->getRawData() + 6, buffer3 + 24, + bufferLength3 - + 28); // dat file contains frame with eth + vlan layer (14 + 4 bytes) and trailing bytes (4 bytes) - pcpp::NDPNeighborSolicitationLayer *neighSoliLayer = neighSoliPacket.getLayerOfType(); + pcpp::NDPNeighborSolicitationLayer* neighSoliLayer = + neighSoliPacket.getLayerOfType(); PTF_ASSERT_EQUAL(neighSoliLayer->getHeaderLen(), 32); PTF_ASSERT_EQUAL((int)neighSoliLayer->getMessageType(), 135); PTF_ASSERT_EQUAL(neighSoliLayer->getCode(), 0); @@ -218,21 +241,25 @@ PTF_TEST_CASE(IcmpV6CreationTest) PTF_ASSERT_EQUAL(neighSoliLayer->getTargetIP(), pcpp::IPv6Address("fd53:7cb8:383:2::1:117")); PTF_ASSERT_EQUAL(neighSoliLayer->getNdpOptionCount(), 1); PTF_ASSERT_EQUAL(neighSoliLayer->getLinkLayerAddress(), pcpp::MacAddress("00:54:af:e9:4d:80")); - pcpp::NdpOption sourceLinkLayerOption = neighSoliLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_SOURCE_LINK_LAYER); + pcpp::NdpOption sourceLinkLayerOption = + neighSoliLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_SOURCE_LINK_LAYER); PTF_ASSERT_TRUE(sourceLinkLayerOption.isNotNull()); PTF_ASSERT_EQUAL(sourceLinkLayerOption.getDataSize(), 6); PTF_ASSERT_EQUAL(sourceLinkLayerOption.getTotalSize(), 8); // Neighbor advertisement with target link-layer option - pcpp::IPv6Layer *ipv6AdvLayer = new pcpp::IPv6Layer(pcpp::IPv6Address("fe80::c000:54ff:fef5:0"), pcpp::IPv6Address("ff02::1")); - pcpp::NDPNeighborAdvertisementLayer *ndpAdvLayer = new pcpp::NDPNeighborAdvertisementLayer(0, pcpp::IPv6Address("fe80::c000:54ff:fef5:0"), pcpp::MacAddress("c2:00:54:f5:00:00"), true, false, true); + pcpp::IPv6Layer* ipv6AdvLayer = + new pcpp::IPv6Layer(pcpp::IPv6Address("fe80::c000:54ff:fef5:0"), pcpp::IPv6Address("ff02::1")); + pcpp::NDPNeighborAdvertisementLayer* ndpAdvLayer = new pcpp::NDPNeighborAdvertisementLayer( + 0, pcpp::IPv6Address("fe80::c000:54ff:fef5:0"), pcpp::MacAddress("c2:00:54:f5:00:00"), true, false, true); pcpp::Packet neighAdvPacket(100); PTF_ASSERT_TRUE(neighAdvPacket.addLayer(ipv6AdvLayer, true)); PTF_ASSERT_TRUE(neighAdvPacket.addLayer(ndpAdvLayer, true)); neighAdvPacket.computeCalculateFields(); - PTF_ASSERT_BUF_COMPARE(neighAdvPacket.getRawPacket()->getRawData()+40, buffer4+54, bufferLength4-54); + PTF_ASSERT_BUF_COMPARE(neighAdvPacket.getRawPacket()->getRawData() + 40, buffer4 + 54, bufferLength4 - 54); - pcpp::NDPNeighborAdvertisementLayer *neighAdvLayer = neighAdvPacket.getLayerOfType(); + pcpp::NDPNeighborAdvertisementLayer* neighAdvLayer = + neighAdvPacket.getLayerOfType(); PTF_ASSERT_EQUAL(neighAdvLayer->getHeaderLen(), 32); PTF_ASSERT_EQUAL((int)neighAdvLayer->getMessageType(), 136); PTF_ASSERT_EQUAL(neighAdvLayer->getCode(), 0); @@ -243,21 +270,26 @@ PTF_TEST_CASE(IcmpV6CreationTest) PTF_ASSERT_EQUAL(neighAdvLayer->getTargetIP(), pcpp::IPv6Address("fe80::c000:54ff:fef5:0")); PTF_ASSERT_EQUAL(neighAdvLayer->getNdpOptionCount(), 1); PTF_ASSERT_EQUAL(neighAdvLayer->getTargetMac(), pcpp::MacAddress("c2:00:54:f5:00:00")); - pcpp::NdpOption targetLinkLayerOption = neighAdvLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_TARGET_LINK_LAYER); + pcpp::NdpOption targetLinkLayerOption = + neighAdvLayer->getNdpOption(pcpp::NDPNeighborOptionTypes::NDP_OPTION_TARGET_LINK_LAYER); PTF_ASSERT_TRUE(targetLinkLayerOption.isNotNull()); PTF_ASSERT_EQUAL(targetLinkLayerOption.getDataSize(), 6); PTF_ASSERT_EQUAL(targetLinkLayerOption.getTotalSize(), 8); // Neighbor advertisement without option - pcpp::IPv6Layer *ipv6AdvLayer2 = new pcpp::IPv6Layer(pcpp::IPv6Address("fe80:ebeb:ebeb::1"), pcpp::IPv6Address("fe80:ebeb:ebeb::2")); - pcpp::NDPNeighborAdvertisementLayer *ndpAdvLayer2 = new pcpp::NDPNeighborAdvertisementLayer(0, pcpp::IPv6Address("fe80:ebeb:ebeb::1"), false, true, false); + pcpp::IPv6Layer* ipv6AdvLayer2 = + new pcpp::IPv6Layer(pcpp::IPv6Address("fe80:ebeb:ebeb::1"), pcpp::IPv6Address("fe80:ebeb:ebeb::2")); + pcpp::NDPNeighborAdvertisementLayer* ndpAdvLayer2 = + new pcpp::NDPNeighborAdvertisementLayer(0, pcpp::IPv6Address("fe80:ebeb:ebeb::1"), false, true, false); pcpp::Packet neighAdvPacket2(100); PTF_ASSERT_TRUE(neighAdvPacket2.addLayer(ipv6AdvLayer2, true)); PTF_ASSERT_TRUE(neighAdvPacket2.addLayer(ndpAdvLayer2, true)); neighAdvPacket2.computeCalculateFields(); - PTF_ASSERT_BUF_COMPARE(neighAdvPacket2.getRawPacket()->getRawData()+40, buffer5+54, bufferLength5-58); // dat file contains eth layer (14 bytes) and trailing bytes (4 bytes) + PTF_ASSERT_BUF_COMPARE(neighAdvPacket2.getRawPacket()->getRawData() + 40, buffer5 + 54, + bufferLength5 - 58); // dat file contains eth layer (14 bytes) and trailing bytes (4 bytes) - pcpp::NDPNeighborAdvertisementLayer *neighAdvLayer2 = neighAdvPacket2.getLayerOfType(); + pcpp::NDPNeighborAdvertisementLayer* neighAdvLayer2 = + neighAdvPacket2.getLayerOfType(); PTF_ASSERT_EQUAL(neighAdvLayer2->getHeaderLen(), 24); PTF_ASSERT_EQUAL((int)neighAdvLayer2->getMessageType(), 136); PTF_ASSERT_EQUAL(neighAdvLayer2->getCode(), 0); @@ -271,7 +303,8 @@ PTF_TEST_CASE(IcmpV6CreationTest) PTF_ASSERT_EQUAL(neighAdvLayer2->getTargetMac(), pcpp::MacAddress()); // Generic ICMPv6 packet - pcpp::IPv6Layer *ipv6Layer2 = new pcpp::IPv6Layer(pcpp::IPv6Address("fe80::a00:27ff:fed4:10bb"), pcpp::IPv6Address("ff02::16")); + pcpp::IPv6Layer* ipv6Layer2 = + new pcpp::IPv6Layer(pcpp::IPv6Address("fe80::a00:27ff:fed4:10bb"), pcpp::IPv6Address("ff02::16")); ipv6Layer2->getIPv6Header()->hopLimit = 1; std::vector hopByHopExtOptions; @@ -281,41 +314,46 @@ PTF_TEST_CASE(IcmpV6CreationTest) ipv6Layer2->addExtension(newHopByHopHeader); ipv6Layer2->getDataPtr(40)[0] = 0x3a; - uint8_t data2[44] = {0x00, 0x00, 0x00, 0x02, 0x04, 0x00, 0x00, 0x00, 0xff, 0x05, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x04, 0x00, - 0x00, 0x00, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x01, 0x00, 0x02}; + uint8_t data2[44] = { 0x00, 0x00, 0x00, 0x02, 0x04, 0x00, 0x00, 0x00, 0xff, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x04, 0x00, 0x00, 0x00, 0xff, 0x02, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02 }; - pcpp::IcmpV6Layer *icmpV6GenericLayer = new pcpp::IcmpV6Layer(pcpp::ICMPv6MessageType::ICMPv6_MULTICAST_LISTENER_DISCOVERY_REPORTS, 0, data2, 44); + pcpp::IcmpV6Layer* icmpV6GenericLayer = + new pcpp::IcmpV6Layer(pcpp::ICMPv6MessageType::ICMPv6_MULTICAST_LISTENER_DISCOVERY_REPORTS, 0, data2, 44); pcpp::Packet genericIcmpV6Packet(100); genericIcmpV6Packet.addLayer(ipv6Layer2, true); genericIcmpV6Packet.addLayer(icmpV6GenericLayer, true); genericIcmpV6Packet.computeCalculateFields(); - PTF_ASSERT_BUF_COMPARE(genericIcmpV6Packet.getRawPacket()->getRawData(), buffer6+14, bufferLength6-14); + PTF_ASSERT_BUF_COMPARE(genericIcmpV6Packet.getRawPacket()->getRawData(), buffer6 + 14, bufferLength6 - 14); - delete [] buffer1; - delete [] buffer2; - delete [] buffer3; - delete [] buffer4; - delete [] buffer5; - delete [] buffer6; + delete[] buffer1; + delete[] buffer2; + delete[] buffer3; + delete[] buffer4; + delete[] buffer5; + delete[] buffer6; } PTF_TEST_CASE(IcmpV6EditTest) { // Creates neighbor advertisement packet without option, adds two options and removes options afterwards. - // Note: This is not a real packet, because neighbor advertisement packet can only contain one target link-layer option - // but for testing NDP options and if padding bytes are handled correct (each option must be padded to 64-bit boundary) - pcpp::IPv6Layer *ipv6AdvLayer = new pcpp::IPv6Layer(pcpp::IPv6Address("fe80::c000:54ff:fef5:0"), pcpp::IPv6Address("ff02::1")); - pcpp::NDPNeighborAdvertisementLayer *ndpAdvLayer = new pcpp::NDPNeighborAdvertisementLayer(0, pcpp::IPv6Address("fe80::c000:54ff:fef5:0"), true, false, true); + // Note: This is not a real packet, because neighbor advertisement packet can only contain one target link-layer + // option but for testing NDP options and if padding bytes are handled correct (each option must be padded to 64-bit + // boundary) + pcpp::IPv6Layer* ipv6AdvLayer = + new pcpp::IPv6Layer(pcpp::IPv6Address("fe80::c000:54ff:fef5:0"), pcpp::IPv6Address("ff02::1")); + pcpp::NDPNeighborAdvertisementLayer* ndpAdvLayer = + new pcpp::NDPNeighborAdvertisementLayer(0, pcpp::IPv6Address("fe80::c000:54ff:fef5:0"), true, false, true); pcpp::Packet neighAdvPacket(100); PTF_ASSERT_TRUE(neighAdvPacket.addLayer(ipv6AdvLayer, true)); PTF_ASSERT_TRUE(neighAdvPacket.addLayer(ndpAdvLayer, true)); - pcpp::NDPNeighborAdvertisementLayer *neighAdvLayer = neighAdvPacket.getLayerOfType(); + pcpp::NDPNeighborAdvertisementLayer* neighAdvLayer = + neighAdvPacket.getLayerOfType(); - uint8_t dataOption1[6] = {0xc2, 0x00, 0x54, 0xf5, 0x01, 0x02}; - neighAdvLayer->addNdpOption(pcpp::NdpOptionBuilder(pcpp::NDPNeighborOptionTypes::NDP_OPTION_TARGET_LINK_LAYER, dataOption1, 4)); // datalen is set to 4 -> for testing padding + uint8_t dataOption1[6] = { 0xc2, 0x00, 0x54, 0xf5, 0x01, 0x02 }; + neighAdvLayer->addNdpOption(pcpp::NdpOptionBuilder(pcpp::NDPNeighborOptionTypes::NDP_OPTION_TARGET_LINK_LAYER, + dataOption1, 4)); // datalen is set to 4 -> for testing padding PTF_ASSERT_EQUAL(neighAdvLayer->getNdpOptionCount(), 1); PTF_ASSERT_EQUAL(neighAdvLayer->getHeaderLen(), 32); pcpp::NdpOption option1 = neighAdvLayer->getFirstNdpOption(); @@ -327,8 +365,9 @@ PTF_TEST_CASE(IcmpV6EditTest) neighAdvPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(neighAdvLayer->getChecksum(), 0x9abb); - uint8_t dataOption2[6] = {0xc2, 0x00, 0x54, 0xf5, 0x01, 0x02}; - neighAdvLayer->addNdpOption(pcpp::NdpOptionBuilder(pcpp::NDPNeighborOptionTypes::NDP_OPTION_SOURCE_LINK_LAYER, dataOption2, 5)); // datalen is set to 5 -> for testing padding + uint8_t dataOption2[6] = { 0xc2, 0x00, 0x54, 0xf5, 0x01, 0x02 }; + neighAdvLayer->addNdpOption(pcpp::NdpOptionBuilder(pcpp::NDPNeighborOptionTypes::NDP_OPTION_SOURCE_LINK_LAYER, + dataOption2, 5)); // datalen is set to 5 -> for testing padding PTF_ASSERT_EQUAL(neighAdvLayer->getNdpOptionCount(), 2); PTF_ASSERT_EQUAL(neighAdvLayer->getHeaderLen(), 40); pcpp::NdpOption option2 = neighAdvLayer->getNextNdpOption(option1); diff --git a/Tests/Packet++Test/Tests/IgmpTests.cpp b/Tests/Packet++Test/Tests/IgmpTests.cpp index 5c07bbd299..8c02625bc9 100644 --- a/Tests/Packet++Test/Tests/IgmpTests.cpp +++ b/Tests/Packet++Test/Tests/IgmpTests.cpp @@ -8,7 +8,6 @@ #include "IgmpLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(IgmpParsingTest) { timeval time; @@ -39,9 +38,7 @@ PTF_TEST_CASE(IgmpParsingTest) PTF_ASSERT_EQUAL(igmpv2Layer->getType(), pcpp::IgmpType_MembershipReportV2, enum); PTF_ASSERT_EQUAL(igmpv2Layer->getGroupAddress(), pcpp::IPv4Address("239.255.255.250")); PTF_ASSERT_EQUAL(igmpv2Layer->toString(), "IGMPv2 Layer, Membership Report message"); -} // IgmpParsingTest - - +} // IgmpParsingTest PTF_TEST_CASE(IgmpCreateAndEditTest) { @@ -84,11 +81,13 @@ PTF_TEST_CASE(IgmpCreateAndEditTest) READ_FILE_INTO_BUFFER(1, "PacketExamples/IGMPv1_1.dat"); READ_FILE_INTO_BUFFER(2, "PacketExamples/IGMPv2_1.dat"); - PTF_ASSERT_EQUAL(igmpv1Packet.getRawPacket()->getRawDataLen(), bufferLength1-14); - PTF_ASSERT_BUF_COMPARE(igmpv1Packet.getRawPacket()->getRawData(), buffer1, igmpv1Packet.getRawPacket()->getRawDataLen()); + PTF_ASSERT_EQUAL(igmpv1Packet.getRawPacket()->getRawDataLen(), bufferLength1 - 14); + PTF_ASSERT_BUF_COMPARE(igmpv1Packet.getRawPacket()->getRawData(), buffer1, + igmpv1Packet.getRawPacket()->getRawDataLen()); - PTF_ASSERT_EQUAL(igmpv2Packet.getRawPacket()->getRawDataLen(), bufferLength2-14); - PTF_ASSERT_BUF_COMPARE(igmpv2Packet.getRawPacket()->getRawData(), buffer2, igmpv2Packet.getRawPacket()->getRawDataLen()); + PTF_ASSERT_EQUAL(igmpv2Packet.getRawPacket()->getRawDataLen(), bufferLength2 - 14); + PTF_ASSERT_BUF_COMPARE(igmpv2Packet.getRawPacket()->getRawData(), buffer2, + igmpv2Packet.getRawPacket()->getRawDataLen()); pcpp::IgmpV1Layer* igmpLayer = igmpv1Packet.getLayerOfType(); igmpLayer->setType(pcpp::IgmpType_MembershipReportV2); @@ -97,11 +96,9 @@ PTF_TEST_CASE(IgmpCreateAndEditTest) PTF_ASSERT_BUF_COMPARE(igmpLayer->getData(), igmpV2Layer.getData(), igmpLayer->getHeaderLen()); - delete [] buffer1; - delete [] buffer2; -} // IgmpCreateAndEditTest - - + delete[] buffer1; + delete[] buffer2; +} // IgmpCreateAndEditTest PTF_TEST_CASE(Igmpv3ParsingTest) { @@ -138,7 +135,6 @@ PTF_TEST_CASE(Igmpv3ParsingTest) PTF_ASSERT_EQUAL(igmpv3QueryLayer->getSourceAddressAtIndex(50).toString(), "0.0.0.0"); PTF_ASSERT_EQUAL(igmpv3QueryLayer->getSourceAddressAtIndex(-1).toString(), "0.0.0.0"); - PTF_ASSERT_TRUE(igmpv3ReportPacket.isPacketOfType(pcpp::IGMPv3)); PTF_ASSERT_TRUE(igmpv3ReportPacket.isPacketOfType(pcpp::IGMP)); PTF_ASSERT_FALSE(igmpv3ReportPacket.isPacketOfType(pcpp::IGMPv1)); @@ -159,9 +155,7 @@ PTF_TEST_CASE(Igmpv3ParsingTest) curGroup = igmpv3ReportLayer->getNextGroupRecord(curGroup); PTF_ASSERT_NULL(curGroup); PTF_ASSERT_EQUAL(igmpv3ReportLayer->toString(), "IGMPv3 Layer, Membership Report message"); -} // Igmpv3ParsingTest - - +} // Igmpv3ParsingTest PTF_TEST_CASE(Igmpv3QueryCreateAndEditTest) { @@ -211,7 +205,8 @@ PTF_TEST_CASE(Igmpv3QueryCreateAndEditTest) READ_FILE_INTO_BUFFER(1, "PacketExamples/igmpv3_query2.dat"); PTF_ASSERT_EQUAL(igmpv3QueryPacket.getRawPacket()->getRawDataLen(), bufferLength1); - PTF_ASSERT_BUF_COMPARE(igmpv3QueryPacket.getRawPacket()->getRawData(), buffer1, igmpv3QueryPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(igmpv3QueryPacket.getRawPacket()->getRawData(), buffer1, + igmpv3QueryPacket.getRawPacket()->getRawDataLen()); delete[] buffer1; @@ -238,14 +233,13 @@ PTF_TEST_CASE(Igmpv3QueryCreateAndEditTest) READ_FILE_INTO_BUFFER(2, "PacketExamples/igmpv3_query.dat"); PTF_ASSERT_EQUAL(igmpv3QueryPacket.getRawPacket()->getRawDataLen(), bufferLength2); - PTF_ASSERT_BUF_COMPARE(igmpv3QueryPacket.getRawPacket()->getRawData(), buffer2, igmpv3QueryPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(igmpv3QueryPacket.getRawPacket()->getRawData(), buffer2, + igmpv3QueryPacket.getRawPacket()->getRawDataLen()); delete[] buffer2; PTF_ASSERT_TRUE(igmpV3QueryLayer.removeAllSourceAddresses()); -} // Igmpv3QueryCreateAndEditTest - - +} // Igmpv3QueryCreateAndEditTest PTF_TEST_CASE(Igmpv3ReportCreateAndEditTest) { @@ -262,7 +256,8 @@ PTF_TEST_CASE(Igmpv3ReportCreateAndEditTest) std::vector srcAddrVec1; srcAddrVec1.push_back(pcpp::IPv4Address("192.168.20.222")); - pcpp::igmpv3_group_record* groupRec = igmpV3ReportLayer.addGroupRecord(1, pcpp::IPv4Address("224.0.0.9"), srcAddrVec1); + pcpp::igmpv3_group_record* groupRec = + igmpV3ReportLayer.addGroupRecord(1, pcpp::IPv4Address("224.0.0.9"), srcAddrVec1); PTF_ASSERT_NOT_NULL(groupRec); PTF_ASSERT_EQUAL(groupRec->getSourceAddressAtIndex(0), pcpp::IPv4Address("192.168.20.222")); @@ -298,7 +293,6 @@ PTF_TEST_CASE(Igmpv3ReportCreateAndEditTest) groupRec = igmpV3ReportLayer.addGroupRecordAtIndex(5, pcpp::IPv4Address("2.4.6.8"), srcAddrVec4, 4); PTF_ASSERT_NOT_NULL(groupRec); - pcpp::Packet igmpv3ReportPacket; PTF_ASSERT_TRUE(igmpv3ReportPacket.addLayer(ðLayer)); PTF_ASSERT_TRUE(igmpv3ReportPacket.addLayer(&ipLayer)); @@ -309,11 +303,11 @@ PTF_TEST_CASE(Igmpv3ReportCreateAndEditTest) READ_FILE_INTO_BUFFER(1, "PacketExamples/igmpv3_report2.dat"); PTF_ASSERT_EQUAL(igmpv3ReportPacket.getRawPacket()->getRawDataLen(), bufferLength1); - PTF_ASSERT_BUF_COMPARE(igmpv3ReportPacket.getRawPacket()->getRawData(), buffer1, igmpv3ReportPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(igmpv3ReportPacket.getRawPacket()->getRawData(), buffer1, + igmpv3ReportPacket.getRawPacket()->getRawDataLen()); delete[] buffer1; - PTF_ASSERT_TRUE(igmpV3ReportLayer.removeGroupRecordAtIndex(4)); pcpp::Logger::getInstance().suppressLogs(); @@ -333,9 +327,10 @@ PTF_TEST_CASE(Igmpv3ReportCreateAndEditTest) igmpv3ReportPacket.computeCalculateFields(); ipLayer.getIPv4Header()->headerChecksum = 0x4fb6; - PTF_ASSERT_BUF_COMPARE(igmpv3ReportPacket.getRawPacket()->getRawData(), buffer2, igmpv3ReportPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(igmpv3ReportPacket.getRawPacket()->getRawData(), buffer2, + igmpv3ReportPacket.getRawPacket()->getRawDataLen()); delete[] buffer2; PTF_ASSERT_TRUE(igmpV3ReportLayer.removeAllGroupRecords()); -} // Igmpv3ReportCreateAndEditTest +} // Igmpv3ReportCreateAndEditTest diff --git a/Tests/Packet++Test/Tests/LLCTests.cpp b/Tests/Packet++Test/Tests/LLCTests.cpp index 6869ae9ea4..0d62a5c518 100644 --- a/Tests/Packet++Test/Tests/LLCTests.cpp +++ b/Tests/Packet++Test/Tests/LLCTests.cpp @@ -17,10 +17,10 @@ PTF_TEST_CASE(LLCParsingTests) pcpp::Packet llcPacket1(&rawPacket1); PTF_ASSERT_TRUE(llcPacket1.isPacketOfType(pcpp::LLC)); - pcpp::LLCLayer *llcLayer1 = llcPacket1.getLayerOfType(); + pcpp::LLCLayer* llcLayer1 = llcPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(llcLayer1); - pcpp::llc_header *header1 = llcLayer1->getLlcHeader(); + pcpp::llc_header* header1 = llcLayer1->getLlcHeader(); PTF_ASSERT_EQUAL(header1->dsap, 0x42); PTF_ASSERT_EQUAL(header1->ssap, 0x42); PTF_ASSERT_EQUAL(header1->control, 0x3); @@ -32,15 +32,15 @@ PTF_TEST_CASE(LLCParsingTests) READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/llc_vlan.dat"); pcpp::Packet llcPacket2(&rawPacket2); - pcpp::LLCLayer *llcLayer2 = llcPacket2.getLayerOfType(); + pcpp::LLCLayer* llcLayer2 = llcPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(llcLayer2); - pcpp::llc_header *header2 = llcLayer2->getLlcHeader(); + pcpp::llc_header* header2 = llcLayer2->getLlcHeader(); PTF_ASSERT_EQUAL(header2->dsap, 0xaa); PTF_ASSERT_EQUAL(header2->ssap, 0xaa); PTF_ASSERT_EQUAL(header2->control, 0x3); -} // LLCParsingTests +} // LLCParsingTests PTF_TEST_CASE(LLCCreationTests) { @@ -52,9 +52,9 @@ PTF_TEST_CASE(LLCCreationTests) pcpp::Packet llcPacket1(&rawPacket1); PTF_ASSERT_TRUE(llcPacket1.isPacketOfType(pcpp::LLC)); - pcpp::LLCLayer *llcLayer1 = llcPacket1.getLayerOfType(); + pcpp::LLCLayer* llcLayer1 = llcPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(llcLayer1); pcpp::LLCLayer craftedLayer1(0x42, 0x42, 0x3); PTF_ASSERT_BUF_COMPARE(llcLayer1->getData(), craftedLayer1.getData(), craftedLayer1.getDataLen()); -} // LLCCreationTests +} // LLCCreationTests diff --git a/Tests/Packet++Test/Tests/LdapTests.cpp b/Tests/Packet++Test/Tests/LdapTests.cpp index e57f5b2aab..63515067a5 100644 --- a/Tests/Packet++Test/Tests/LdapTests.cpp +++ b/Tests/Packet++Test/Tests/LdapTests.cpp @@ -31,9 +31,10 @@ PTF_TEST_CASE(LdapParsingTest) pcpp::Asn1EnumeratedRecord enumeratedRecord(0); pcpp::Asn1OctetStringRecord stringRecord1(""); pcpp::Asn1OctetStringRecord stringRecord2(""); - pcpp::Asn1ConstructedRecord expectedOperationRecord(pcpp::Asn1TagClass::Application, 9, {&enumeratedRecord, &stringRecord1, &stringRecord2}); + pcpp::Asn1ConstructedRecord expectedOperationRecord(pcpp::Asn1TagClass::Application, 9, + { &enumeratedRecord, &stringRecord1, &stringRecord2 }); - pcpp::Asn1SequenceRecord expectedRootRecord({&messageIdRecord, &expectedOperationRecord}); + pcpp::Asn1SequenceRecord expectedRootRecord({ &messageIdRecord, &expectedOperationRecord }); PTF_ASSERT_EQUAL(ldapLayer->getRootAsn1Record()->toString(), expectedRootRecord.toString()); PTF_ASSERT_EQUAL(ldapLayer->getLdapOperationAsn1Record()->toString(), expectedOperationRecord.toString()); @@ -49,8 +50,8 @@ PTF_TEST_CASE(LdapParsingTest) auto controls = ldapLayer->getControls(); std::vector expectedControls = { - {"1.2.840.113556.1.4.801", "3003020107"}, - {"1.2.840.113556.1.4.319", "3006020201f40400"} + { "1.2.840.113556.1.4.801", "3003020107" }, + { "1.2.840.113556.1.4.319", "3006020201f40400" } }; PTF_ASSERT_VECTORS_EQUAL(controls, expectedControls); } @@ -64,7 +65,7 @@ PTF_TEST_CASE(LdapParsingTest) PTF_ASSERT_NOT_NULL(ldapLayer); auto controls = ldapLayer->getControls(); - std::vector expectedControls = {{"1.3.6.1.4.1.42.2.27.8.5.1"}}; + std::vector expectedControls = { { "1.3.6.1.4.1.42.2.27.8.5.1" } }; PTF_ASSERT_VECTORS_EQUAL(controls, expectedControls); } @@ -82,7 +83,7 @@ PTF_TEST_CASE(LdapParsingTest) std::vector controls; PTF_ASSERT_TRUE(malformedLdapLayer->tryGet(&pcpp::LdapLayer::getControls, controls)); - std::vector expectedControls = {{"1.3.6.1.4.1.42.2.27.8.5.1"}}; + std::vector expectedControls = { { "1.3.6.1.4.1.42.2.27.8.5.1" } }; PTF_ASSERT_VECTORS_EQUAL(controls, expectedControls); } @@ -116,11 +117,14 @@ PTF_TEST_CASE(LdapParsingTest) PTF_ASSERT_EQUAL(bindRequestLayer->getLdapOperationType(), pcpp::LdapOperationType::BindRequest, enum); PTF_ASSERT_EQUAL(bindRequestLayer->getVersion(), 3); PTF_ASSERT_EQUAL(bindRequestLayer->getName(), "cn=Administrator,cn=Users,dc=cloudshark-a,dc=example,dc=com"); - PTF_ASSERT_EQUAL(bindRequestLayer->getAuthenticationType(), pcpp::LdapBindRequestLayer::AuthenticationType::Simple, enumclass); + PTF_ASSERT_EQUAL(bindRequestLayer->getAuthenticationType(), + pcpp::LdapBindRequestLayer::AuthenticationType::Simple, enumclass); PTF_ASSERT_EQUAL(bindRequestLayer->getSimpleAuthentication(), "cloudshark123!"); - PTF_ASSERT_RAISES(bindRequestLayer->getSaslAuthentication(), std::invalid_argument, "Authentication type is not sasl"); + PTF_ASSERT_RAISES(bindRequestLayer->getSaslAuthentication(), std::invalid_argument, + "Authentication type is not sasl"); pcpp::LdapBindRequestLayer::SaslAuthentication saslAuthentication; - PTF_ASSERT_FALSE(bindRequestLayer->tryGet(&pcpp::LdapBindRequestLayer::getSaslAuthentication, saslAuthentication)); + PTF_ASSERT_FALSE( + bindRequestLayer->tryGet(&pcpp::LdapBindRequestLayer::getSaslAuthentication, saslAuthentication)); PTF_ASSERT_EQUAL(bindRequestLayer->toString(), "LDAP Layer, BindRequest, simple"); } @@ -135,49 +139,95 @@ PTF_TEST_CASE(LdapParsingTest) PTF_ASSERT_EQUAL(bindRequestLayer->getLdapOperationType(), pcpp::LdapOperationType::BindRequest, enum); PTF_ASSERT_EQUAL(bindRequestLayer->getVersion(), 3); PTF_ASSERT_EQUAL(bindRequestLayer->getName(), ""); - PTF_ASSERT_EQUAL(bindRequestLayer->getAuthenticationType(), pcpp::LdapBindRequestLayer::AuthenticationType::Sasl, enumclass); - pcpp::LdapBindRequestLayer::SaslAuthentication expectedSaslAuthentication { + PTF_ASSERT_EQUAL(bindRequestLayer->getAuthenticationType(), + pcpp::LdapBindRequestLayer::AuthenticationType::Sasl, enumclass); + pcpp::LdapBindRequestLayer::SaslAuthentication expectedSaslAuthentication{ "GSS-SPNEGO", - {0x60, 0x82, 0x05, 0x1a, 0x06, 0x06, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02, 0xa0, 0x82, 0x05, 0x0e, 0x30, 0x82, 0x05, 0x0a, 0xa0, 0x24, 0x30, 0x22, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x06, 0x09, 0x2a, - 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0a, 0xa2, 0x82, 0x04, 0xe0, 0x04, 0x82, 0x04, 0xdc, 0x60, 0x82, 0x04, 0xd8, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, - 0xf7, 0x12, 0x01, 0x02, 0x02, 0x01, 0x00, 0x6e, 0x82, 0x04, 0xc7, 0x30, 0x82, 0x04, 0xc3, 0xa0, 0x03, 0x02, 0x01, 0x05, 0xa1, 0x03, 0x02, 0x01, 0x0e, 0xa2, 0x07, 0x03, 0x05, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa3, 0x82, 0x03, 0xe0, - 0x61, 0x82, 0x03, 0xdc, 0x30, 0x82, 0x03, 0xd8, 0xa0, 0x03, 0x02, 0x01, 0x05, 0xa1, 0x15, 0x1b, 0x13, 0x57, 0x32, 0x4b, 0x33, 0x2e, 0x56, 0x4d, 0x4e, 0x45, 0x54, 0x31, 0x2e, 0x56, 0x4d, 0x2e, 0x42, 0x41, 0x53, 0x45, 0xa2, 0x2f, - 0x30, 0x2d, 0xa0, 0x03, 0x02, 0x01, 0x02, 0xa1, 0x26, 0x30, 0x24, 0x1b, 0x04, 0x6c, 0x64, 0x61, 0x70, 0x1b, 0x1c, 0x77, 0x32, 0x6b, 0x33, 0x2d, 0x31, 0x30, 0x31, 0x2e, 0x77, 0x32, 0x6b, 0x33, 0x2e, 0x76, 0x6d, 0x6e, 0x65, 0x74, - 0x31, 0x2e, 0x76, 0x6d, 0x2e, 0x62, 0x61, 0x73, 0x65, 0xa3, 0x82, 0x03, 0x87, 0x30, 0x82, 0x03, 0x83, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa1, 0x03, 0x02, 0x01, 0x07, 0xa2, 0x82, 0x03, 0x75, 0x04, 0x82, 0x03, 0x71, 0x6a, 0x61, 0xc8, - 0x86, 0xba, 0x58, 0xd1, 0x62, 0x11, 0x3d, 0xb4, 0x26, 0x8f, 0x77, 0x43, 0xa1, 0x7e, 0xb4, 0x76, 0x18, 0x3b, 0xc0, 0xc5, 0x19, 0xad, 0xde, 0xa7, 0x65, 0x56, 0xa3, 0x70, 0x1d, 0xe3, 0x49, 0x03, 0xe6, 0xbd, 0x3f, 0x3f, 0xdc, 0xa0, - 0xb0, 0x1b, 0xbc, 0xcb, 0x9a, 0x86, 0x93, 0xb2, 0x3f, 0xa8, 0xd1, 0x98, 0x5e, 0x14, 0x92, 0x2e, 0x4c, 0xa1, 0x9b, 0x05, 0xa9, 0x07, 0x69, 0x84, 0x5a, 0x58, 0x58, 0x51, 0x5b, 0xba, 0x4a, 0xf2, 0xd7, 0xe5, 0x9b, 0xfa, 0x86, 0x34, - 0x28, 0x5a, 0x2e, 0x95, 0x4f, 0xb5, 0x18, 0x37, 0x8b, 0x8d, 0x3f, 0x27, 0x44, 0xb9, 0xbb, 0xf8, 0x84, 0x2b, 0x48, 0x07, 0x87, 0x9f, 0xf2, 0x8e, 0x55, 0xbf, 0xba, 0x49, 0x67, 0xe8, 0xc1, 0xd3, 0xb6, 0xc4, 0xe3, 0x58, 0xa5, 0x61, - 0xc5, 0x4a, 0xbb, 0xc1, 0xcb, 0x7c, 0x97, 0xb6, 0x50, 0x3f, 0xe5, 0x9b, 0x7f, 0xee, 0x64, 0x23, 0xdf, 0xfe, 0x66, 0xfe, 0x6d, 0xcb, 0x8a, 0xf0, 0x0e, 0x69, 0xc5, 0x3d, 0x6b, 0x57, 0x6f, 0x55, 0x06, 0x99, 0x04, 0x38, 0x31, 0x0f, - 0xb7, 0xdd, 0x14, 0x68, 0xa3, 0x2f, 0xd8, 0xe0, 0xde, 0xab, 0x40, 0xb1, 0x5e, 0xcf, 0xd4, 0x38, 0x56, 0x83, 0x70, 0x14, 0x0a, 0x1e, 0xda, 0xfe, 0xe7, 0x01, 0xa4, 0xa4, 0xb4, 0xe7, 0xb3, 0xaa, 0xef, 0xdc, 0x4b, 0x1a, 0xff, 0x58, - 0x68, 0xae, 0xfe, 0x5a, 0x36, 0x29, 0x4d, 0x5d, 0xd6, 0x87, 0xd5, 0xa6, 0x49, 0x31, 0x43, 0xd3, 0xad, 0xe8, 0x03, 0x1c, 0x98, 0xd2, 0x8f, 0x6c, 0x7f, 0x3d, 0xce, 0xa4, 0x14, 0x35, 0x13, 0x2f, 0x67, 0x5f, 0x26, 0x94, 0x0d, 0x1f, - 0x69, 0xe5, 0x73, 0xe5, 0xec, 0xe6, 0xed, 0x5a, 0x66, 0x11, 0x1f, 0xf9, 0xf4, 0xb0, 0x2a, 0x8d, 0xdd, 0x19, 0x08, 0x6e, 0x5b, 0x9d, 0xc0, 0xad, 0xc8, 0x6a, 0x0b, 0xc1, 0x23, 0x0f, 0x1b, 0x71, 0x5f, 0xfc, 0x40, 0x04, 0xdf, 0xc4, - 0xa7, 0xd5, 0xf7, 0x8a, 0x4d, 0xc3, 0x1a, 0xbf, 0x83, 0x0a, 0xe6, 0xe3, 0xbf, 0xd2, 0x1c, 0x87, 0xfa, 0x51, 0x96, 0x54, 0x9e, 0x13, 0x0f, 0x6a, 0x08, 0x1b, 0xaf, 0xcf, 0x41, 0x70, 0xae, 0x20, 0x1c, 0x78, 0xa3, 0x82, 0x9a, 0x01, - 0xdb, 0xa5, 0x78, 0xa2, 0xef, 0x96, 0x8f, 0x2a, 0xb6, 0x66, 0x8d, 0x81, 0x14, 0xdf, 0xcc, 0x65, 0xd7, 0x03, 0x8f, 0x55, 0x58, 0xbe, 0x7c, 0xdd, 0x92, 0x46, 0xd5, 0x22, 0x47, 0x91, 0x52, 0x60, 0xa4, 0x0e, 0x59, 0xc4, 0x8b, 0x08, - 0xa1, 0xed, 0x61, 0x42, 0x7f, 0xd3, 0x03, 0x91, 0x7c, 0x6b, 0x34, 0xb7, 0x01, 0xa4, 0xba, 0x9a, 0x38, 0x15, 0xd4, 0x82, 0x8a, 0x22, 0x8c, 0xd2, 0x09, 0xda, 0x13, 0x76, 0x26, 0xe2, 0x02, 0x9a, 0xab, 0xf6, 0xc2, 0x00, 0xbf, 0x7f, - 0xd6, 0x3c, 0xf6, 0xd4, 0x3b, 0xb6, 0x18, 0xb3, 0x1a, 0xc4, 0x8e, 0x09, 0x61, 0x35, 0x89, 0xd7, 0x4a, 0x69, 0x54, 0x2e, 0x90, 0x9c, 0xe0, 0xdc, 0x9c, 0x57, 0xc7, 0x7f, 0x7d, 0x89, 0xb9, 0x66, 0xde, 0x20, 0x00, 0x53, 0xa5, 0x8e, - 0xa5, 0x8f, 0x23, 0x74, 0x51, 0x39, 0x61, 0x63, 0x8a, 0x30, 0xca, 0x49, 0xef, 0x0e, 0xec, 0x67, 0x9d, 0x92, 0x7e, 0x38, 0x5b, 0x5d, 0xa7, 0xd4, 0xd3, 0xc1, 0xa5, 0x91, 0x69, 0xb4, 0x63, 0x0b, 0x87, 0x4a, 0x1d, 0x96, 0x9e, 0x45, - 0xd1, 0xfe, 0x37, 0x82, 0x08, 0x9f, 0x43, 0x85, 0x02, 0x49, 0x55, 0x09, 0x3b, 0x30, 0x8e, 0x19, 0x64, 0xd3, 0x07, 0x91, 0x52, 0x71, 0xaa, 0x88, 0x6c, 0x3d, 0x9b, 0x64, 0xd8, 0x46, 0xc8, 0x8c, 0xa1, 0x34, 0x1f, 0xd2, 0xf7, 0x2b, - 0x76, 0x67, 0x9d, 0x4f, 0x25, 0x8f, 0x64, 0x7b, 0xc0, 0x48, 0x20, 0xe4, 0x27, 0x76, 0xc9, 0xec, 0x0d, 0x01, 0x46, 0x46, 0x52, 0x76, 0x3a, 0x49, 0xd8, 0x22, 0xc9, 0xd2, 0x5b, 0x60, 0x39, 0x03, 0xeb, 0xd6, 0x33, 0x89, 0x52, 0x25, - 0x9b, 0x83, 0xa7, 0x40, 0xa4, 0x20, 0xd6, 0x9d, 0x23, 0xae, 0xbb, 0xdf, 0x06, 0xa9, 0x2d, 0x88, 0xa4, 0x6f, 0xfc, 0xd8, 0xd8, 0x1a, 0x47, 0xb6, 0xec, 0x99, 0xb6, 0xce, 0xa0, 0x48, 0x9c, 0xc8, 0x3e, 0xf1, 0x57, 0x57, 0xc4, 0x05, - 0x3d, 0x53, 0x84, 0x46, 0xf2, 0xe6, 0xb9, 0xeb, 0xa1, 0x2c, 0xe4, 0x96, 0x9b, 0x8d, 0x6d, 0xf9, 0xb3, 0xef, 0x57, 0x4b, 0x7d, 0x40, 0x13, 0x41, 0xc2, 0xf5, 0x55, 0xa0, 0x0f, 0x02, 0x91, 0x64, 0xe5, 0xd3, 0x87, 0x28, 0x2c, 0x0c, - 0x87, 0x91, 0xba, 0x8c, 0x69, 0x81, 0x62, 0x48, 0xe2, 0xe5, 0x44, 0xa9, 0xc1, 0x2b, 0x7a, 0xeb, 0xa6, 0x29, 0xfd, 0xee, 0xa2, 0xe1, 0x11, 0x65, 0x5e, 0x44, 0xb9, 0xc2, 0x15, 0x92, 0x4c, 0x54, 0x55, 0xea, 0xa4, 0xab, 0x32, 0xae, - 0xa1, 0xd9, 0xce, 0xf1, 0xd8, 0x6e, 0x8a, 0xcf, 0x6b, 0x0f, 0xf4, 0xdc, 0xab, 0xaf, 0x4f, 0x0e, 0x2d, 0x9a, 0xe6, 0x5c, 0x8b, 0xb1, 0x06, 0x5e, 0x04, 0x18, 0xff, 0x12, 0xd4, 0x62, 0x69, 0x30, 0x31, 0x59, 0x38, 0xbf, 0xe0, 0x0a, - 0x8d, 0x03, 0xe8, 0xe7, 0x0e, 0x9d, 0xea, 0x9d, 0xc9, 0xff, 0x74, 0x85, 0x4c, 0xbb, 0x4d, 0xbd, 0xf7, 0x00, 0xa6, 0x2e, 0x77, 0xb2, 0x6e, 0x50, 0xb1, 0x3e, 0x2d, 0x39, 0x60, 0xc9, 0x13, 0x36, 0x0c, 0x84, 0xc8, 0x7e, 0x80, 0x1e, - 0xd3, 0xdf, 0x3d, 0xb0, 0xe2, 0x76, 0x04, 0x50, 0x8c, 0xb7, 0x30, 0xc5, 0xa0, 0x52, 0xc0, 0x68, 0xab, 0xe5, 0x82, 0x6b, 0x01, 0xbe, 0x9f, 0x62, 0xe3, 0x3b, 0x9a, 0xf8, 0xed, 0xb6, 0x66, 0x7c, 0x57, 0xcb, 0x1a, 0xa8, 0x79, 0x74, - 0x3b, 0x77, 0xa7, 0x43, 0x2f, 0x75, 0xfe, 0x3a, 0xe2, 0x11, 0xf9, 0x6a, 0xf4, 0x1a, 0xde, 0xf1, 0xe1, 0xc5, 0x07, 0x25, 0x6f, 0xe5, 0xfa, 0x2b, 0xcc, 0xab, 0xe5, 0x2c, 0xf8, 0x21, 0x6d, 0x34, 0x10, 0xe6, 0x37, 0x85, 0x06, 0xd4, - 0x27, 0x34, 0x34, 0x58, 0x33, 0x2d, 0x15, 0x3a, 0x77, 0xa1, 0x62, 0xc4, 0xc5, 0xf1, 0x8d, 0x9f, 0x31, 0xb0, 0xc1, 0x42, 0x88, 0x0c, 0xad, 0x22, 0x29, 0x98, 0x17, 0x20, 0x61, 0x5a, 0xb2, 0x6b, 0x7c, 0x13, 0x44, 0x2e, 0x43, 0x17, - 0x8a, 0xad, 0xee, 0x43, 0x65, 0x10, 0xc9, 0x1b, 0xc9, 0xd5, 0xd7, 0x35, 0xeb, 0x94, 0x53, 0xcf, 0x39, 0xce, 0xf5, 0x12, 0x0e, 0x28, 0x60, 0x37, 0x75, 0xf0, 0x48, 0x3f, 0x01, 0xc3, 0xc4, 0x8b, 0x5b, 0x06, 0x0c, 0xa7, 0xf3, 0xa5, - 0x4d, 0x7c, 0x7c, 0x99, 0xa4, 0x81, 0xc9, 0x30, 0x81, 0xc6, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa2, 0x81, 0xbe, 0x04, 0x81, 0xbb, 0x03, 0xab, 0x65, 0x67, 0x60, 0xa3, 0x51, 0x2f, 0xec, 0xc7, 0x03, 0x2d, 0xa8, 0xb2, 0x01, 0x46, 0x59, - 0xf0, 0xfb, 0x34, 0xeb, 0x76, 0xb4, 0x61, 0xe4, 0x04, 0x4d, 0xa2, 0x4d, 0x16, 0xd4, 0x58, 0xe3, 0xe1, 0xc5, 0x89, 0x19, 0xc7, 0x4c, 0x4c, 0x07, 0x20, 0xaa, 0xfb, 0x87, 0xa9, 0x48, 0x15, 0x23, 0x72, 0xa2, 0x48, 0x3a, 0x4d, 0x1a, - 0xe9, 0xb9, 0x5b, 0x85, 0x8a, 0x52, 0xab, 0xaa, 0x94, 0xe7, 0xaa, 0x64, 0x1a, 0x8b, 0x99, 0x7d, 0x7e, 0x6c, 0x6e, 0x57, 0x0b, 0x59, 0x08, 0xcc, 0x54, 0x91, 0x55, 0xf5, 0xe6, 0xf1, 0x10, 0xc9, 0x8d, 0x64, 0x89, 0x78, 0x72, 0x7a, - 0xba, 0xe3, 0x92, 0x1d, 0xa5, 0x2a, 0x4c, 0x1f, 0xd7, 0x6b, 0xeb, 0x12, 0x1b, 0xf3, 0x39, 0x6b, 0xe8, 0xf9, 0x8e, 0x4a, 0xcf, 0x1e, 0xbf, 0xc3, 0xb6, 0xfb, 0x7a, 0x13, 0x54, 0xc1, 0x21, 0x87, 0x3e, 0x59, 0x18, 0x5d, 0xb9, 0x00, - 0x30, 0x08, 0x4d, 0x97, 0x86, 0x47, 0x98, 0xd7, 0x9e, 0xb9, 0xdf, 0x30, 0x75, 0x6c, 0xa1, 0xfa, 0xa7, 0xa8, 0x08, 0x80, 0xf7, 0x4f, 0x7d, 0x93, 0x64, 0x2d, 0x9c, 0xeb, 0x5e, 0x01, 0x28, 0xce, 0xd6, 0xab, 0x09, 0x6a, 0x4f, 0x01, - 0x5e, 0x5a, 0x03, 0x2b, 0x42, 0x70, 0x23, 0x1e, 0x7f, 0xf1, 0xbc, 0xd0, 0x87, 0xe8, 0xb5, 0x27, 0x02, 0x7d} + { 0x60, 0x82, 0x05, 0x1a, 0x06, 0x06, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02, 0xa0, 0x82, 0x05, 0x0e, 0x30, + 0x82, 0x05, 0x0a, 0xa0, 0x24, 0x30, 0x22, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, + 0x02, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x06, 0x0a, 0x2b, 0x06, 0x01, + 0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0a, 0xa2, 0x82, 0x04, 0xe0, 0x04, 0x82, 0x04, 0xdc, 0x60, 0x82, + 0x04, 0xd8, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x01, 0x00, 0x6e, 0x82, + 0x04, 0xc7, 0x30, 0x82, 0x04, 0xc3, 0xa0, 0x03, 0x02, 0x01, 0x05, 0xa1, 0x03, 0x02, 0x01, 0x0e, 0xa2, + 0x07, 0x03, 0x05, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa3, 0x82, 0x03, 0xe0, 0x61, 0x82, 0x03, 0xdc, 0x30, + 0x82, 0x03, 0xd8, 0xa0, 0x03, 0x02, 0x01, 0x05, 0xa1, 0x15, 0x1b, 0x13, 0x57, 0x32, 0x4b, 0x33, 0x2e, + 0x56, 0x4d, 0x4e, 0x45, 0x54, 0x31, 0x2e, 0x56, 0x4d, 0x2e, 0x42, 0x41, 0x53, 0x45, 0xa2, 0x2f, 0x30, + 0x2d, 0xa0, 0x03, 0x02, 0x01, 0x02, 0xa1, 0x26, 0x30, 0x24, 0x1b, 0x04, 0x6c, 0x64, 0x61, 0x70, 0x1b, + 0x1c, 0x77, 0x32, 0x6b, 0x33, 0x2d, 0x31, 0x30, 0x31, 0x2e, 0x77, 0x32, 0x6b, 0x33, 0x2e, 0x76, 0x6d, + 0x6e, 0x65, 0x74, 0x31, 0x2e, 0x76, 0x6d, 0x2e, 0x62, 0x61, 0x73, 0x65, 0xa3, 0x82, 0x03, 0x87, 0x30, + 0x82, 0x03, 0x83, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa1, 0x03, 0x02, 0x01, 0x07, 0xa2, 0x82, 0x03, 0x75, + 0x04, 0x82, 0x03, 0x71, 0x6a, 0x61, 0xc8, 0x86, 0xba, 0x58, 0xd1, 0x62, 0x11, 0x3d, 0xb4, 0x26, 0x8f, + 0x77, 0x43, 0xa1, 0x7e, 0xb4, 0x76, 0x18, 0x3b, 0xc0, 0xc5, 0x19, 0xad, 0xde, 0xa7, 0x65, 0x56, 0xa3, + 0x70, 0x1d, 0xe3, 0x49, 0x03, 0xe6, 0xbd, 0x3f, 0x3f, 0xdc, 0xa0, 0xb0, 0x1b, 0xbc, 0xcb, 0x9a, 0x86, + 0x93, 0xb2, 0x3f, 0xa8, 0xd1, 0x98, 0x5e, 0x14, 0x92, 0x2e, 0x4c, 0xa1, 0x9b, 0x05, 0xa9, 0x07, 0x69, + 0x84, 0x5a, 0x58, 0x58, 0x51, 0x5b, 0xba, 0x4a, 0xf2, 0xd7, 0xe5, 0x9b, 0xfa, 0x86, 0x34, 0x28, 0x5a, + 0x2e, 0x95, 0x4f, 0xb5, 0x18, 0x37, 0x8b, 0x8d, 0x3f, 0x27, 0x44, 0xb9, 0xbb, 0xf8, 0x84, 0x2b, 0x48, + 0x07, 0x87, 0x9f, 0xf2, 0x8e, 0x55, 0xbf, 0xba, 0x49, 0x67, 0xe8, 0xc1, 0xd3, 0xb6, 0xc4, 0xe3, 0x58, + 0xa5, 0x61, 0xc5, 0x4a, 0xbb, 0xc1, 0xcb, 0x7c, 0x97, 0xb6, 0x50, 0x3f, 0xe5, 0x9b, 0x7f, 0xee, 0x64, + 0x23, 0xdf, 0xfe, 0x66, 0xfe, 0x6d, 0xcb, 0x8a, 0xf0, 0x0e, 0x69, 0xc5, 0x3d, 0x6b, 0x57, 0x6f, 0x55, + 0x06, 0x99, 0x04, 0x38, 0x31, 0x0f, 0xb7, 0xdd, 0x14, 0x68, 0xa3, 0x2f, 0xd8, 0xe0, 0xde, 0xab, 0x40, + 0xb1, 0x5e, 0xcf, 0xd4, 0x38, 0x56, 0x83, 0x70, 0x14, 0x0a, 0x1e, 0xda, 0xfe, 0xe7, 0x01, 0xa4, 0xa4, + 0xb4, 0xe7, 0xb3, 0xaa, 0xef, 0xdc, 0x4b, 0x1a, 0xff, 0x58, 0x68, 0xae, 0xfe, 0x5a, 0x36, 0x29, 0x4d, + 0x5d, 0xd6, 0x87, 0xd5, 0xa6, 0x49, 0x31, 0x43, 0xd3, 0xad, 0xe8, 0x03, 0x1c, 0x98, 0xd2, 0x8f, 0x6c, + 0x7f, 0x3d, 0xce, 0xa4, 0x14, 0x35, 0x13, 0x2f, 0x67, 0x5f, 0x26, 0x94, 0x0d, 0x1f, 0x69, 0xe5, 0x73, + 0xe5, 0xec, 0xe6, 0xed, 0x5a, 0x66, 0x11, 0x1f, 0xf9, 0xf4, 0xb0, 0x2a, 0x8d, 0xdd, 0x19, 0x08, 0x6e, + 0x5b, 0x9d, 0xc0, 0xad, 0xc8, 0x6a, 0x0b, 0xc1, 0x23, 0x0f, 0x1b, 0x71, 0x5f, 0xfc, 0x40, 0x04, 0xdf, + 0xc4, 0xa7, 0xd5, 0xf7, 0x8a, 0x4d, 0xc3, 0x1a, 0xbf, 0x83, 0x0a, 0xe6, 0xe3, 0xbf, 0xd2, 0x1c, 0x87, + 0xfa, 0x51, 0x96, 0x54, 0x9e, 0x13, 0x0f, 0x6a, 0x08, 0x1b, 0xaf, 0xcf, 0x41, 0x70, 0xae, 0x20, 0x1c, + 0x78, 0xa3, 0x82, 0x9a, 0x01, 0xdb, 0xa5, 0x78, 0xa2, 0xef, 0x96, 0x8f, 0x2a, 0xb6, 0x66, 0x8d, 0x81, + 0x14, 0xdf, 0xcc, 0x65, 0xd7, 0x03, 0x8f, 0x55, 0x58, 0xbe, 0x7c, 0xdd, 0x92, 0x46, 0xd5, 0x22, 0x47, + 0x91, 0x52, 0x60, 0xa4, 0x0e, 0x59, 0xc4, 0x8b, 0x08, 0xa1, 0xed, 0x61, 0x42, 0x7f, 0xd3, 0x03, 0x91, + 0x7c, 0x6b, 0x34, 0xb7, 0x01, 0xa4, 0xba, 0x9a, 0x38, 0x15, 0xd4, 0x82, 0x8a, 0x22, 0x8c, 0xd2, 0x09, + 0xda, 0x13, 0x76, 0x26, 0xe2, 0x02, 0x9a, 0xab, 0xf6, 0xc2, 0x00, 0xbf, 0x7f, 0xd6, 0x3c, 0xf6, 0xd4, + 0x3b, 0xb6, 0x18, 0xb3, 0x1a, 0xc4, 0x8e, 0x09, 0x61, 0x35, 0x89, 0xd7, 0x4a, 0x69, 0x54, 0x2e, 0x90, + 0x9c, 0xe0, 0xdc, 0x9c, 0x57, 0xc7, 0x7f, 0x7d, 0x89, 0xb9, 0x66, 0xde, 0x20, 0x00, 0x53, 0xa5, 0x8e, + 0xa5, 0x8f, 0x23, 0x74, 0x51, 0x39, 0x61, 0x63, 0x8a, 0x30, 0xca, 0x49, 0xef, 0x0e, 0xec, 0x67, 0x9d, + 0x92, 0x7e, 0x38, 0x5b, 0x5d, 0xa7, 0xd4, 0xd3, 0xc1, 0xa5, 0x91, 0x69, 0xb4, 0x63, 0x0b, 0x87, 0x4a, + 0x1d, 0x96, 0x9e, 0x45, 0xd1, 0xfe, 0x37, 0x82, 0x08, 0x9f, 0x43, 0x85, 0x02, 0x49, 0x55, 0x09, 0x3b, + 0x30, 0x8e, 0x19, 0x64, 0xd3, 0x07, 0x91, 0x52, 0x71, 0xaa, 0x88, 0x6c, 0x3d, 0x9b, 0x64, 0xd8, 0x46, + 0xc8, 0x8c, 0xa1, 0x34, 0x1f, 0xd2, 0xf7, 0x2b, 0x76, 0x67, 0x9d, 0x4f, 0x25, 0x8f, 0x64, 0x7b, 0xc0, + 0x48, 0x20, 0xe4, 0x27, 0x76, 0xc9, 0xec, 0x0d, 0x01, 0x46, 0x46, 0x52, 0x76, 0x3a, 0x49, 0xd8, 0x22, + 0xc9, 0xd2, 0x5b, 0x60, 0x39, 0x03, 0xeb, 0xd6, 0x33, 0x89, 0x52, 0x25, 0x9b, 0x83, 0xa7, 0x40, 0xa4, + 0x20, 0xd6, 0x9d, 0x23, 0xae, 0xbb, 0xdf, 0x06, 0xa9, 0x2d, 0x88, 0xa4, 0x6f, 0xfc, 0xd8, 0xd8, 0x1a, + 0x47, 0xb6, 0xec, 0x99, 0xb6, 0xce, 0xa0, 0x48, 0x9c, 0xc8, 0x3e, 0xf1, 0x57, 0x57, 0xc4, 0x05, 0x3d, + 0x53, 0x84, 0x46, 0xf2, 0xe6, 0xb9, 0xeb, 0xa1, 0x2c, 0xe4, 0x96, 0x9b, 0x8d, 0x6d, 0xf9, 0xb3, 0xef, + 0x57, 0x4b, 0x7d, 0x40, 0x13, 0x41, 0xc2, 0xf5, 0x55, 0xa0, 0x0f, 0x02, 0x91, 0x64, 0xe5, 0xd3, 0x87, + 0x28, 0x2c, 0x0c, 0x87, 0x91, 0xba, 0x8c, 0x69, 0x81, 0x62, 0x48, 0xe2, 0xe5, 0x44, 0xa9, 0xc1, 0x2b, + 0x7a, 0xeb, 0xa6, 0x29, 0xfd, 0xee, 0xa2, 0xe1, 0x11, 0x65, 0x5e, 0x44, 0xb9, 0xc2, 0x15, 0x92, 0x4c, + 0x54, 0x55, 0xea, 0xa4, 0xab, 0x32, 0xae, 0xa1, 0xd9, 0xce, 0xf1, 0xd8, 0x6e, 0x8a, 0xcf, 0x6b, 0x0f, + 0xf4, 0xdc, 0xab, 0xaf, 0x4f, 0x0e, 0x2d, 0x9a, 0xe6, 0x5c, 0x8b, 0xb1, 0x06, 0x5e, 0x04, 0x18, 0xff, + 0x12, 0xd4, 0x62, 0x69, 0x30, 0x31, 0x59, 0x38, 0xbf, 0xe0, 0x0a, 0x8d, 0x03, 0xe8, 0xe7, 0x0e, 0x9d, + 0xea, 0x9d, 0xc9, 0xff, 0x74, 0x85, 0x4c, 0xbb, 0x4d, 0xbd, 0xf7, 0x00, 0xa6, 0x2e, 0x77, 0xb2, 0x6e, + 0x50, 0xb1, 0x3e, 0x2d, 0x39, 0x60, 0xc9, 0x13, 0x36, 0x0c, 0x84, 0xc8, 0x7e, 0x80, 0x1e, 0xd3, 0xdf, + 0x3d, 0xb0, 0xe2, 0x76, 0x04, 0x50, 0x8c, 0xb7, 0x30, 0xc5, 0xa0, 0x52, 0xc0, 0x68, 0xab, 0xe5, 0x82, + 0x6b, 0x01, 0xbe, 0x9f, 0x62, 0xe3, 0x3b, 0x9a, 0xf8, 0xed, 0xb6, 0x66, 0x7c, 0x57, 0xcb, 0x1a, 0xa8, + 0x79, 0x74, 0x3b, 0x77, 0xa7, 0x43, 0x2f, 0x75, 0xfe, 0x3a, 0xe2, 0x11, 0xf9, 0x6a, 0xf4, 0x1a, 0xde, + 0xf1, 0xe1, 0xc5, 0x07, 0x25, 0x6f, 0xe5, 0xfa, 0x2b, 0xcc, 0xab, 0xe5, 0x2c, 0xf8, 0x21, 0x6d, 0x34, + 0x10, 0xe6, 0x37, 0x85, 0x06, 0xd4, 0x27, 0x34, 0x34, 0x58, 0x33, 0x2d, 0x15, 0x3a, 0x77, 0xa1, 0x62, + 0xc4, 0xc5, 0xf1, 0x8d, 0x9f, 0x31, 0xb0, 0xc1, 0x42, 0x88, 0x0c, 0xad, 0x22, 0x29, 0x98, 0x17, 0x20, + 0x61, 0x5a, 0xb2, 0x6b, 0x7c, 0x13, 0x44, 0x2e, 0x43, 0x17, 0x8a, 0xad, 0xee, 0x43, 0x65, 0x10, 0xc9, + 0x1b, 0xc9, 0xd5, 0xd7, 0x35, 0xeb, 0x94, 0x53, 0xcf, 0x39, 0xce, 0xf5, 0x12, 0x0e, 0x28, 0x60, 0x37, + 0x75, 0xf0, 0x48, 0x3f, 0x01, 0xc3, 0xc4, 0x8b, 0x5b, 0x06, 0x0c, 0xa7, 0xf3, 0xa5, 0x4d, 0x7c, 0x7c, + 0x99, 0xa4, 0x81, 0xc9, 0x30, 0x81, 0xc6, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa2, 0x81, 0xbe, 0x04, 0x81, + 0xbb, 0x03, 0xab, 0x65, 0x67, 0x60, 0xa3, 0x51, 0x2f, 0xec, 0xc7, 0x03, 0x2d, 0xa8, 0xb2, 0x01, 0x46, + 0x59, 0xf0, 0xfb, 0x34, 0xeb, 0x76, 0xb4, 0x61, 0xe4, 0x04, 0x4d, 0xa2, 0x4d, 0x16, 0xd4, 0x58, 0xe3, + 0xe1, 0xc5, 0x89, 0x19, 0xc7, 0x4c, 0x4c, 0x07, 0x20, 0xaa, 0xfb, 0x87, 0xa9, 0x48, 0x15, 0x23, 0x72, + 0xa2, 0x48, 0x3a, 0x4d, 0x1a, 0xe9, 0xb9, 0x5b, 0x85, 0x8a, 0x52, 0xab, 0xaa, 0x94, 0xe7, 0xaa, 0x64, + 0x1a, 0x8b, 0x99, 0x7d, 0x7e, 0x6c, 0x6e, 0x57, 0x0b, 0x59, 0x08, 0xcc, 0x54, 0x91, 0x55, 0xf5, 0xe6, + 0xf1, 0x10, 0xc9, 0x8d, 0x64, 0x89, 0x78, 0x72, 0x7a, 0xba, 0xe3, 0x92, 0x1d, 0xa5, 0x2a, 0x4c, 0x1f, + 0xd7, 0x6b, 0xeb, 0x12, 0x1b, 0xf3, 0x39, 0x6b, 0xe8, 0xf9, 0x8e, 0x4a, 0xcf, 0x1e, 0xbf, 0xc3, 0xb6, + 0xfb, 0x7a, 0x13, 0x54, 0xc1, 0x21, 0x87, 0x3e, 0x59, 0x18, 0x5d, 0xb9, 0x00, 0x30, 0x08, 0x4d, 0x97, + 0x86, 0x47, 0x98, 0xd7, 0x9e, 0xb9, 0xdf, 0x30, 0x75, 0x6c, 0xa1, 0xfa, 0xa7, 0xa8, 0x08, 0x80, 0xf7, + 0x4f, 0x7d, 0x93, 0x64, 0x2d, 0x9c, 0xeb, 0x5e, 0x01, 0x28, 0xce, 0xd6, 0xab, 0x09, 0x6a, 0x4f, 0x01, + 0x5e, 0x5a, 0x03, 0x2b, 0x42, 0x70, 0x23, 0x1e, 0x7f, 0xf1, 0xbc, 0xd0, 0x87, 0xe8, 0xb5, 0x27, 0x02, + 0x7d } }; PTF_ASSERT_EQUAL(bindRequestLayer->getSaslAuthentication(), expectedSaslAuthentication); - PTF_ASSERT_RAISES(bindRequestLayer->getSimpleAuthentication(), std::invalid_argument, "Authentication type is not simple"); + PTF_ASSERT_RAISES(bindRequestLayer->getSimpleAuthentication(), std::invalid_argument, + "Authentication type is not simple"); std::string simpleAuthentication; - PTF_ASSERT_FALSE(bindRequestLayer->tryGet(&pcpp::LdapBindRequestLayer::getSimpleAuthentication, simpleAuthentication)); + PTF_ASSERT_FALSE( + bindRequestLayer->tryGet(&pcpp::LdapBindRequestLayer::getSimpleAuthentication, simpleAuthentication)); PTF_ASSERT_EQUAL(bindRequestLayer->toString(), "LDAP Layer, BindRequest, sasl"); } @@ -195,11 +245,17 @@ PTF_TEST_CASE(LdapParsingTest) PTF_ASSERT_EQUAL(bindResponseLayer->getDiagnosticMessage(), ""); PTF_ASSERT_VECTORS_EQUAL(bindResponseLayer->getReferral(), std::vector()); std::vector expectedServerSaslCredentials = { - 0xa1, 0x81, 0xa1, 0x30, 0x81, 0x9e, 0xa0, 0x03, 0x0a, 0x01, 0x00, 0xa1, 0x0b, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, 0x02, 0xa2, 0x81, 0x89, 0x04, 0x81, 0x86, 0x60, 0x81, 0x83, 0x06, 0x09, 0x2a, 0x86, 0x48, - 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x02, 0x00, 0x6f, 0x74, 0x30, 0x72, 0xa0, 0x03, 0x02, 0x01, 0x05, 0xa1, 0x03, 0x02, 0x01, 0x0f, 0xa2, 0x66, 0x30, 0x64, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa2, 0x5d, 0x04, 0x5b, 0x4a, 0x9f, 0x10, - 0xab, 0x89, 0x96, 0xfa, 0x43, 0xf2, 0xfb, 0x40, 0x92, 0xa7, 0x6c, 0xc3, 0xfa, 0x6c, 0x1f, 0x00, 0x11, 0x67, 0xfa, 0xc9, 0x04, 0xda, 0xb0, 0x67, 0xf5, 0xf2, 0xda, 0x59, 0xa7, 0x54, 0x90, 0x57, 0xbd, 0x3e, 0xb4, 0x6c, 0xb4, 0x67, - 0xfd, 0x3b, 0x01, 0xd7, 0x3f, 0x50, 0x51, 0xaa, 0x63, 0x2e, 0xd8, 0xd6, 0xa6, 0xe5, 0x81, 0xbb, 0xab, 0x17, 0x80, 0xfa, 0xab, 0xac, 0x51, 0x52, 0x84, 0x13, 0x9c, 0xfb, 0x44, 0xc2, 0x04, 0xae, 0x1e, 0xc2, 0x5a, 0x2d, 0x58, 0x90, - 0x9d, 0x22, 0xff, 0x52, 0x34, 0x9e, 0x6d, 0x2e, 0x4d, 0x83, 0x5b, 0x98}; + 0xa1, 0x81, 0xa1, 0x30, 0x81, 0x9e, 0xa0, 0x03, 0x0a, 0x01, 0x00, 0xa1, 0x0b, 0x06, 0x09, 0x2a, 0x86, + 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, 0x02, 0xa2, 0x81, 0x89, 0x04, 0x81, 0x86, 0x60, 0x81, 0x83, 0x06, + 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x02, 0x00, 0x6f, 0x74, 0x30, 0x72, 0xa0, + 0x03, 0x02, 0x01, 0x05, 0xa1, 0x03, 0x02, 0x01, 0x0f, 0xa2, 0x66, 0x30, 0x64, 0xa0, 0x03, 0x02, 0x01, + 0x17, 0xa2, 0x5d, 0x04, 0x5b, 0x4a, 0x9f, 0x10, 0xab, 0x89, 0x96, 0xfa, 0x43, 0xf2, 0xfb, 0x40, 0x92, + 0xa7, 0x6c, 0xc3, 0xfa, 0x6c, 0x1f, 0x00, 0x11, 0x67, 0xfa, 0xc9, 0x04, 0xda, 0xb0, 0x67, 0xf5, 0xf2, + 0xda, 0x59, 0xa7, 0x54, 0x90, 0x57, 0xbd, 0x3e, 0xb4, 0x6c, 0xb4, 0x67, 0xfd, 0x3b, 0x01, 0xd7, 0x3f, + 0x50, 0x51, 0xaa, 0x63, 0x2e, 0xd8, 0xd6, 0xa6, 0xe5, 0x81, 0xbb, 0xab, 0x17, 0x80, 0xfa, 0xab, 0xac, + 0x51, 0x52, 0x84, 0x13, 0x9c, 0xfb, 0x44, 0xc2, 0x04, 0xae, 0x1e, 0xc2, 0x5a, 0x2d, 0x58, 0x90, 0x9d, + 0x22, 0xff, 0x52, 0x34, 0x9e, 0x6d, 0x2e, 0x4d, 0x83, 0x5b, 0x98 + }; PTF_ASSERT_VECTORS_EQUAL(bindResponseLayer->getServerSaslCredentials(), expectedServerSaslCredentials); } @@ -241,33 +297,32 @@ PTF_TEST_CASE(LdapParsingTest) PTF_ASSERT_EQUAL(searchRequestLayer->getMessageID(), 9); PTF_ASSERT_EQUAL(searchRequestLayer->getLdapOperationType(), pcpp::LdapOperationType::SearchRequest, enum); PTF_ASSERT_EQUAL(searchRequestLayer->getBaseObject(), "cn=schema"); - PTF_ASSERT_EQUAL(searchRequestLayer->getScope(), pcpp::LdapSearchRequestLayer::SearchRequestScope::BaseObject, enum); - PTF_ASSERT_EQUAL(searchRequestLayer->getDerefAlias(), pcpp::LdapSearchRequestLayer::DerefAliases::DerefAlways, enum); + PTF_ASSERT_EQUAL(searchRequestLayer->getScope(), pcpp::LdapSearchRequestLayer::SearchRequestScope::BaseObject, + enum); + PTF_ASSERT_EQUAL(searchRequestLayer->getDerefAlias(), pcpp::LdapSearchRequestLayer::DerefAliases::DerefAlways, + enum); PTF_ASSERT_EQUAL(searchRequestLayer->getSizeLimit(), 0); PTF_ASSERT_EQUAL(searchRequestLayer->getTimeLimit(), 0); PTF_ASSERT_FALSE(searchRequestLayer->getTypesOnly()); std::ostringstream expectedFilter; - expectedFilter - << "ContextSpecific (3) (constructed), Length: 2+24" << std::endl - << " OctetString, Length: 2+11, Value: objectClass" << std::endl - << " OctetString, Length: 2+9, Value: subschema"; + expectedFilter << "ContextSpecific (3) (constructed), Length: 2+24" << std::endl + << " OctetString, Length: 2+11, Value: objectClass" << std::endl + << " OctetString, Length: 2+9, Value: subschema"; PTF_ASSERT_EQUAL(searchRequestLayer->getFilter()->toString(), expectedFilter.str()); PTF_ASSERT_EQUAL(searchRequestLayer->toString(), "LDAP Layer, SearchRequest, \"cn=schema\", BaseObject"); auto attributes = searchRequestLayer->getAttributes(); - std::vector expectedAttributes = { - "objectClasses", - "attributeTypes", - "ldapSyntaxes", - "matchingRules", - "matchingRuleUse", - "dITContentRules", - "dITStructureRules", - "nameForms", - "createTimestamp", - "modifyTimestamp", - "*", - "+" - }; + std::vector expectedAttributes = { "objectClasses", + "attributeTypes", + "ldapSyntaxes", + "matchingRules", + "matchingRuleUse", + "dITContentRules", + "dITStructureRules", + "nameForms", + "createTimestamp", + "modifyTimestamp", + "*", + "+" }; PTF_ASSERT_VECTORS_EQUAL(attributes, expectedAttributes); } @@ -279,13 +334,15 @@ PTF_TEST_CASE(LdapParsingTest) auto searchResultEntryLayer = searchResEntryPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(searchResultEntryLayer); PTF_ASSERT_EQUAL(searchResultEntryLayer->getMessageID(), 16); - PTF_ASSERT_EQUAL(searchResultEntryLayer->getLdapOperationType(), pcpp::LdapOperationType::SearchResultEntry, enum); - PTF_ASSERT_EQUAL(searchResultEntryLayer->getObjectName(), "cn=b.smith,ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org"); + PTF_ASSERT_EQUAL(searchResultEntryLayer->getLdapOperationType(), pcpp::LdapOperationType::SearchResultEntry, + enum); + PTF_ASSERT_EQUAL(searchResultEntryLayer->getObjectName(), + "cn=b.smith,ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org"); std::vector expectedAttributes = { - {"objectclass", {"inetOrgPerson", "organizationalPerson", "person", "top"}}, - {"sn", {"Young"}}, - {"cn", {"b.smith"}}, - {"givenname", {"Beatrix"}} + { "objectclass", { "inetOrgPerson", "organizationalPerson", "person", "top" } }, + { "sn", { "Young" } }, + { "cn", { "b.smith" } }, + { "givenname", { "Beatrix" } } }; PTF_ASSERT_VECTORS_EQUAL(searchResultEntryLayer->getAttributes(), expectedAttributes); } @@ -298,7 +355,8 @@ PTF_TEST_CASE(LdapParsingTest) auto searchResultDoneLayer = searchResultDonePacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(searchResultDoneLayer); PTF_ASSERT_EQUAL(searchResultDoneLayer->getMessageID(), 8); - PTF_ASSERT_EQUAL(searchResultDoneLayer->getLdapOperationType(), pcpp::LdapOperationType::SearchResultDone, enum); + PTF_ASSERT_EQUAL(searchResultDoneLayer->getLdapOperationType(), pcpp::LdapOperationType::SearchResultDone, + enum); PTF_ASSERT_EQUAL(searchResultDoneLayer->getResultCode(), pcpp::LdapResultCode::Success, enum); PTF_ASSERT_EQUAL(searchResultDoneLayer->getMatchedDN(), ""); PTF_ASSERT_EQUAL(searchResultDoneLayer->getDiagnosticMessage(), ""); @@ -351,10 +409,8 @@ PTF_TEST_CASE(LdapParsingTest) PTF_ASSERT_EQUAL(deleteResponseLayer->getMatchedDN(), "ou=People,dc=example,dc=com"); PTF_ASSERT_EQUAL(deleteResponseLayer->getDiagnosticMessage(), "LDAP: error code 32 - No such object"); - std::vector expectedReferral = { - "ldap://ldap.example.com/dc=example,dc=com", - "ldap://ldap.example.com/dc=example,dc=com?objectClass?one" - }; + std::vector expectedReferral = { "ldap://ldap.example.com/dc=example,dc=com", + "ldap://ldap.example.com/dc=example,dc=com?objectClass?one" }; PTF_ASSERT_VECTORS_EQUAL(deleteResponseLayer->getReferral(), expectedReferral); PTF_ASSERT_EQUAL(deleteResponseLayer->toString(), "LDAP Layer, DeleteResponse, NoSuchObject"); } @@ -367,7 +423,8 @@ PTF_TEST_CASE(LdapParsingTest) auto modifyDNResponseLayer = modifyDNResponsePacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(modifyDNResponseLayer); PTF_ASSERT_EQUAL(modifyDNResponseLayer->getMessageID(), 15); - PTF_ASSERT_EQUAL(modifyDNResponseLayer->getLdapOperationType(), pcpp::LdapOperationType::ModifyDNResponse, enum); + PTF_ASSERT_EQUAL(modifyDNResponseLayer->getLdapOperationType(), pcpp::LdapOperationType::ModifyDNResponse, + enum); PTF_ASSERT_EQUAL(modifyDNResponseLayer->getResultCode(), pcpp::LdapResultCode::NoSuchObject, enum); PTF_ASSERT_EQUAL(modifyDNResponseLayer->getMatchedDN(), "ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org"); PTF_ASSERT_EQUAL(modifyDNResponseLayer->getDiagnosticMessage(), ""); @@ -390,8 +447,7 @@ PTF_TEST_CASE(LdapParsingTest) PTF_ASSERT_VECTORS_EQUAL(compareResponseLayer->getReferral(), std::vector()); PTF_ASSERT_EQUAL(compareResponseLayer->toString(), "LDAP Layer, CompareResponse, CompareFalse"); } -} // LdapParsingTest - +} // LdapParsingTest PTF_TEST_CASE(LdapCreationTest) { @@ -410,23 +466,26 @@ PTF_TEST_CASE(LdapCreationTest) pcpp::Asn1IntegerRecord integerRecord2(0); pcpp::Asn1BooleanRecord booleanRecord(false); - pcpp::Asn1GenericRecord subRecord1(pcpp::Asn1TagClass::ContextSpecific, false, 1, "2.16.840.1.113730.3.3.2.46.1"); + pcpp::Asn1GenericRecord subRecord1(pcpp::Asn1TagClass::ContextSpecific, false, 1, + "2.16.840.1.113730.3.3.2.46.1"); pcpp::Asn1GenericRecord subRecord2(pcpp::Asn1TagClass::ContextSpecific, false, 2, "departmentNumber"); pcpp::Asn1GenericRecord subRecord3(pcpp::Asn1TagClass::ContextSpecific, false, 3, ">=N4709"); - pcpp::Asn1ConstructedRecord constructedRecord1(pcpp::Asn1TagClass::ContextSpecific, 9, {&subRecord1, &subRecord2, &subRecord3}); + pcpp::Asn1ConstructedRecord constructedRecord1(pcpp::Asn1TagClass::ContextSpecific, 9, + { &subRecord1, &subRecord2, &subRecord3 }); pcpp::Asn1OctetStringRecord stringSubRecord1("*"); pcpp::Asn1OctetStringRecord stringSubRecord2("ntsecuritydescriptor"); - pcpp::Asn1SequenceRecord sequenceRecord({&stringSubRecord1, &stringSubRecord2}); + pcpp::Asn1SequenceRecord sequenceRecord({ &stringSubRecord1, &stringSubRecord2 }); std::vector controls = { - {"1.2.840.113556.1.4.801", "3003020107"}, - {"1.2.840.113556.1.4.319", "3006020201f40400"} + { "1.2.840.113556.1.4.801", "3003020107" }, + { "1.2.840.113556.1.4.319", "3006020201f40400" } }; pcpp::LdapLayer ldapLayer(6, pcpp::LdapOperationType::SearchRequest, - {&stringRecord, &enumeratedRecord1, &enumeratedRecord2, &integerRecord1, &integerRecord2, &booleanRecord, &constructedRecord1, &sequenceRecord}, - controls); + { &stringRecord, &enumeratedRecord1, &enumeratedRecord2, &integerRecord1, + &integerRecord2, &booleanRecord, &constructedRecord1, &sequenceRecord }, + controls); auto expectedLdapLayer = ldapPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(expectedLdapLayer); @@ -441,11 +500,14 @@ PTF_TEST_CASE(LdapCreationTest) pcpp::Asn1IntegerRecord integerRecord(3); pcpp::Asn1OctetStringRecord stringRecord("cn=Administrator,cn=Users,dc=cloudshark-a,dc=example,dc=com"); - uint8_t contextSpecificData[14] = {0x63, 0x6c, 0x6f, 0x75, 0x64, 0x73, 0x68, 0x61, 0x72, 0x6b, 0x31, 0x32, 0x33, 0x21}; - pcpp::Asn1GenericRecord contextSpecificRecord(pcpp::Asn1TagClass::ContextSpecific, false, 0, contextSpecificData, 14); - std::vector controls = {{"1.3.6.1.4.1.42.2.27.8.5.1"}}; + uint8_t contextSpecificData[14] = { 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x73, 0x68, + 0x61, 0x72, 0x6b, 0x31, 0x32, 0x33, 0x21 }; + pcpp::Asn1GenericRecord contextSpecificRecord(pcpp::Asn1TagClass::ContextSpecific, false, 0, + contextSpecificData, 14); + std::vector controls = { { "1.3.6.1.4.1.42.2.27.8.5.1" } }; - pcpp::LdapLayer ldapLayer(2, pcpp::LdapOperationType::BindRequest, {&integerRecord, &stringRecord, &contextSpecificRecord}, controls); + pcpp::LdapLayer ldapLayer(2, pcpp::LdapOperationType::BindRequest, + { &integerRecord, &stringRecord, &contextSpecificRecord }, controls); auto expectedLdapLayer = ldapPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(expectedLdapLayer); @@ -459,13 +521,13 @@ PTF_TEST_CASE(LdapCreationTest) pcpp::Packet bindRequestPacket(&rawPacket1); pcpp::LdapBindRequestLayer bindRequestLayer(2, 3, "cn=Administrator,cn=Users,dc=cloudshark-a,dc=example,dc=com", - "cloudshark123!", {{"1.3.6.1.4.1.42.2.27.8.5.1"}}); + "cloudshark123!", { { "1.3.6.1.4.1.42.2.27.8.5.1" } }); auto expectedBindRequestLayer = bindRequestPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(expectedBindRequestLayer); PTF_ASSERT_BUF_COMPARE(bindRequestLayer.getData(), expectedBindRequestLayer->getData(), - expectedBindRequestLayer->getDataLen()); + expectedBindRequestLayer->getDataLen()); } // BindRequest with sasl authentication @@ -473,54 +535,99 @@ PTF_TEST_CASE(LdapCreationTest) READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ldap_bind_request2.dat"); pcpp::Packet bindRequestPacket(&rawPacket1); - pcpp::LdapBindRequestLayer::SaslAuthentication saslAuthentication { + pcpp::LdapBindRequestLayer::SaslAuthentication saslAuthentication{ "GSS-SPNEGO", - {0x60, 0x82, 0x05, 0x1a, 0x06, 0x06, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02, 0xa0, 0x82, 0x05, 0x0e, 0x30, 0x82, 0x05, 0x0a, 0xa0, 0x24, 0x30, 0x22, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x06, 0x09, 0x2a, - 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0a, 0xa2, 0x82, 0x04, 0xe0, 0x04, 0x82, 0x04, 0xdc, 0x60, 0x82, 0x04, 0xd8, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, - 0xf7, 0x12, 0x01, 0x02, 0x02, 0x01, 0x00, 0x6e, 0x82, 0x04, 0xc7, 0x30, 0x82, 0x04, 0xc3, 0xa0, 0x03, 0x02, 0x01, 0x05, 0xa1, 0x03, 0x02, 0x01, 0x0e, 0xa2, 0x07, 0x03, 0x05, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa3, 0x82, 0x03, 0xe0, - 0x61, 0x82, 0x03, 0xdc, 0x30, 0x82, 0x03, 0xd8, 0xa0, 0x03, 0x02, 0x01, 0x05, 0xa1, 0x15, 0x1b, 0x13, 0x57, 0x32, 0x4b, 0x33, 0x2e, 0x56, 0x4d, 0x4e, 0x45, 0x54, 0x31, 0x2e, 0x56, 0x4d, 0x2e, 0x42, 0x41, 0x53, 0x45, 0xa2, 0x2f, - 0x30, 0x2d, 0xa0, 0x03, 0x02, 0x01, 0x02, 0xa1, 0x26, 0x30, 0x24, 0x1b, 0x04, 0x6c, 0x64, 0x61, 0x70, 0x1b, 0x1c, 0x77, 0x32, 0x6b, 0x33, 0x2d, 0x31, 0x30, 0x31, 0x2e, 0x77, 0x32, 0x6b, 0x33, 0x2e, 0x76, 0x6d, 0x6e, 0x65, 0x74, - 0x31, 0x2e, 0x76, 0x6d, 0x2e, 0x62, 0x61, 0x73, 0x65, 0xa3, 0x82, 0x03, 0x87, 0x30, 0x82, 0x03, 0x83, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa1, 0x03, 0x02, 0x01, 0x07, 0xa2, 0x82, 0x03, 0x75, 0x04, 0x82, 0x03, 0x71, 0x6a, 0x61, 0xc8, - 0x86, 0xba, 0x58, 0xd1, 0x62, 0x11, 0x3d, 0xb4, 0x26, 0x8f, 0x77, 0x43, 0xa1, 0x7e, 0xb4, 0x76, 0x18, 0x3b, 0xc0, 0xc5, 0x19, 0xad, 0xde, 0xa7, 0x65, 0x56, 0xa3, 0x70, 0x1d, 0xe3, 0x49, 0x03, 0xe6, 0xbd, 0x3f, 0x3f, 0xdc, 0xa0, - 0xb0, 0x1b, 0xbc, 0xcb, 0x9a, 0x86, 0x93, 0xb2, 0x3f, 0xa8, 0xd1, 0x98, 0x5e, 0x14, 0x92, 0x2e, 0x4c, 0xa1, 0x9b, 0x05, 0xa9, 0x07, 0x69, 0x84, 0x5a, 0x58, 0x58, 0x51, 0x5b, 0xba, 0x4a, 0xf2, 0xd7, 0xe5, 0x9b, 0xfa, 0x86, 0x34, - 0x28, 0x5a, 0x2e, 0x95, 0x4f, 0xb5, 0x18, 0x37, 0x8b, 0x8d, 0x3f, 0x27, 0x44, 0xb9, 0xbb, 0xf8, 0x84, 0x2b, 0x48, 0x07, 0x87, 0x9f, 0xf2, 0x8e, 0x55, 0xbf, 0xba, 0x49, 0x67, 0xe8, 0xc1, 0xd3, 0xb6, 0xc4, 0xe3, 0x58, 0xa5, 0x61, - 0xc5, 0x4a, 0xbb, 0xc1, 0xcb, 0x7c, 0x97, 0xb6, 0x50, 0x3f, 0xe5, 0x9b, 0x7f, 0xee, 0x64, 0x23, 0xdf, 0xfe, 0x66, 0xfe, 0x6d, 0xcb, 0x8a, 0xf0, 0x0e, 0x69, 0xc5, 0x3d, 0x6b, 0x57, 0x6f, 0x55, 0x06, 0x99, 0x04, 0x38, 0x31, 0x0f, - 0xb7, 0xdd, 0x14, 0x68, 0xa3, 0x2f, 0xd8, 0xe0, 0xde, 0xab, 0x40, 0xb1, 0x5e, 0xcf, 0xd4, 0x38, 0x56, 0x83, 0x70, 0x14, 0x0a, 0x1e, 0xda, 0xfe, 0xe7, 0x01, 0xa4, 0xa4, 0xb4, 0xe7, 0xb3, 0xaa, 0xef, 0xdc, 0x4b, 0x1a, 0xff, 0x58, - 0x68, 0xae, 0xfe, 0x5a, 0x36, 0x29, 0x4d, 0x5d, 0xd6, 0x87, 0xd5, 0xa6, 0x49, 0x31, 0x43, 0xd3, 0xad, 0xe8, 0x03, 0x1c, 0x98, 0xd2, 0x8f, 0x6c, 0x7f, 0x3d, 0xce, 0xa4, 0x14, 0x35, 0x13, 0x2f, 0x67, 0x5f, 0x26, 0x94, 0x0d, 0x1f, - 0x69, 0xe5, 0x73, 0xe5, 0xec, 0xe6, 0xed, 0x5a, 0x66, 0x11, 0x1f, 0xf9, 0xf4, 0xb0, 0x2a, 0x8d, 0xdd, 0x19, 0x08, 0x6e, 0x5b, 0x9d, 0xc0, 0xad, 0xc8, 0x6a, 0x0b, 0xc1, 0x23, 0x0f, 0x1b, 0x71, 0x5f, 0xfc, 0x40, 0x04, 0xdf, 0xc4, - 0xa7, 0xd5, 0xf7, 0x8a, 0x4d, 0xc3, 0x1a, 0xbf, 0x83, 0x0a, 0xe6, 0xe3, 0xbf, 0xd2, 0x1c, 0x87, 0xfa, 0x51, 0x96, 0x54, 0x9e, 0x13, 0x0f, 0x6a, 0x08, 0x1b, 0xaf, 0xcf, 0x41, 0x70, 0xae, 0x20, 0x1c, 0x78, 0xa3, 0x82, 0x9a, 0x01, - 0xdb, 0xa5, 0x78, 0xa2, 0xef, 0x96, 0x8f, 0x2a, 0xb6, 0x66, 0x8d, 0x81, 0x14, 0xdf, 0xcc, 0x65, 0xd7, 0x03, 0x8f, 0x55, 0x58, 0xbe, 0x7c, 0xdd, 0x92, 0x46, 0xd5, 0x22, 0x47, 0x91, 0x52, 0x60, 0xa4, 0x0e, 0x59, 0xc4, 0x8b, 0x08, - 0xa1, 0xed, 0x61, 0x42, 0x7f, 0xd3, 0x03, 0x91, 0x7c, 0x6b, 0x34, 0xb7, 0x01, 0xa4, 0xba, 0x9a, 0x38, 0x15, 0xd4, 0x82, 0x8a, 0x22, 0x8c, 0xd2, 0x09, 0xda, 0x13, 0x76, 0x26, 0xe2, 0x02, 0x9a, 0xab, 0xf6, 0xc2, 0x00, 0xbf, 0x7f, - 0xd6, 0x3c, 0xf6, 0xd4, 0x3b, 0xb6, 0x18, 0xb3, 0x1a, 0xc4, 0x8e, 0x09, 0x61, 0x35, 0x89, 0xd7, 0x4a, 0x69, 0x54, 0x2e, 0x90, 0x9c, 0xe0, 0xdc, 0x9c, 0x57, 0xc7, 0x7f, 0x7d, 0x89, 0xb9, 0x66, 0xde, 0x20, 0x00, 0x53, 0xa5, 0x8e, - 0xa5, 0x8f, 0x23, 0x74, 0x51, 0x39, 0x61, 0x63, 0x8a, 0x30, 0xca, 0x49, 0xef, 0x0e, 0xec, 0x67, 0x9d, 0x92, 0x7e, 0x38, 0x5b, 0x5d, 0xa7, 0xd4, 0xd3, 0xc1, 0xa5, 0x91, 0x69, 0xb4, 0x63, 0x0b, 0x87, 0x4a, 0x1d, 0x96, 0x9e, 0x45, - 0xd1, 0xfe, 0x37, 0x82, 0x08, 0x9f, 0x43, 0x85, 0x02, 0x49, 0x55, 0x09, 0x3b, 0x30, 0x8e, 0x19, 0x64, 0xd3, 0x07, 0x91, 0x52, 0x71, 0xaa, 0x88, 0x6c, 0x3d, 0x9b, 0x64, 0xd8, 0x46, 0xc8, 0x8c, 0xa1, 0x34, 0x1f, 0xd2, 0xf7, 0x2b, - 0x76, 0x67, 0x9d, 0x4f, 0x25, 0x8f, 0x64, 0x7b, 0xc0, 0x48, 0x20, 0xe4, 0x27, 0x76, 0xc9, 0xec, 0x0d, 0x01, 0x46, 0x46, 0x52, 0x76, 0x3a, 0x49, 0xd8, 0x22, 0xc9, 0xd2, 0x5b, 0x60, 0x39, 0x03, 0xeb, 0xd6, 0x33, 0x89, 0x52, 0x25, - 0x9b, 0x83, 0xa7, 0x40, 0xa4, 0x20, 0xd6, 0x9d, 0x23, 0xae, 0xbb, 0xdf, 0x06, 0xa9, 0x2d, 0x88, 0xa4, 0x6f, 0xfc, 0xd8, 0xd8, 0x1a, 0x47, 0xb6, 0xec, 0x99, 0xb6, 0xce, 0xa0, 0x48, 0x9c, 0xc8, 0x3e, 0xf1, 0x57, 0x57, 0xc4, 0x05, - 0x3d, 0x53, 0x84, 0x46, 0xf2, 0xe6, 0xb9, 0xeb, 0xa1, 0x2c, 0xe4, 0x96, 0x9b, 0x8d, 0x6d, 0xf9, 0xb3, 0xef, 0x57, 0x4b, 0x7d, 0x40, 0x13, 0x41, 0xc2, 0xf5, 0x55, 0xa0, 0x0f, 0x02, 0x91, 0x64, 0xe5, 0xd3, 0x87, 0x28, 0x2c, 0x0c, - 0x87, 0x91, 0xba, 0x8c, 0x69, 0x81, 0x62, 0x48, 0xe2, 0xe5, 0x44, 0xa9, 0xc1, 0x2b, 0x7a, 0xeb, 0xa6, 0x29, 0xfd, 0xee, 0xa2, 0xe1, 0x11, 0x65, 0x5e, 0x44, 0xb9, 0xc2, 0x15, 0x92, 0x4c, 0x54, 0x55, 0xea, 0xa4, 0xab, 0x32, 0xae, - 0xa1, 0xd9, 0xce, 0xf1, 0xd8, 0x6e, 0x8a, 0xcf, 0x6b, 0x0f, 0xf4, 0xdc, 0xab, 0xaf, 0x4f, 0x0e, 0x2d, 0x9a, 0xe6, 0x5c, 0x8b, 0xb1, 0x06, 0x5e, 0x04, 0x18, 0xff, 0x12, 0xd4, 0x62, 0x69, 0x30, 0x31, 0x59, 0x38, 0xbf, 0xe0, 0x0a, - 0x8d, 0x03, 0xe8, 0xe7, 0x0e, 0x9d, 0xea, 0x9d, 0xc9, 0xff, 0x74, 0x85, 0x4c, 0xbb, 0x4d, 0xbd, 0xf7, 0x00, 0xa6, 0x2e, 0x77, 0xb2, 0x6e, 0x50, 0xb1, 0x3e, 0x2d, 0x39, 0x60, 0xc9, 0x13, 0x36, 0x0c, 0x84, 0xc8, 0x7e, 0x80, 0x1e, - 0xd3, 0xdf, 0x3d, 0xb0, 0xe2, 0x76, 0x04, 0x50, 0x8c, 0xb7, 0x30, 0xc5, 0xa0, 0x52, 0xc0, 0x68, 0xab, 0xe5, 0x82, 0x6b, 0x01, 0xbe, 0x9f, 0x62, 0xe3, 0x3b, 0x9a, 0xf8, 0xed, 0xb6, 0x66, 0x7c, 0x57, 0xcb, 0x1a, 0xa8, 0x79, 0x74, - 0x3b, 0x77, 0xa7, 0x43, 0x2f, 0x75, 0xfe, 0x3a, 0xe2, 0x11, 0xf9, 0x6a, 0xf4, 0x1a, 0xde, 0xf1, 0xe1, 0xc5, 0x07, 0x25, 0x6f, 0xe5, 0xfa, 0x2b, 0xcc, 0xab, 0xe5, 0x2c, 0xf8, 0x21, 0x6d, 0x34, 0x10, 0xe6, 0x37, 0x85, 0x06, 0xd4, - 0x27, 0x34, 0x34, 0x58, 0x33, 0x2d, 0x15, 0x3a, 0x77, 0xa1, 0x62, 0xc4, 0xc5, 0xf1, 0x8d, 0x9f, 0x31, 0xb0, 0xc1, 0x42, 0x88, 0x0c, 0xad, 0x22, 0x29, 0x98, 0x17, 0x20, 0x61, 0x5a, 0xb2, 0x6b, 0x7c, 0x13, 0x44, 0x2e, 0x43, 0x17, - 0x8a, 0xad, 0xee, 0x43, 0x65, 0x10, 0xc9, 0x1b, 0xc9, 0xd5, 0xd7, 0x35, 0xeb, 0x94, 0x53, 0xcf, 0x39, 0xce, 0xf5, 0x12, 0x0e, 0x28, 0x60, 0x37, 0x75, 0xf0, 0x48, 0x3f, 0x01, 0xc3, 0xc4, 0x8b, 0x5b, 0x06, 0x0c, 0xa7, 0xf3, 0xa5, - 0x4d, 0x7c, 0x7c, 0x99, 0xa4, 0x81, 0xc9, 0x30, 0x81, 0xc6, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa2, 0x81, 0xbe, 0x04, 0x81, 0xbb, 0x03, 0xab, 0x65, 0x67, 0x60, 0xa3, 0x51, 0x2f, 0xec, 0xc7, 0x03, 0x2d, 0xa8, 0xb2, 0x01, 0x46, 0x59, - 0xf0, 0xfb, 0x34, 0xeb, 0x76, 0xb4, 0x61, 0xe4, 0x04, 0x4d, 0xa2, 0x4d, 0x16, 0xd4, 0x58, 0xe3, 0xe1, 0xc5, 0x89, 0x19, 0xc7, 0x4c, 0x4c, 0x07, 0x20, 0xaa, 0xfb, 0x87, 0xa9, 0x48, 0x15, 0x23, 0x72, 0xa2, 0x48, 0x3a, 0x4d, 0x1a, - 0xe9, 0xb9, 0x5b, 0x85, 0x8a, 0x52, 0xab, 0xaa, 0x94, 0xe7, 0xaa, 0x64, 0x1a, 0x8b, 0x99, 0x7d, 0x7e, 0x6c, 0x6e, 0x57, 0x0b, 0x59, 0x08, 0xcc, 0x54, 0x91, 0x55, 0xf5, 0xe6, 0xf1, 0x10, 0xc9, 0x8d, 0x64, 0x89, 0x78, 0x72, 0x7a, - 0xba, 0xe3, 0x92, 0x1d, 0xa5, 0x2a, 0x4c, 0x1f, 0xd7, 0x6b, 0xeb, 0x12, 0x1b, 0xf3, 0x39, 0x6b, 0xe8, 0xf9, 0x8e, 0x4a, 0xcf, 0x1e, 0xbf, 0xc3, 0xb6, 0xfb, 0x7a, 0x13, 0x54, 0xc1, 0x21, 0x87, 0x3e, 0x59, 0x18, 0x5d, 0xb9, 0x00, - 0x30, 0x08, 0x4d, 0x97, 0x86, 0x47, 0x98, 0xd7, 0x9e, 0xb9, 0xdf, 0x30, 0x75, 0x6c, 0xa1, 0xfa, 0xa7, 0xa8, 0x08, 0x80, 0xf7, 0x4f, 0x7d, 0x93, 0x64, 0x2d, 0x9c, 0xeb, 0x5e, 0x01, 0x28, 0xce, 0xd6, 0xab, 0x09, 0x6a, 0x4f, 0x01, - 0x5e, 0x5a, 0x03, 0x2b, 0x42, 0x70, 0x23, 0x1e, 0x7f, 0xf1, 0xbc, 0xd0, 0x87, 0xe8, 0xb5, 0x27, 0x02, 0x7d} + { 0x60, 0x82, 0x05, 0x1a, 0x06, 0x06, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02, 0xa0, 0x82, 0x05, 0x0e, 0x30, + 0x82, 0x05, 0x0a, 0xa0, 0x24, 0x30, 0x22, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, + 0x02, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x06, 0x0a, 0x2b, 0x06, 0x01, + 0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0a, 0xa2, 0x82, 0x04, 0xe0, 0x04, 0x82, 0x04, 0xdc, 0x60, 0x82, + 0x04, 0xd8, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x01, 0x00, 0x6e, 0x82, + 0x04, 0xc7, 0x30, 0x82, 0x04, 0xc3, 0xa0, 0x03, 0x02, 0x01, 0x05, 0xa1, 0x03, 0x02, 0x01, 0x0e, 0xa2, + 0x07, 0x03, 0x05, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa3, 0x82, 0x03, 0xe0, 0x61, 0x82, 0x03, 0xdc, 0x30, + 0x82, 0x03, 0xd8, 0xa0, 0x03, 0x02, 0x01, 0x05, 0xa1, 0x15, 0x1b, 0x13, 0x57, 0x32, 0x4b, 0x33, 0x2e, + 0x56, 0x4d, 0x4e, 0x45, 0x54, 0x31, 0x2e, 0x56, 0x4d, 0x2e, 0x42, 0x41, 0x53, 0x45, 0xa2, 0x2f, 0x30, + 0x2d, 0xa0, 0x03, 0x02, 0x01, 0x02, 0xa1, 0x26, 0x30, 0x24, 0x1b, 0x04, 0x6c, 0x64, 0x61, 0x70, 0x1b, + 0x1c, 0x77, 0x32, 0x6b, 0x33, 0x2d, 0x31, 0x30, 0x31, 0x2e, 0x77, 0x32, 0x6b, 0x33, 0x2e, 0x76, 0x6d, + 0x6e, 0x65, 0x74, 0x31, 0x2e, 0x76, 0x6d, 0x2e, 0x62, 0x61, 0x73, 0x65, 0xa3, 0x82, 0x03, 0x87, 0x30, + 0x82, 0x03, 0x83, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa1, 0x03, 0x02, 0x01, 0x07, 0xa2, 0x82, 0x03, 0x75, + 0x04, 0x82, 0x03, 0x71, 0x6a, 0x61, 0xc8, 0x86, 0xba, 0x58, 0xd1, 0x62, 0x11, 0x3d, 0xb4, 0x26, 0x8f, + 0x77, 0x43, 0xa1, 0x7e, 0xb4, 0x76, 0x18, 0x3b, 0xc0, 0xc5, 0x19, 0xad, 0xde, 0xa7, 0x65, 0x56, 0xa3, + 0x70, 0x1d, 0xe3, 0x49, 0x03, 0xe6, 0xbd, 0x3f, 0x3f, 0xdc, 0xa0, 0xb0, 0x1b, 0xbc, 0xcb, 0x9a, 0x86, + 0x93, 0xb2, 0x3f, 0xa8, 0xd1, 0x98, 0x5e, 0x14, 0x92, 0x2e, 0x4c, 0xa1, 0x9b, 0x05, 0xa9, 0x07, 0x69, + 0x84, 0x5a, 0x58, 0x58, 0x51, 0x5b, 0xba, 0x4a, 0xf2, 0xd7, 0xe5, 0x9b, 0xfa, 0x86, 0x34, 0x28, 0x5a, + 0x2e, 0x95, 0x4f, 0xb5, 0x18, 0x37, 0x8b, 0x8d, 0x3f, 0x27, 0x44, 0xb9, 0xbb, 0xf8, 0x84, 0x2b, 0x48, + 0x07, 0x87, 0x9f, 0xf2, 0x8e, 0x55, 0xbf, 0xba, 0x49, 0x67, 0xe8, 0xc1, 0xd3, 0xb6, 0xc4, 0xe3, 0x58, + 0xa5, 0x61, 0xc5, 0x4a, 0xbb, 0xc1, 0xcb, 0x7c, 0x97, 0xb6, 0x50, 0x3f, 0xe5, 0x9b, 0x7f, 0xee, 0x64, + 0x23, 0xdf, 0xfe, 0x66, 0xfe, 0x6d, 0xcb, 0x8a, 0xf0, 0x0e, 0x69, 0xc5, 0x3d, 0x6b, 0x57, 0x6f, 0x55, + 0x06, 0x99, 0x04, 0x38, 0x31, 0x0f, 0xb7, 0xdd, 0x14, 0x68, 0xa3, 0x2f, 0xd8, 0xe0, 0xde, 0xab, 0x40, + 0xb1, 0x5e, 0xcf, 0xd4, 0x38, 0x56, 0x83, 0x70, 0x14, 0x0a, 0x1e, 0xda, 0xfe, 0xe7, 0x01, 0xa4, 0xa4, + 0xb4, 0xe7, 0xb3, 0xaa, 0xef, 0xdc, 0x4b, 0x1a, 0xff, 0x58, 0x68, 0xae, 0xfe, 0x5a, 0x36, 0x29, 0x4d, + 0x5d, 0xd6, 0x87, 0xd5, 0xa6, 0x49, 0x31, 0x43, 0xd3, 0xad, 0xe8, 0x03, 0x1c, 0x98, 0xd2, 0x8f, 0x6c, + 0x7f, 0x3d, 0xce, 0xa4, 0x14, 0x35, 0x13, 0x2f, 0x67, 0x5f, 0x26, 0x94, 0x0d, 0x1f, 0x69, 0xe5, 0x73, + 0xe5, 0xec, 0xe6, 0xed, 0x5a, 0x66, 0x11, 0x1f, 0xf9, 0xf4, 0xb0, 0x2a, 0x8d, 0xdd, 0x19, 0x08, 0x6e, + 0x5b, 0x9d, 0xc0, 0xad, 0xc8, 0x6a, 0x0b, 0xc1, 0x23, 0x0f, 0x1b, 0x71, 0x5f, 0xfc, 0x40, 0x04, 0xdf, + 0xc4, 0xa7, 0xd5, 0xf7, 0x8a, 0x4d, 0xc3, 0x1a, 0xbf, 0x83, 0x0a, 0xe6, 0xe3, 0xbf, 0xd2, 0x1c, 0x87, + 0xfa, 0x51, 0x96, 0x54, 0x9e, 0x13, 0x0f, 0x6a, 0x08, 0x1b, 0xaf, 0xcf, 0x41, 0x70, 0xae, 0x20, 0x1c, + 0x78, 0xa3, 0x82, 0x9a, 0x01, 0xdb, 0xa5, 0x78, 0xa2, 0xef, 0x96, 0x8f, 0x2a, 0xb6, 0x66, 0x8d, 0x81, + 0x14, 0xdf, 0xcc, 0x65, 0xd7, 0x03, 0x8f, 0x55, 0x58, 0xbe, 0x7c, 0xdd, 0x92, 0x46, 0xd5, 0x22, 0x47, + 0x91, 0x52, 0x60, 0xa4, 0x0e, 0x59, 0xc4, 0x8b, 0x08, 0xa1, 0xed, 0x61, 0x42, 0x7f, 0xd3, 0x03, 0x91, + 0x7c, 0x6b, 0x34, 0xb7, 0x01, 0xa4, 0xba, 0x9a, 0x38, 0x15, 0xd4, 0x82, 0x8a, 0x22, 0x8c, 0xd2, 0x09, + 0xda, 0x13, 0x76, 0x26, 0xe2, 0x02, 0x9a, 0xab, 0xf6, 0xc2, 0x00, 0xbf, 0x7f, 0xd6, 0x3c, 0xf6, 0xd4, + 0x3b, 0xb6, 0x18, 0xb3, 0x1a, 0xc4, 0x8e, 0x09, 0x61, 0x35, 0x89, 0xd7, 0x4a, 0x69, 0x54, 0x2e, 0x90, + 0x9c, 0xe0, 0xdc, 0x9c, 0x57, 0xc7, 0x7f, 0x7d, 0x89, 0xb9, 0x66, 0xde, 0x20, 0x00, 0x53, 0xa5, 0x8e, + 0xa5, 0x8f, 0x23, 0x74, 0x51, 0x39, 0x61, 0x63, 0x8a, 0x30, 0xca, 0x49, 0xef, 0x0e, 0xec, 0x67, 0x9d, + 0x92, 0x7e, 0x38, 0x5b, 0x5d, 0xa7, 0xd4, 0xd3, 0xc1, 0xa5, 0x91, 0x69, 0xb4, 0x63, 0x0b, 0x87, 0x4a, + 0x1d, 0x96, 0x9e, 0x45, 0xd1, 0xfe, 0x37, 0x82, 0x08, 0x9f, 0x43, 0x85, 0x02, 0x49, 0x55, 0x09, 0x3b, + 0x30, 0x8e, 0x19, 0x64, 0xd3, 0x07, 0x91, 0x52, 0x71, 0xaa, 0x88, 0x6c, 0x3d, 0x9b, 0x64, 0xd8, 0x46, + 0xc8, 0x8c, 0xa1, 0x34, 0x1f, 0xd2, 0xf7, 0x2b, 0x76, 0x67, 0x9d, 0x4f, 0x25, 0x8f, 0x64, 0x7b, 0xc0, + 0x48, 0x20, 0xe4, 0x27, 0x76, 0xc9, 0xec, 0x0d, 0x01, 0x46, 0x46, 0x52, 0x76, 0x3a, 0x49, 0xd8, 0x22, + 0xc9, 0xd2, 0x5b, 0x60, 0x39, 0x03, 0xeb, 0xd6, 0x33, 0x89, 0x52, 0x25, 0x9b, 0x83, 0xa7, 0x40, 0xa4, + 0x20, 0xd6, 0x9d, 0x23, 0xae, 0xbb, 0xdf, 0x06, 0xa9, 0x2d, 0x88, 0xa4, 0x6f, 0xfc, 0xd8, 0xd8, 0x1a, + 0x47, 0xb6, 0xec, 0x99, 0xb6, 0xce, 0xa0, 0x48, 0x9c, 0xc8, 0x3e, 0xf1, 0x57, 0x57, 0xc4, 0x05, 0x3d, + 0x53, 0x84, 0x46, 0xf2, 0xe6, 0xb9, 0xeb, 0xa1, 0x2c, 0xe4, 0x96, 0x9b, 0x8d, 0x6d, 0xf9, 0xb3, 0xef, + 0x57, 0x4b, 0x7d, 0x40, 0x13, 0x41, 0xc2, 0xf5, 0x55, 0xa0, 0x0f, 0x02, 0x91, 0x64, 0xe5, 0xd3, 0x87, + 0x28, 0x2c, 0x0c, 0x87, 0x91, 0xba, 0x8c, 0x69, 0x81, 0x62, 0x48, 0xe2, 0xe5, 0x44, 0xa9, 0xc1, 0x2b, + 0x7a, 0xeb, 0xa6, 0x29, 0xfd, 0xee, 0xa2, 0xe1, 0x11, 0x65, 0x5e, 0x44, 0xb9, 0xc2, 0x15, 0x92, 0x4c, + 0x54, 0x55, 0xea, 0xa4, 0xab, 0x32, 0xae, 0xa1, 0xd9, 0xce, 0xf1, 0xd8, 0x6e, 0x8a, 0xcf, 0x6b, 0x0f, + 0xf4, 0xdc, 0xab, 0xaf, 0x4f, 0x0e, 0x2d, 0x9a, 0xe6, 0x5c, 0x8b, 0xb1, 0x06, 0x5e, 0x04, 0x18, 0xff, + 0x12, 0xd4, 0x62, 0x69, 0x30, 0x31, 0x59, 0x38, 0xbf, 0xe0, 0x0a, 0x8d, 0x03, 0xe8, 0xe7, 0x0e, 0x9d, + 0xea, 0x9d, 0xc9, 0xff, 0x74, 0x85, 0x4c, 0xbb, 0x4d, 0xbd, 0xf7, 0x00, 0xa6, 0x2e, 0x77, 0xb2, 0x6e, + 0x50, 0xb1, 0x3e, 0x2d, 0x39, 0x60, 0xc9, 0x13, 0x36, 0x0c, 0x84, 0xc8, 0x7e, 0x80, 0x1e, 0xd3, 0xdf, + 0x3d, 0xb0, 0xe2, 0x76, 0x04, 0x50, 0x8c, 0xb7, 0x30, 0xc5, 0xa0, 0x52, 0xc0, 0x68, 0xab, 0xe5, 0x82, + 0x6b, 0x01, 0xbe, 0x9f, 0x62, 0xe3, 0x3b, 0x9a, 0xf8, 0xed, 0xb6, 0x66, 0x7c, 0x57, 0xcb, 0x1a, 0xa8, + 0x79, 0x74, 0x3b, 0x77, 0xa7, 0x43, 0x2f, 0x75, 0xfe, 0x3a, 0xe2, 0x11, 0xf9, 0x6a, 0xf4, 0x1a, 0xde, + 0xf1, 0xe1, 0xc5, 0x07, 0x25, 0x6f, 0xe5, 0xfa, 0x2b, 0xcc, 0xab, 0xe5, 0x2c, 0xf8, 0x21, 0x6d, 0x34, + 0x10, 0xe6, 0x37, 0x85, 0x06, 0xd4, 0x27, 0x34, 0x34, 0x58, 0x33, 0x2d, 0x15, 0x3a, 0x77, 0xa1, 0x62, + 0xc4, 0xc5, 0xf1, 0x8d, 0x9f, 0x31, 0xb0, 0xc1, 0x42, 0x88, 0x0c, 0xad, 0x22, 0x29, 0x98, 0x17, 0x20, + 0x61, 0x5a, 0xb2, 0x6b, 0x7c, 0x13, 0x44, 0x2e, 0x43, 0x17, 0x8a, 0xad, 0xee, 0x43, 0x65, 0x10, 0xc9, + 0x1b, 0xc9, 0xd5, 0xd7, 0x35, 0xeb, 0x94, 0x53, 0xcf, 0x39, 0xce, 0xf5, 0x12, 0x0e, 0x28, 0x60, 0x37, + 0x75, 0xf0, 0x48, 0x3f, 0x01, 0xc3, 0xc4, 0x8b, 0x5b, 0x06, 0x0c, 0xa7, 0xf3, 0xa5, 0x4d, 0x7c, 0x7c, + 0x99, 0xa4, 0x81, 0xc9, 0x30, 0x81, 0xc6, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa2, 0x81, 0xbe, 0x04, 0x81, + 0xbb, 0x03, 0xab, 0x65, 0x67, 0x60, 0xa3, 0x51, 0x2f, 0xec, 0xc7, 0x03, 0x2d, 0xa8, 0xb2, 0x01, 0x46, + 0x59, 0xf0, 0xfb, 0x34, 0xeb, 0x76, 0xb4, 0x61, 0xe4, 0x04, 0x4d, 0xa2, 0x4d, 0x16, 0xd4, 0x58, 0xe3, + 0xe1, 0xc5, 0x89, 0x19, 0xc7, 0x4c, 0x4c, 0x07, 0x20, 0xaa, 0xfb, 0x87, 0xa9, 0x48, 0x15, 0x23, 0x72, + 0xa2, 0x48, 0x3a, 0x4d, 0x1a, 0xe9, 0xb9, 0x5b, 0x85, 0x8a, 0x52, 0xab, 0xaa, 0x94, 0xe7, 0xaa, 0x64, + 0x1a, 0x8b, 0x99, 0x7d, 0x7e, 0x6c, 0x6e, 0x57, 0x0b, 0x59, 0x08, 0xcc, 0x54, 0x91, 0x55, 0xf5, 0xe6, + 0xf1, 0x10, 0xc9, 0x8d, 0x64, 0x89, 0x78, 0x72, 0x7a, 0xba, 0xe3, 0x92, 0x1d, 0xa5, 0x2a, 0x4c, 0x1f, + 0xd7, 0x6b, 0xeb, 0x12, 0x1b, 0xf3, 0x39, 0x6b, 0xe8, 0xf9, 0x8e, 0x4a, 0xcf, 0x1e, 0xbf, 0xc3, 0xb6, + 0xfb, 0x7a, 0x13, 0x54, 0xc1, 0x21, 0x87, 0x3e, 0x59, 0x18, 0x5d, 0xb9, 0x00, 0x30, 0x08, 0x4d, 0x97, + 0x86, 0x47, 0x98, 0xd7, 0x9e, 0xb9, 0xdf, 0x30, 0x75, 0x6c, 0xa1, 0xfa, 0xa7, 0xa8, 0x08, 0x80, 0xf7, + 0x4f, 0x7d, 0x93, 0x64, 0x2d, 0x9c, 0xeb, 0x5e, 0x01, 0x28, 0xce, 0xd6, 0xab, 0x09, 0x6a, 0x4f, 0x01, + 0x5e, 0x5a, 0x03, 0x2b, 0x42, 0x70, 0x23, 0x1e, 0x7f, 0xf1, 0xbc, 0xd0, 0x87, 0xe8, 0xb5, 0x27, 0x02, + 0x7d } }; pcpp::LdapBindRequestLayer bindRequestLayer(2, 3, "", saslAuthentication); auto expectedBindRequestLayer = bindRequestPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(expectedBindRequestLayer); - PTF_ASSERT_EQUAL(bindRequestLayer.getLdapOperationAsn1Record()->getSubRecords().size(), expectedBindRequestLayer->getLdapOperationAsn1Record()->getSubRecords().size()); - PTF_ASSERT_TRUE(std::equal(bindRequestLayer.getLdapOperationAsn1Record()->getSubRecords().begin(), + PTF_ASSERT_EQUAL(bindRequestLayer.getLdapOperationAsn1Record()->getSubRecords().size(), + expectedBindRequestLayer->getLdapOperationAsn1Record()->getSubRecords().size()); + PTF_ASSERT_TRUE(std::equal( + bindRequestLayer.getLdapOperationAsn1Record()->getSubRecords().begin(), bindRequestLayer.getLdapOperationAsn1Record()->getSubRecords().end(), expectedBindRequestLayer->getLdapOperationAsn1Record()->getSubRecords().begin(), - [](pcpp::Asn1Record* elem1, pcpp::Asn1Record* elem2) { return elem1->encode() == elem2->encode();})); + [](pcpp::Asn1Record* elem1, pcpp::Asn1Record* elem2) { return elem1->encode() == elem2->encode(); })); } // BindResponse with server sasl credentials @@ -529,28 +636,43 @@ PTF_TEST_CASE(LdapCreationTest) pcpp::Packet bindResponsePacket(&rawPacket1); std::vector serverSaslCredentials = { - 0xa1, 0x81, 0xa1, 0x30, 0x81, 0x9e, 0xa0, 0x03, 0x0a, 0x01, 0x00, 0xa1, 0x0b, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, 0x02, 0xa2, 0x81, 0x89, 0x04, 0x81, 0x86, 0x60, 0x81, 0x83, 0x06, 0x09, 0x2a, 0x86, 0x48, - 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x02, 0x00, 0x6f, 0x74, 0x30, 0x72, 0xa0, 0x03, 0x02, 0x01, 0x05, 0xa1, 0x03, 0x02, 0x01, 0x0f, 0xa2, 0x66, 0x30, 0x64, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa2, 0x5d, 0x04, 0x5b, 0x4a, 0x9f, 0x10, - 0xab, 0x89, 0x96, 0xfa, 0x43, 0xf2, 0xfb, 0x40, 0x92, 0xa7, 0x6c, 0xc3, 0xfa, 0x6c, 0x1f, 0x00, 0x11, 0x67, 0xfa, 0xc9, 0x04, 0xda, 0xb0, 0x67, 0xf5, 0xf2, 0xda, 0x59, 0xa7, 0x54, 0x90, 0x57, 0xbd, 0x3e, 0xb4, 0x6c, 0xb4, 0x67, - 0xfd, 0x3b, 0x01, 0xd7, 0x3f, 0x50, 0x51, 0xaa, 0x63, 0x2e, 0xd8, 0xd6, 0xa6, 0xe5, 0x81, 0xbb, 0xab, 0x17, 0x80, 0xfa, 0xab, 0xac, 0x51, 0x52, 0x84, 0x13, 0x9c, 0xfb, 0x44, 0xc2, 0x04, 0xae, 0x1e, 0xc2, 0x5a, 0x2d, 0x58, 0x90, - 0x9d, 0x22, 0xff, 0x52, 0x34, 0x9e, 0x6d, 0x2e, 0x4d, 0x83, 0x5b, 0x98}; + 0xa1, 0x81, 0xa1, 0x30, 0x81, 0x9e, 0xa0, 0x03, 0x0a, 0x01, 0x00, 0xa1, 0x0b, 0x06, 0x09, 0x2a, 0x86, + 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, 0x02, 0xa2, 0x81, 0x89, 0x04, 0x81, 0x86, 0x60, 0x81, 0x83, 0x06, + 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02, 0x02, 0x00, 0x6f, 0x74, 0x30, 0x72, 0xa0, + 0x03, 0x02, 0x01, 0x05, 0xa1, 0x03, 0x02, 0x01, 0x0f, 0xa2, 0x66, 0x30, 0x64, 0xa0, 0x03, 0x02, 0x01, + 0x17, 0xa2, 0x5d, 0x04, 0x5b, 0x4a, 0x9f, 0x10, 0xab, 0x89, 0x96, 0xfa, 0x43, 0xf2, 0xfb, 0x40, 0x92, + 0xa7, 0x6c, 0xc3, 0xfa, 0x6c, 0x1f, 0x00, 0x11, 0x67, 0xfa, 0xc9, 0x04, 0xda, 0xb0, 0x67, 0xf5, 0xf2, + 0xda, 0x59, 0xa7, 0x54, 0x90, 0x57, 0xbd, 0x3e, 0xb4, 0x6c, 0xb4, 0x67, 0xfd, 0x3b, 0x01, 0xd7, 0x3f, + 0x50, 0x51, 0xaa, 0x63, 0x2e, 0xd8, 0xd6, 0xa6, 0xe5, 0x81, 0xbb, 0xab, 0x17, 0x80, 0xfa, 0xab, 0xac, + 0x51, 0x52, 0x84, 0x13, 0x9c, 0xfb, 0x44, 0xc2, 0x04, 0xae, 0x1e, 0xc2, 0x5a, 0x2d, 0x58, 0x90, 0x9d, + 0x22, 0xff, 0x52, 0x34, 0x9e, 0x6d, 0x2e, 0x4d, 0x83, 0x5b, 0x98 + }; - pcpp::LdapBindResponseLayer bindResponseLayer(215, pcpp::LdapResultCode::Success, "", "", {}, serverSaslCredentials); + pcpp::LdapBindResponseLayer bindResponseLayer(215, pcpp::LdapResultCode::Success, "", "", {}, + serverSaslCredentials); auto expectedBindResponseLayer = bindResponsePacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(expectedBindResponseLayer); - PTF_ASSERT_EQUAL(bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().size(), expectedBindResponseLayer->getLdapOperationAsn1Record()->getSubRecords().size()); + PTF_ASSERT_EQUAL(bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().size(), + expectedBindResponseLayer->getLdapOperationAsn1Record()->getSubRecords().size()); for (int i = 0; i < 3; i++) { - PTF_ASSERT_EQUAL(bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().at(i)->toString(), + PTF_ASSERT_EQUAL( + bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().at(i)->toString(), expectedBindResponseLayer->getLdapOperationAsn1Record()->getSubRecords().at(i)->toString()); } - auto actualServerSaslCredentialsRecord = bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().at(3)->castAs(); - auto expectedServerSaslCredentialsRecord = expectedBindResponseLayer->getLdapOperationAsn1Record()->getSubRecords().at(3)->castAs(); - PTF_ASSERT_BUF_COMPARE(actualServerSaslCredentialsRecord->getValue(), expectedServerSaslCredentialsRecord->getValue(), expectedServerSaslCredentialsRecord->getValueLength()) + auto actualServerSaslCredentialsRecord = + bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().at(3)->castAs(); + auto expectedServerSaslCredentialsRecord = expectedBindResponseLayer->getLdapOperationAsn1Record() + ->getSubRecords() + .at(3) + ->castAs(); + PTF_ASSERT_BUF_COMPARE(actualServerSaslCredentialsRecord->getValue(), + expectedServerSaslCredentialsRecord->getValue(), + expectedServerSaslCredentialsRecord->getValueLength()) } // BindResponse without server sasl credentials @@ -563,11 +685,13 @@ PTF_TEST_CASE(LdapCreationTest) auto expectedBindResponseLayer = bindResponsePacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(expectedBindResponseLayer); - PTF_ASSERT_EQUAL(bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().size(), expectedBindResponseLayer->getLdapOperationAsn1Record()->getSubRecords().size()); - PTF_ASSERT_TRUE(std::equal(bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().begin(), + PTF_ASSERT_EQUAL(bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().size(), + expectedBindResponseLayer->getLdapOperationAsn1Record()->getSubRecords().size()); + PTF_ASSERT_TRUE(std::equal( + bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().begin(), bindResponseLayer.getLdapOperationAsn1Record()->getSubRecords().end(), expectedBindResponseLayer->getLdapOperationAsn1Record()->getSubRecords().begin(), - [](pcpp::Asn1Record* elem1, pcpp::Asn1Record* elem2) { return elem1->encode() == elem2->encode();})); + [](pcpp::Asn1Record* elem1, pcpp::Asn1Record* elem2) { return elem1->encode() == elem2->encode(); })); } // UnbindRequest @@ -581,7 +705,7 @@ PTF_TEST_CASE(LdapCreationTest) PTF_ASSERT_NOT_NULL(expectedUnbindRequestLayer); PTF_ASSERT_BUF_COMPARE(unbindRequestLayer.getData(), expectedUnbindRequestLayer->getData(), - expectedUnbindRequestLayer->getDataLen()); + expectedUnbindRequestLayer->getDataLen()); } // SearchRequest @@ -591,33 +715,31 @@ PTF_TEST_CASE(LdapCreationTest) pcpp::Asn1OctetStringRecord filterSubRecord1("objectClass"); pcpp::Asn1OctetStringRecord filterSubRecord2("subschema"); - pcpp::Asn1ConstructedRecord filterRecord(pcpp::Asn1TagClass::ContextSpecific, 3, {&filterSubRecord1, &filterSubRecord2}); - - std::vector attributes = { - "objectClasses", - "attributeTypes", - "ldapSyntaxes", - "matchingRules", - "matchingRuleUse", - "dITContentRules", - "dITStructureRules", - "nameForms", - "createTimestamp", - "modifyTimestamp", - "*", - "+" - }; + pcpp::Asn1ConstructedRecord filterRecord(pcpp::Asn1TagClass::ContextSpecific, 3, + { &filterSubRecord1, &filterSubRecord2 }); + + std::vector attributes = { "objectClasses", + "attributeTypes", + "ldapSyntaxes", + "matchingRules", + "matchingRuleUse", + "dITContentRules", + "dITStructureRules", + "nameForms", + "createTimestamp", + "modifyTimestamp", + "*", + "+" }; pcpp::LdapSearchRequestLayer searchRequestLayer( 9, "cn=schema", pcpp::LdapSearchRequestLayer::SearchRequestScope::BaseObject, - pcpp::LdapSearchRequestLayer::DerefAliases::DerefAlways, - 0, 0, false, &filterRecord, attributes); + pcpp::LdapSearchRequestLayer::DerefAliases::DerefAlways, 0, 0, false, &filterRecord, attributes); auto expectedSearchRequestLayer = searchRequestPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(expectedSearchRequestLayer); PTF_ASSERT_BUF_COMPARE(searchRequestLayer.getData(), expectedSearchRequestLayer->getData(), - expectedSearchRequestLayer->getDataLen()); + expectedSearchRequestLayer->getDataLen()); } // SearchResultEntry @@ -626,19 +748,21 @@ PTF_TEST_CASE(LdapCreationTest) pcpp::Packet searchResultEntryPacket(&rawPacket1); std::vector attributes = { - {"objectclass", {"inetOrgPerson", "organizationalPerson", "person", "top"}}, - {"sn", {"Young"}}, - {"cn", {"b.smith"}}, - {"givenname", {"Beatrix"}} + { "objectclass", { "inetOrgPerson", "organizationalPerson", "person", "top" } }, + { "sn", { "Young" } }, + { "cn", { "b.smith" } }, + { "givenname", { "Beatrix" } } }; - pcpp::LdapSearchResultEntryLayer searchResultEntryLayer(16, "cn=b.smith,ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org", attributes); + pcpp::LdapSearchResultEntryLayer searchResultEntryLayer( + 16, "cn=b.smith,ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org", attributes); - auto expectedSearchResultEntryLayer = searchResultEntryPacket.getLayerOfType(); + auto expectedSearchResultEntryLayer = + searchResultEntryPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(expectedSearchResultEntryLayer); PTF_ASSERT_BUF_COMPARE(searchResultEntryLayer.getData(), expectedSearchResultEntryLayer->getData(), - expectedSearchResultEntryLayer->getDataLen()); + expectedSearchResultEntryLayer->getDataLen()); } // LdapSearchResultDoneLayer @@ -652,7 +776,7 @@ PTF_TEST_CASE(LdapCreationTest) PTF_ASSERT_NOT_NULL(expectedSearchResultDoneLayer); PTF_ASSERT_BUF_COMPARE(searchResultDoneLayer.getData(), expectedSearchResultDoneLayer->getData(), - expectedSearchResultDoneLayer->getDataLen()); + expectedSearchResultDoneLayer->getDataLen()); } // LdapModifyResponseLayer @@ -666,7 +790,7 @@ PTF_TEST_CASE(LdapCreationTest) PTF_ASSERT_NOT_NULL(expectedModifyResponseLayer); PTF_ASSERT_BUF_COMPARE(modifyResponseLayer.getData(), expectedModifyResponseLayer->getData(), - expectedModifyResponseLayer->getDataLen()); + expectedModifyResponseLayer->getDataLen()); } // LdapAddResponseLayer @@ -680,7 +804,7 @@ PTF_TEST_CASE(LdapCreationTest) PTF_ASSERT_NOT_NULL(expectedAddResponseLayer); PTF_ASSERT_BUF_COMPARE(addResponseLayer.getData(), expectedAddResponseLayer->getData(), - expectedAddResponseLayer->getDataLen()); + expectedAddResponseLayer->getDataLen()); } // LdapDeleteResponseLayer @@ -688,19 +812,18 @@ PTF_TEST_CASE(LdapCreationTest) READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ldap_delete_response.dat"); pcpp::Packet deleteResponsePacket(&rawPacket1); - std::vector referral = { - "ldap://ldap.example.com/dc=example,dc=com", - "ldap://ldap.example.com/dc=example,dc=com?objectClass?one" - }; + std::vector referral = { "ldap://ldap.example.com/dc=example,dc=com", + "ldap://ldap.example.com/dc=example,dc=com?objectClass?one" }; - pcpp::LdapDeleteResponseLayer deleteResponseLayer(27, pcpp::LdapResultCode::NoSuchObject, "ou=People,dc=example,dc=com", - "LDAP: error code 32 - No such object", referral); + pcpp::LdapDeleteResponseLayer deleteResponseLayer(27, pcpp::LdapResultCode::NoSuchObject, + "ou=People,dc=example,dc=com", + "LDAP: error code 32 - No such object", referral); auto expectedDeleteResponseLayer = deleteResponsePacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(expectedDeleteResponseLayer); PTF_ASSERT_BUF_COMPARE(deleteResponseLayer.getData(), expectedDeleteResponseLayer->getData(), - expectedDeleteResponseLayer->getDataLen()); + expectedDeleteResponseLayer->getDataLen()); } // LdapModifyDNResponseLayer @@ -708,13 +831,14 @@ PTF_TEST_CASE(LdapCreationTest) READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ldap_modify_dn_response.dat"); pcpp::Packet modifyDNResponsePacket(&rawPacket1); - pcpp::LdapModifyDNResponseLayer modifyDNResponseLayer(15, pcpp::LdapResultCode::NoSuchObject, "ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org", ""); + pcpp::LdapModifyDNResponseLayer modifyDNResponseLayer(15, pcpp::LdapResultCode::NoSuchObject, + "ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org", ""); auto expectedModifyDNResponseLayer = modifyDNResponsePacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(expectedModifyDNResponseLayer); PTF_ASSERT_BUF_COMPARE(modifyDNResponseLayer.getData(), expectedModifyDNResponseLayer->getData(), - expectedModifyDNResponseLayer->getDataLen()); + expectedModifyDNResponseLayer->getDataLen()); } // LdapCompareResponseLayer @@ -728,6 +852,6 @@ PTF_TEST_CASE(LdapCreationTest) PTF_ASSERT_NOT_NULL(expectedCompareResponseLayer); PTF_ASSERT_BUF_COMPARE(compareResponseLayer.getData(), expectedCompareResponseLayer->getData(), - expectedCompareResponseLayer->getDataLen()); + expectedCompareResponseLayer->getDataLen()); } -} // LdapCreationTest +} // LdapCreationTest diff --git a/Tests/Packet++Test/Tests/NflogTests.cpp b/Tests/Packet++Test/Tests/NflogTests.cpp index ec8a5fb1df..adc7af9093 100644 --- a/Tests/Packet++Test/Tests/NflogTests.cpp +++ b/Tests/Packet++Test/Tests/NflogTests.cpp @@ -8,7 +8,6 @@ #include "SystemUtils.h" #include "GeneralUtils.h" - PTF_TEST_CASE(NflogPacketParsingTest) { timeval time; @@ -29,32 +28,31 @@ PTF_TEST_CASE(NflogPacketParsingTest) PTF_ASSERT_EQUAL(nflogLayer->getNextLayer()->getProtocol(), pcpp::IPv4, enum); - pcpp::NflogTlvType expectedTypes[6] = { - pcpp::NflogTlvType::NFULA_PACKET_HDR, - pcpp::NflogTlvType::NFULA_PREFIX, - pcpp::NflogTlvType::NFULA_IFINDEX_OUTDEV, - pcpp::NflogTlvType::NFULA_UID, - pcpp::NflogTlvType::NFULA_GID, - pcpp::NflogTlvType::NFULA_PAYLOAD - }; - - int optSizes[6] = {8, 8, 8, 8, 8, 68}; - std::string optDataAsHexString[6] = { - "0800010000000300", - "05000a0000000000", - "0800050000000002", - "08000b0000000000", - "08000e0000000000", - "410009004500003d021040004011208f0a00020f0a000203a542003500294156c04e0100000100000000000003777777076578616d706c65036e657400000100012f0a31" - }; - - for (int i = 0; i < 6; i++) { + pcpp::NflogTlvType expectedTypes[6] = { pcpp::NflogTlvType::NFULA_PACKET_HDR, + pcpp::NflogTlvType::NFULA_PREFIX, + pcpp::NflogTlvType::NFULA_IFINDEX_OUTDEV, + pcpp::NflogTlvType::NFULA_UID, + pcpp::NflogTlvType::NFULA_GID, + pcpp::NflogTlvType::NFULA_PAYLOAD }; + + int optSizes[6] = { 8, 8, 8, 8, 8, 68 }; + std::string optDataAsHexString[6] = { "0800010000000300", + "05000a0000000000", + "0800050000000002", + "08000b0000000000", + "08000e0000000000", + "410009004500003d021040004011208f0a00020f0a000203a542003500294156c04e01000001" + "00000000000003777777076578616d706c65036e657400000100012f0a31" }; + + for (int i = 0; i < 6; i++) + { pcpp::NflogTlv tlv = nflogLayer->getTlvByType(expectedTypes[i]); PTF_ASSERT_EQUAL(tlv.getTotalSize(), optSizes[i]); PTF_ASSERT_EQUAL(pcpp::byteArrayToHexString(tlv.getRecordBasePtr(), optSizes[i]), optDataAsHexString[i]); } - /// sum of all TLVs before payload + size of nflog_header + size of (recordLength + recordType) variables of payload TLV + /// sum of all TLVs before payload + size of nflog_header + size of (recordLength + recordType) variables of payload + /// TLV PTF_ASSERT_EQUAL(nflogLayer->getHeaderLen(), 48); } diff --git a/Tests/Packet++Test/Tests/NtpTests.cpp b/Tests/Packet++Test/Tests/NtpTests.cpp index 06cf056036..3373968e3c 100644 --- a/Tests/Packet++Test/Tests/NtpTests.cpp +++ b/Tests/Packet++Test/Tests/NtpTests.cpp @@ -16,276 +16,277 @@ PTF_TEST_CASE(NtpMethodsTests) { - double val = 12345.125; - PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertFromTimestampFormat(pcpp::NtpLayer::convertToTimestampFormat(val)), val); - PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertFromShortFormat(pcpp::NtpLayer::convertToShortFormat(val)), val); + double val = 12345.125; + PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertFromTimestampFormat(pcpp::NtpLayer::convertToTimestampFormat(val)), val); + PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertFromShortFormat(pcpp::NtpLayer::convertToShortFormat(val)), val); - // First check the epoch is correct + // First check the epoch is correct #if defined(_WIN32) - PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(0.0), std::string("1970-01-01T00:00:00.0000Z")); - PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(uint64_t(0)), std::string("1970-01-01T00:00:00.0000Z")); + PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(0.0), std::string("1970-01-01T00:00:00.0000Z")); + PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(uint64_t(0)), std::string("1970-01-01T00:00:00.0000Z")); #else - PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(0.0), std::string("1970-01-01T00:00:00.0000Z")); - PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(uint64_t(0)), std::string("1900-01-01T00:00:00.0000Z")); + PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(0.0), std::string("1970-01-01T00:00:00.0000Z")); + PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(uint64_t(0)), std::string("1900-01-01T00:00:00.0000Z")); #endif - PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(1642879410.0), "2022-01-22T19:23:30.0000Z"); - PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(pcpp::NtpLayer::convertToTimestampFormat(1642879410.0)), "2022-01-22T19:23:30.0000Z"); + PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(1642879410.0), "2022-01-22T19:23:30.0000Z"); + PTF_ASSERT_EQUAL(pcpp::NtpLayer::convertToIsoFormat(pcpp::NtpLayer::convertToTimestampFormat(1642879410.0)), + "2022-01-22T19:23:30.0000Z"); -} // NtpMethodsTests +} // NtpMethodsTests PTF_TEST_CASE(NtpParsingV3Tests) { - timeval time; - gettimeofday(&time, nullptr); - - READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ntpv3.dat"); - - pcpp::Packet ntpPacket(&rawPacket1); - pcpp::NtpLayer *ntpLayer = ntpPacket.getLayerOfType(); - - PTF_ASSERT_NOT_NULL(ntpLayer); - PTF_ASSERT_EQUAL(ntpLayer->getVersion(), 3); - PTF_ASSERT_EQUAL(ntpLayer->getLeapIndicator(), pcpp::NtpLayer::NoWarning); - PTF_ASSERT_EQUAL(ntpLayer->getMode(), pcpp::NtpLayer::Server); - PTF_ASSERT_EQUAL(ntpLayer->getModeString(), "Server"); - PTF_ASSERT_EQUAL(ntpLayer->getStratum(), 0); - PTF_ASSERT_EQUAL(ntpLayer->getPollInterval(), 4); - PTF_ASSERT_EQUAL(ntpLayer->getPrecision(), int8_t(-6)); - // NTPv3 pcap is a bit useless, too many zeros but these fields same with v4 - PTF_ASSERT_EQUAL(ntpLayer->getRootDelay(), 0); - PTF_ASSERT_EQUAL(ntpLayer->getRootDispersion(), 0); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifier(), 0); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestamp(), 0); - PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestamp(), 0); - PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestamp(), be64toh(0xd94f4f1100000000)); - PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestamp(), be64toh(0xd94f4f1100000000)); - PTF_ASSERT_EQUAL(ntpLayer->toString(), "NTP Layer v3, Mode: Server"); - - // Since they are double it may or may not equal - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPollIntervalInSecs() - 16), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPrecisionInSecs() - 0.015625), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDelayInSecs() - 0), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDispersionInSecs() - 0), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReferenceTimestampInSecs() - -double(EPOCH_OFFSET)), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getOriginTimestampInSecs() - -double(EPOCH_OFFSET)), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReceiveTimestampInSecs() - 1436864657.0), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getTransmitTimestampInSecs() - 1436864657.0), EPSILON); + timeval time; + gettimeofday(&time, nullptr); + + READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ntpv3.dat"); + + pcpp::Packet ntpPacket(&rawPacket1); + pcpp::NtpLayer* ntpLayer = ntpPacket.getLayerOfType(); + + PTF_ASSERT_NOT_NULL(ntpLayer); + PTF_ASSERT_EQUAL(ntpLayer->getVersion(), 3); + PTF_ASSERT_EQUAL(ntpLayer->getLeapIndicator(), pcpp::NtpLayer::NoWarning); + PTF_ASSERT_EQUAL(ntpLayer->getMode(), pcpp::NtpLayer::Server); + PTF_ASSERT_EQUAL(ntpLayer->getModeString(), "Server"); + PTF_ASSERT_EQUAL(ntpLayer->getStratum(), 0); + PTF_ASSERT_EQUAL(ntpLayer->getPollInterval(), 4); + PTF_ASSERT_EQUAL(ntpLayer->getPrecision(), int8_t(-6)); + // NTPv3 pcap is a bit useless, too many zeros but these fields same with v4 + PTF_ASSERT_EQUAL(ntpLayer->getRootDelay(), 0); + PTF_ASSERT_EQUAL(ntpLayer->getRootDispersion(), 0); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifier(), 0); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestamp(), 0); + PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestamp(), 0); + PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestamp(), be64toh(0xd94f4f1100000000)); + PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestamp(), be64toh(0xd94f4f1100000000)); + PTF_ASSERT_EQUAL(ntpLayer->toString(), "NTP Layer v3, Mode: Server"); + + // Since they are double it may or may not equal + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPollIntervalInSecs() - 16), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPrecisionInSecs() - 0.015625), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDelayInSecs() - 0), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDispersionInSecs() - 0), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReferenceTimestampInSecs() - -double(EPOCH_OFFSET)), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getOriginTimestampInSecs() - -double(EPOCH_OFFSET)), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReceiveTimestampInSecs() - 1436864657.0), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getTransmitTimestampInSecs() - 1436864657.0), EPSILON); #if defined(_WIN32) - PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestampAsString(), "1970-01-01T00:00:00.0000Z"); - PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "1970-01-01T00:00:00.0000Z"); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestampAsString(), "1970-01-01T00:00:00.0000Z"); + PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "1970-01-01T00:00:00.0000Z"); #else - PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestampAsString(), "1900-01-01T00:00:00.0000Z"); - PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "1900-01-01T00:00:00.0000Z"); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestampAsString(), "1900-01-01T00:00:00.0000Z"); + PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "1900-01-01T00:00:00.0000Z"); #endif - PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestampAsString(), "2015-07-14T09:04:17.0000Z"); - PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestampAsString(), "2015-07-14T09:04:17.0000Z"); + PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestampAsString(), "2015-07-14T09:04:17.0000Z"); + PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestampAsString(), "2015-07-14T09:04:17.0000Z"); -} // NtpParsingV3Tests +} // NtpParsingV3Tests PTF_TEST_CASE(NtpParsingV4Tests) { - timeval time; - gettimeofday(&time, nullptr); - - READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ntpv4.dat"); - - // Test Ipv4 - pcpp::Packet ntpPacket(&rawPacket1); - pcpp::NtpLayer *ntpLayer = ntpPacket.getLayerOfType(); - - PTF_ASSERT_NOT_NULL(ntpLayer); - PTF_ASSERT_EQUAL(ntpLayer->getVersion(), 4); - PTF_ASSERT_EQUAL(ntpLayer->getLeapIndicator(), pcpp::NtpLayer::NoWarning); - PTF_ASSERT_EQUAL(ntpLayer->getMode(), pcpp::NtpLayer::Client); - PTF_ASSERT_EQUAL(ntpLayer->getModeString(), "Client"); - PTF_ASSERT_EQUAL(ntpLayer->getStratum(), 2); - PTF_ASSERT_EQUAL(ntpLayer->getPollInterval(), 7); - PTF_ASSERT_EQUAL(ntpLayer->getPrecision(), int8_t(0xeb)); - PTF_ASSERT_EQUAL(ntpLayer->getRootDelay(), be32toh(0x450)); - PTF_ASSERT_EQUAL(ntpLayer->getRootDispersion(), be32toh(0x3ab)); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifier(), be32toh(0x83bc03df)); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifierString(), "131.188.3.223"); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestamp(), be64toh(0xd94f51c33165b860)); - PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestamp(), be64toh(0xd944575530336fd0)); - PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestamp(), be64toh(0xd944575531b4e978)); - PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestamp(), be64toh(0xd94f51f42d26e2f4)); - PTF_ASSERT_EQUAL(ntpLayer->toString(), "NTP Layer v4, Mode: Client"); - - // Since they are double it may or may not equal - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPollIntervalInSecs() - 128), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPrecisionInSecs() - 0.0000004), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDelayInSecs() - 0.0168457), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDispersionInSecs() - 0.014328), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReferenceTimestampInSecs() - 1436865347.192958377), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getOriginTimestampInSecs() - 1436145877.188284862), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReceiveTimestampInSecs() - 1436145877.194166747), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getTransmitTimestampInSecs() - 1436865396.176374611), EPSILON); - - PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestampAsString(), "2015-07-14T09:15:47.1930Z"); - PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "2015-07-06T01:24:37.1883Z"); - PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestampAsString(), "2015-07-06T01:24:37.1942Z"); - PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestampAsString(), "2015-07-14T09:16:36.1764Z"); - - // Test Ipv6 - READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/ntpv4Ipv6_withAuth.dat"); - - ntpPacket = pcpp::Packet(&rawPacket2); - ntpLayer = ntpPacket.getLayerOfType(); - - PTF_ASSERT_NOT_NULL(ntpLayer); - PTF_ASSERT_EQUAL(ntpLayer->getVersion(), 4); - PTF_ASSERT_EQUAL(ntpLayer->getLeapIndicator(), pcpp::NtpLayer::NoWarning); - PTF_ASSERT_EQUAL(ntpLayer->getMode(), pcpp::NtpLayer::Client); - PTF_ASSERT_EQUAL(ntpLayer->getModeString(), "Client"); - PTF_ASSERT_EQUAL(ntpLayer->getStratum(), 2); - PTF_ASSERT_EQUAL(ntpLayer->getPollInterval(), 6); - PTF_ASSERT_EQUAL(ntpLayer->getPrecision(), int8_t(0xe8)); - PTF_ASSERT_EQUAL(ntpLayer->getRootDelay(), be32toh(0x91)); - PTF_ASSERT_EQUAL(ntpLayer->getRootDispersion(), be32toh(0x6b7)); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifier(), be32toh(0xb6a580db)); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifierString(), "182.165.128.219"); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestamp(), be64toh(0xdcd2a7d77a05d46a)); - PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestamp(), 0); - PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestamp(), 0); - PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestamp(), be64toh(0xdcd2aa817b9f9bdc)); - PTF_ASSERT_EQUAL(ntpLayer->getKeyID(), be32toh(1)); - PTF_ASSERT_EQUAL(ntpLayer->getDigest(), "ac017b69915ce5a7a9fb73ac8bd1603b"); // MD5 - PTF_ASSERT_EQUAL(ntpLayer->toString(), "NTP Layer v4, Mode: Client"); - - // Since they are double it may or may not equal - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPollIntervalInSecs() - 64), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPrecisionInSecs() - 0.000000059), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDelayInSecs() - 0.002213), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDispersionInSecs() - 0.02623), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReferenceTimestampInSecs() - 1495804247.476651454), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getOriginTimestampInSecs() - -double(EPOCH_OFFSET)), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReceiveTimestampInSecs() - -double(EPOCH_OFFSET)), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getTransmitTimestampInSecs() - 1495804929.482904187), EPSILON); - - PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestampAsString(), "2017-05-26T13:10:47.4767Z"); + timeval time; + gettimeofday(&time, nullptr); + + READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ntpv4.dat"); + + // Test Ipv4 + pcpp::Packet ntpPacket(&rawPacket1); + pcpp::NtpLayer* ntpLayer = ntpPacket.getLayerOfType(); + + PTF_ASSERT_NOT_NULL(ntpLayer); + PTF_ASSERT_EQUAL(ntpLayer->getVersion(), 4); + PTF_ASSERT_EQUAL(ntpLayer->getLeapIndicator(), pcpp::NtpLayer::NoWarning); + PTF_ASSERT_EQUAL(ntpLayer->getMode(), pcpp::NtpLayer::Client); + PTF_ASSERT_EQUAL(ntpLayer->getModeString(), "Client"); + PTF_ASSERT_EQUAL(ntpLayer->getStratum(), 2); + PTF_ASSERT_EQUAL(ntpLayer->getPollInterval(), 7); + PTF_ASSERT_EQUAL(ntpLayer->getPrecision(), int8_t(0xeb)); + PTF_ASSERT_EQUAL(ntpLayer->getRootDelay(), be32toh(0x450)); + PTF_ASSERT_EQUAL(ntpLayer->getRootDispersion(), be32toh(0x3ab)); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifier(), be32toh(0x83bc03df)); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifierString(), "131.188.3.223"); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestamp(), be64toh(0xd94f51c33165b860)); + PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestamp(), be64toh(0xd944575530336fd0)); + PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestamp(), be64toh(0xd944575531b4e978)); + PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestamp(), be64toh(0xd94f51f42d26e2f4)); + PTF_ASSERT_EQUAL(ntpLayer->toString(), "NTP Layer v4, Mode: Client"); + + // Since they are double it may or may not equal + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPollIntervalInSecs() - 128), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPrecisionInSecs() - 0.0000004), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDelayInSecs() - 0.0168457), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDispersionInSecs() - 0.014328), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReferenceTimestampInSecs() - 1436865347.192958377), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getOriginTimestampInSecs() - 1436145877.188284862), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReceiveTimestampInSecs() - 1436145877.194166747), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getTransmitTimestampInSecs() - 1436865396.176374611), EPSILON); + + PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestampAsString(), "2015-07-14T09:15:47.1930Z"); + PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "2015-07-06T01:24:37.1883Z"); + PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestampAsString(), "2015-07-06T01:24:37.1942Z"); + PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestampAsString(), "2015-07-14T09:16:36.1764Z"); + + // Test Ipv6 + READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/ntpv4Ipv6_withAuth.dat"); + + ntpPacket = pcpp::Packet(&rawPacket2); + ntpLayer = ntpPacket.getLayerOfType(); + + PTF_ASSERT_NOT_NULL(ntpLayer); + PTF_ASSERT_EQUAL(ntpLayer->getVersion(), 4); + PTF_ASSERT_EQUAL(ntpLayer->getLeapIndicator(), pcpp::NtpLayer::NoWarning); + PTF_ASSERT_EQUAL(ntpLayer->getMode(), pcpp::NtpLayer::Client); + PTF_ASSERT_EQUAL(ntpLayer->getModeString(), "Client"); + PTF_ASSERT_EQUAL(ntpLayer->getStratum(), 2); + PTF_ASSERT_EQUAL(ntpLayer->getPollInterval(), 6); + PTF_ASSERT_EQUAL(ntpLayer->getPrecision(), int8_t(0xe8)); + PTF_ASSERT_EQUAL(ntpLayer->getRootDelay(), be32toh(0x91)); + PTF_ASSERT_EQUAL(ntpLayer->getRootDispersion(), be32toh(0x6b7)); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifier(), be32toh(0xb6a580db)); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifierString(), "182.165.128.219"); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestamp(), be64toh(0xdcd2a7d77a05d46a)); + PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestamp(), 0); + PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestamp(), 0); + PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestamp(), be64toh(0xdcd2aa817b9f9bdc)); + PTF_ASSERT_EQUAL(ntpLayer->getKeyID(), be32toh(1)); + PTF_ASSERT_EQUAL(ntpLayer->getDigest(), "ac017b69915ce5a7a9fb73ac8bd1603b"); // MD5 + PTF_ASSERT_EQUAL(ntpLayer->toString(), "NTP Layer v4, Mode: Client"); + + // Since they are double it may or may not equal + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPollIntervalInSecs() - 64), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPrecisionInSecs() - 0.000000059), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDelayInSecs() - 0.002213), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDispersionInSecs() - 0.02623), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReferenceTimestampInSecs() - 1495804247.476651454), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getOriginTimestampInSecs() - -double(EPOCH_OFFSET)), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReceiveTimestampInSecs() - -double(EPOCH_OFFSET)), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getTransmitTimestampInSecs() - 1495804929.482904187), EPSILON); + + PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestampAsString(), "2017-05-26T13:10:47.4767Z"); #if defined(_WIN32) - PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "1970-01-01T00:00:00.0000Z"); - PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestampAsString(), "1970-01-01T00:00:00.0000Z"); + PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "1970-01-01T00:00:00.0000Z"); + PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestampAsString(), "1970-01-01T00:00:00.0000Z"); #else - PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "1900-01-01T00:00:00.0000Z"); - PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestampAsString(), "1900-01-01T00:00:00.0000Z"); + PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "1900-01-01T00:00:00.0000Z"); + PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestampAsString(), "1900-01-01T00:00:00.0000Z"); #endif - PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestampAsString(), "2017-05-26T13:22:09.4829Z"); - - READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/ntpv4Ipv6_withAuth2.dat"); - - ntpPacket = pcpp::Packet(&rawPacket3); - ntpLayer = ntpPacket.getLayerOfType(); - - PTF_ASSERT_NOT_NULL(ntpLayer); - PTF_ASSERT_EQUAL(ntpLayer->getVersion(), 4); - PTF_ASSERT_EQUAL(ntpLayer->getLeapIndicator(), pcpp::NtpLayer::NoWarning); - PTF_ASSERT_EQUAL(ntpLayer->getMode(), pcpp::NtpLayer::Server); - PTF_ASSERT_EQUAL(ntpLayer->getModeString(), "Server"); - PTF_ASSERT_EQUAL(ntpLayer->getStratum(), 1); - PTF_ASSERT_EQUAL(ntpLayer->getPollInterval(), 10); - PTF_ASSERT_EQUAL(ntpLayer->getPrecision(), int8_t(0xee)); - PTF_ASSERT_EQUAL(ntpLayer->getRootDelay(), 0); - PTF_ASSERT_EQUAL(ntpLayer->getRootDispersion(), be32toh(0xfb)); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifier(), static_cast(pcpp::NtpLayer::ClockSource::DCFa)); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifierString(), "Meinberg DCF77 with amplitude modulation"); - PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestamp(), be64toh(0xdcd2aabfe3771e96)); - PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestamp(), be64toh(0xdcd2aae48e835d2a)); - PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestamp(), be64toh(0xdcd2aae48e9f4d3c)); - PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestamp(), be64toh(0xdcd2aae48ece4367)); - PTF_ASSERT_EQUAL(ntpLayer->getKeyID(), be32toh(0xb)); - PTF_ASSERT_EQUAL(ntpLayer->getDigest(), "ece2d5b07e9fc63279aa2322b76038e53cd0ecc6"); // SHA1 - PTF_ASSERT_EQUAL(ntpLayer->toString(), "NTP Layer v4, Mode: Server"); - - // Since they are double it may or may not equal - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPollIntervalInSecs() - 1024), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPrecisionInSecs() - 0.0000038), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDelayInSecs() - 0.0), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDispersionInSecs() - 0.00383), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReferenceTimestampInSecs() - 1495804991.888536368), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getOriginTimestampInSecs() - 1495805028.556691954), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReceiveTimestampInSecs() - 1495805028.55711825), EPSILON); - PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getTransmitTimestampInSecs() - 1495805028.557834828), EPSILON); - - PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestampAsString(), "2017-05-26T13:23:11.8885Z"); - PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "2017-05-26T13:23:48.5567Z"); - PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestampAsString(), "2017-05-26T13:23:48.5571Z"); - PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestampAsString(), "2017-05-26T13:23:48.5578Z"); -} // NtpParsingV4Tests + PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestampAsString(), "2017-05-26T13:22:09.4829Z"); + + READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/ntpv4Ipv6_withAuth2.dat"); + + ntpPacket = pcpp::Packet(&rawPacket3); + ntpLayer = ntpPacket.getLayerOfType(); + + PTF_ASSERT_NOT_NULL(ntpLayer); + PTF_ASSERT_EQUAL(ntpLayer->getVersion(), 4); + PTF_ASSERT_EQUAL(ntpLayer->getLeapIndicator(), pcpp::NtpLayer::NoWarning); + PTF_ASSERT_EQUAL(ntpLayer->getMode(), pcpp::NtpLayer::Server); + PTF_ASSERT_EQUAL(ntpLayer->getModeString(), "Server"); + PTF_ASSERT_EQUAL(ntpLayer->getStratum(), 1); + PTF_ASSERT_EQUAL(ntpLayer->getPollInterval(), 10); + PTF_ASSERT_EQUAL(ntpLayer->getPrecision(), int8_t(0xee)); + PTF_ASSERT_EQUAL(ntpLayer->getRootDelay(), 0); + PTF_ASSERT_EQUAL(ntpLayer->getRootDispersion(), be32toh(0xfb)); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifier(), static_cast(pcpp::NtpLayer::ClockSource::DCFa)); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceIdentifierString(), "Meinberg DCF77 with amplitude modulation"); + PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestamp(), be64toh(0xdcd2aabfe3771e96)); + PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestamp(), be64toh(0xdcd2aae48e835d2a)); + PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestamp(), be64toh(0xdcd2aae48e9f4d3c)); + PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestamp(), be64toh(0xdcd2aae48ece4367)); + PTF_ASSERT_EQUAL(ntpLayer->getKeyID(), be32toh(0xb)); + PTF_ASSERT_EQUAL(ntpLayer->getDigest(), "ece2d5b07e9fc63279aa2322b76038e53cd0ecc6"); // SHA1 + PTF_ASSERT_EQUAL(ntpLayer->toString(), "NTP Layer v4, Mode: Server"); + + // Since they are double it may or may not equal + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPollIntervalInSecs() - 1024), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getPrecisionInSecs() - 0.0000038), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDelayInSecs() - 0.0), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getRootDispersionInSecs() - 0.00383), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReferenceTimestampInSecs() - 1495804991.888536368), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getOriginTimestampInSecs() - 1495805028.556691954), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getReceiveTimestampInSecs() - 1495805028.55711825), EPSILON); + PTF_ASSERT_LOWER_THAN(fabs(ntpLayer->getTransmitTimestampInSecs() - 1495805028.557834828), EPSILON); + + PTF_ASSERT_EQUAL(ntpLayer->getReferenceTimestampAsString(), "2017-05-26T13:23:11.8885Z"); + PTF_ASSERT_EQUAL(ntpLayer->getOriginTimestampAsString(), "2017-05-26T13:23:48.5567Z"); + PTF_ASSERT_EQUAL(ntpLayer->getReceiveTimestampAsString(), "2017-05-26T13:23:48.5571Z"); + PTF_ASSERT_EQUAL(ntpLayer->getTransmitTimestampAsString(), "2017-05-26T13:23:48.5578Z"); +} // NtpParsingV4Tests PTF_TEST_CASE(NtpCreationTests) { - timeval time; - gettimeofday(&time, nullptr); - - READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ntpv4.dat"); - - pcpp::Packet ntpPacket(&rawPacket1); - - pcpp::EthLayer ethLayer(*ntpPacket.getLayerOfType()); - pcpp::IPv4Layer ipv4Layer(*ntpPacket.getLayerOfType()); - pcpp::UdpLayer udpLayer(*ntpPacket.getLayerOfType()); - - pcpp::NtpLayer ntpLayer; - - // Set the values - ntpLayer.setVersion(4); - ntpLayer.setLeapIndicator(pcpp::NtpLayer::NoWarning); - ntpLayer.setMode(pcpp::NtpLayer::Client); - ntpLayer.setStratum(2); - ntpLayer.setPollInterval(7); - ntpLayer.setPrecision(int8_t(0xeb)); - ntpLayer.setRootDelay(be32toh(0x450)); - ntpLayer.setRootDispersion(be32toh(0x3ab)); - ntpLayer.setReferenceIdentifier(pcpp::IPv4Address("131.188.3.223")); - ntpLayer.setReferenceTimestamp(be64toh(0xd94f51c33165b860)); - ntpLayer.setOriginTimestamp(be64toh(0xd944575530336fd0)); - ntpLayer.setReceiveTimestamp(be64toh(0xd944575531b4e978)); - ntpLayer.setTransmitTimestamp(be64toh(0xd94f51f42d26e2f4)); + timeval time; + gettimeofday(&time, nullptr); + + READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/ntpv4.dat"); + + pcpp::Packet ntpPacket(&rawPacket1); + + pcpp::EthLayer ethLayer(*ntpPacket.getLayerOfType()); + pcpp::IPv4Layer ipv4Layer(*ntpPacket.getLayerOfType()); + pcpp::UdpLayer udpLayer(*ntpPacket.getLayerOfType()); + + pcpp::NtpLayer ntpLayer; + + // Set the values + ntpLayer.setVersion(4); + ntpLayer.setLeapIndicator(pcpp::NtpLayer::NoWarning); + ntpLayer.setMode(pcpp::NtpLayer::Client); + ntpLayer.setStratum(2); + ntpLayer.setPollInterval(7); + ntpLayer.setPrecision(int8_t(0xeb)); + ntpLayer.setRootDelay(be32toh(0x450)); + ntpLayer.setRootDispersion(be32toh(0x3ab)); + ntpLayer.setReferenceIdentifier(pcpp::IPv4Address("131.188.3.223")); + ntpLayer.setReferenceTimestamp(be64toh(0xd94f51c33165b860)); + ntpLayer.setOriginTimestamp(be64toh(0xd944575530336fd0)); + ntpLayer.setReceiveTimestamp(be64toh(0xd944575531b4e978)); + ntpLayer.setTransmitTimestamp(be64toh(0xd94f51f42d26e2f4)); pcpp::Packet craftedPacket; PTF_ASSERT_TRUE(craftedPacket.addLayer(ðLayer)); PTF_ASSERT_TRUE(craftedPacket.addLayer(&ipv4Layer)); PTF_ASSERT_TRUE(craftedPacket.addLayer(&udpLayer)); - craftedPacket.addLayer(&ntpLayer); + craftedPacket.addLayer(&ntpLayer); - PTF_ASSERT_EQUAL(bufferLength1, craftedPacket.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(buffer1, craftedPacket.getRawPacket()->getRawData(), bufferLength1); + PTF_ASSERT_EQUAL(bufferLength1, craftedPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(buffer1, craftedPacket.getRawPacket()->getRawData(), bufferLength1); - READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/ntpv3crafting.dat"); + READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/ntpv3crafting.dat"); - pcpp::Packet ntpPacket2(&rawPacket2); + pcpp::Packet ntpPacket2(&rawPacket2); - pcpp::EthLayer ethLayer2(*ntpPacket2.getLayerOfType()); - pcpp::IPv4Layer ipv4Layer2(*ntpPacket2.getLayerOfType()); - pcpp::UdpLayer udpLayer2(*ntpPacket2.getLayerOfType()); + pcpp::EthLayer ethLayer2(*ntpPacket2.getLayerOfType()); + pcpp::IPv4Layer ipv4Layer2(*ntpPacket2.getLayerOfType()); + pcpp::UdpLayer udpLayer2(*ntpPacket2.getLayerOfType()); - pcpp::NtpLayer ntpLayer2; + pcpp::NtpLayer ntpLayer2; - // Set the values - ntpLayer2.setVersion(3); - ntpLayer2.setLeapIndicator(pcpp::NtpLayer::NoWarning); - ntpLayer2.setMode(pcpp::NtpLayer::Server); - ntpLayer2.setStratum(1); - ntpLayer2.setPollInterval(10); - ntpLayer2.setPrecision(int8_t(0xfa)); - ntpLayer2.setRootDelayInSecs(0.031250); - ntpLayer2.setRootDispersionInSecs(0.125); - ntpLayer2.setReferenceIdentifier(pcpp::NtpLayer::ClockSource::DCFa); - ntpLayer2.setReferenceTimestampInSecs(1121509470.0); - ntpLayer2.setOriginTimestampInSecs(1121509866.0); - ntpLayer2.setReceiveTimestampInSecs(1121509865.0); - ntpLayer2.setTransmitTimestampInSecs(1121509865.0); + // Set the values + ntpLayer2.setVersion(3); + ntpLayer2.setLeapIndicator(pcpp::NtpLayer::NoWarning); + ntpLayer2.setMode(pcpp::NtpLayer::Server); + ntpLayer2.setStratum(1); + ntpLayer2.setPollInterval(10); + ntpLayer2.setPrecision(int8_t(0xfa)); + ntpLayer2.setRootDelayInSecs(0.031250); + ntpLayer2.setRootDispersionInSecs(0.125); + ntpLayer2.setReferenceIdentifier(pcpp::NtpLayer::ClockSource::DCFa); + ntpLayer2.setReferenceTimestampInSecs(1121509470.0); + ntpLayer2.setOriginTimestampInSecs(1121509866.0); + ntpLayer2.setReceiveTimestampInSecs(1121509865.0); + ntpLayer2.setTransmitTimestampInSecs(1121509865.0); pcpp::Packet craftedPacket2; PTF_ASSERT_TRUE(craftedPacket2.addLayer(ðLayer2)); PTF_ASSERT_TRUE(craftedPacket2.addLayer(&ipv4Layer2)); PTF_ASSERT_TRUE(craftedPacket2.addLayer(&udpLayer2)); - craftedPacket2.addLayer(&ntpLayer2); + craftedPacket2.addLayer(&ntpLayer2); - PTF_ASSERT_EQUAL(bufferLength2, craftedPacket2.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(buffer2, craftedPacket2.getRawPacket()->getRawData(), bufferLength2); -} // NtpCraftingTests + PTF_ASSERT_EQUAL(bufferLength2, craftedPacket2.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(buffer2, craftedPacket2.getRawPacket()->getRawData(), bufferLength2); +} // NtpCraftingTests diff --git a/Tests/Packet++Test/Tests/PPPoETests.cpp b/Tests/Packet++Test/Tests/PPPoETests.cpp index 5fdbed4b91..a850c2feb2 100644 --- a/Tests/Packet++Test/Tests/PPPoETests.cpp +++ b/Tests/Packet++Test/Tests/PPPoETests.cpp @@ -10,7 +10,6 @@ #include "DhcpV6Layer.h" #include "SystemUtils.h" - PTF_TEST_CASE(PPPoESessionLayerParsingTest) { timeval time; @@ -37,10 +36,9 @@ PTF_TEST_CASE(PPPoESessionLayerParsingTest) PTF_ASSERT_EQUAL(pppoeSessionLayer->getPPPoEHeader()->payloadLength, htobe16(20)); PTF_ASSERT_EQUAL(pppoeSessionLayer->getPPPNextProtocol(), PCPP_PPP_LCP); - PTF_ASSERT_EQUAL(pppoeSessionLayer->toString(), std::string("PPP-over-Ethernet Session (followed by 'Link Control Protocol')")); -} // PPPoESessionLayerParsingTest - - + PTF_ASSERT_EQUAL(pppoeSessionLayer->toString(), + std::string("PPP-over-Ethernet Session (followed by 'Link Control Protocol')")); +} // PPPoESessionLayerParsingTest PTF_TEST_CASE(PPPoESessionLayerCreationTest) { @@ -68,9 +66,7 @@ PTF_TEST_CASE(PPPoESessionLayerCreationTest) PTF_ASSERT_EQUAL(bufferLength1, pppoesPacket.getRawPacket()->getRawDataLen()); PTF_ASSERT_BUF_COMPARE(pppoesPacket.getRawPacket()->getRawData(), buffer1, bufferLength1); -} // PPPoESessionLayerCreationTest - - +} // PPPoESessionLayerCreationTest PTF_TEST_CASE(PPPoEDiscoveryLayerParsingTest) { @@ -108,14 +104,16 @@ PTF_TEST_CASE(PPPoEDiscoveryLayerParsingTest) PTF_ASSERT_EQUAL(secondTag.getDataSize(), 4); PTF_ASSERT_EQUAL(be32toh(secondTag.getValueAs()), 0x64138518); - pcpp::PPPoEDiscoveryLayer::PPPoETag thirdTag = pppoeDiscoveryLayer->getTag(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_NAME); + pcpp::PPPoEDiscoveryLayer::PPPoETag thirdTag = + pppoeDiscoveryLayer->getTag(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_NAME); PTF_ASSERT_FALSE(thirdTag.isNull()); PTF_ASSERT_TRUE(thirdTag == pppoeDiscoveryLayer->getNextTag(secondTag)); PTF_ASSERT_EQUAL(thirdTag.getType(), pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_NAME, enum); PTF_ASSERT_EQUAL(thirdTag.getDataSize(), 4); PTF_ASSERT_EQUAL(thirdTag.getValueAsString(), "BRAS"); - pcpp::PPPoEDiscoveryLayer::PPPoETag fourthTag = pppoeDiscoveryLayer->getTag(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_COOKIE); + pcpp::PPPoEDiscoveryLayer::PPPoETag fourthTag = + pppoeDiscoveryLayer->getTag(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_COOKIE); PTF_ASSERT_FALSE(fourthTag.isNull()); PTF_ASSERT_TRUE(fourthTag == pppoeDiscoveryLayer->getNextTag(thirdTag)); PTF_ASSERT_EQUAL(fourthTag.getType(), pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_COOKIE, enum); @@ -127,9 +125,7 @@ PTF_TEST_CASE(PPPoEDiscoveryLayerParsingTest) PTF_ASSERT_EQUAL(pppoeDiscoveryLayer->getTagCount(), 4); PTF_ASSERT_EQUAL(pppoeDiscoveryLayer->toString(), std::string("PPP-over-Ethernet Discovery (PADS)")); -} // PPPoEDiscoveryLayerParsingTest - - +} // PPPoEDiscoveryLayerParsingTest PTF_TEST_CASE(PPPoEDiscoveryLayerCreateTest) { @@ -143,12 +139,15 @@ PTF_TEST_CASE(PPPoEDiscoveryLayerCreateTest) pcpp::EthLayer ethLayer(*samplePacket.getLayerOfType()); pcpp::PPPoEDiscoveryLayer pppoedLayer(1, 1, pcpp::PPPoELayer::PPPOE_CODE_PADI, 0); - pcpp::PPPoEDiscoveryLayer::PPPoETag svcNameTag = pppoedLayer.addTag(pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_SVC_NAME)); + pcpp::PPPoEDiscoveryLayer::PPPoETag svcNameTag = + pppoedLayer.addTag(pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_SVC_NAME)); PTF_ASSERT_EQUAL(pppoedLayer.getTagCount(), 1); PTF_ASSERT_EQUAL(pppoedLayer.getPPPoEHeader()->payloadLength, htobe16(4)); uint32_t hostUniqData = 0x64138518; - pppoedLayer.addTagAfter(pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_HOST_UNIQ, hostUniqData), svcNameTag.getType()); + pppoedLayer.addTagAfter( + pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_HOST_UNIQ, hostUniqData), + svcNameTag.getType()); PTF_ASSERT_EQUAL(pppoedLayer.getTagCount(), 2); PTF_ASSERT_EQUAL(pppoedLayer.getPPPoEHeader()->payloadLength, htobe16(12)); @@ -161,7 +160,6 @@ PTF_TEST_CASE(PPPoEDiscoveryLayerCreateTest) PTF_ASSERT_EQUAL(pppoedPacket.getRawPacket()->getRawDataLen(), bufferLength1); PTF_ASSERT_BUF_COMPARE(pppoedPacket.getRawPacket()->getRawData(), buffer1, bufferLength1); - READ_FILE_INTO_BUFFER(2, "PacketExamples/PPPoEDiscovery2.dat"); pcpp::EthLayer* ethLayerPtr = pppoedPacket.getLayerOfType(); @@ -172,20 +170,25 @@ PTF_TEST_CASE(PPPoEDiscoveryLayerCreateTest) pppoedLayer.getPPPoEHeader()->code = pcpp::PPPoELayer::PPPOE_CODE_PADS; pppoedLayer.getPPPoEHeader()->sessionId = htobe16(0x11); - - uint8_t acCookieValue[16] = {0x3d, 0x0f, 0x05, 0x87, 0x06, 0x24, 0x84, 0xf2, 0xdf, 0x32, 0xb9, 0xdd, 0xfd, 0x77, 0xbd, 0x5b}; - pcpp::PPPoEDiscoveryLayer::PPPoETag acCookieTag = pppoedLayer.addTag(pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_COOKIE, acCookieValue, 16)); + uint8_t acCookieValue[16] = { 0x3d, 0x0f, 0x05, 0x87, 0x06, 0x24, 0x84, 0xf2, + 0xdf, 0x32, 0xb9, 0xdd, 0xfd, 0x77, 0xbd, 0x5b }; + pcpp::PPPoEDiscoveryLayer::PPPoETag acCookieTag = pppoedLayer.addTag( + pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_COOKIE, acCookieValue, 16)); PTF_ASSERT_EQUAL(pppoedLayer.getTagCount(), 3); PTF_ASSERT_EQUAL(pppoedLayer.getPPPoEHeader()->payloadLength, htobe16(32)); - pppoedLayer.addTagAfter(pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_HURL, hostUniqData), acCookieTag.getType()); + pppoedLayer.addTagAfter( + pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_HURL, hostUniqData), + acCookieTag.getType()); PTF_ASSERT_EQUAL(pppoedLayer.getTagCount(), 4); PTF_ASSERT_EQUAL(pppoedLayer.getPPPoEHeader()->payloadLength, htobe16(40)); - - pcpp::PPPoEDiscoveryLayer::PPPoETag hostUniqTag = pppoedLayer.getTag(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_HOST_UNIQ); + pcpp::PPPoEDiscoveryLayer::PPPoETag hostUniqTag = + pppoedLayer.getTag(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_HOST_UNIQ); PTF_ASSERT_FALSE(hostUniqTag.isNull()); - pppoedLayer.addTagAfter(pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_NAME, 0x42524153), hostUniqTag.getType()); + pppoedLayer.addTagAfter( + pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_NAME, 0x42524153), + hostUniqTag.getType()); PTF_ASSERT_EQUAL(pppoedLayer.getTagCount(), 5); PTF_ASSERT_EQUAL(pppoedLayer.getPPPoEHeader()->payloadLength, htobe16(48)); @@ -204,11 +207,11 @@ PTF_TEST_CASE(PPPoEDiscoveryLayerCreateTest) PTF_ASSERT_EQUAL(pppoedPacket.getRawPacket()->getRawDataLen(), bufferLength2); PTF_ASSERT_BUF_COMPARE(pppoedPacket.getRawPacket()->getRawData(), buffer2, bufferLength2); - delete [] buffer2; + delete[] buffer2; PTF_ASSERT_TRUE(pppoedLayer.removeAllTags()); pppoedPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(pppoedLayer.getHeaderLen(), sizeof(pcpp::pppoe_header)); PTF_ASSERT_EQUAL(pppoedLayer.getPPPoEHeader()->payloadLength, 0); -} // PPPoEDiscoveryLayerCreateTest +} // PPPoEDiscoveryLayerCreateTest diff --git a/Tests/Packet++Test/Tests/PacketTests.cpp b/Tests/Packet++Test/Tests/PacketTests.cpp index cea40f0502..594f06492e 100644 --- a/Tests/Packet++Test/Tests/PacketTests.cpp +++ b/Tests/Packet++Test/Tests/PacketTests.cpp @@ -58,7 +58,6 @@ PTF_TEST_CASE(InsertDataToPacket) PTF_ASSERT_EQUAL(ip4Layer.getSrcIPAddress(), ipSrc); PTF_ASSERT_EQUAL(payloadLayer.getPayload()[3], 0x04); - // Adding another Eth layer at the beginning of the packet // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -76,26 +75,23 @@ PTF_TEST_CASE(InsertDataToPacket) PTF_ASSERT_EQUAL(ip4Layer.getSrcIPAddress(), ipSrc); PTF_ASSERT_EQUAL(payloadLayer.getPayload()[3], 0x04); - // Adding a TCP layer at the end of the packet // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ auto tcpLayer = new pcpp::TcpLayer((uint16_t)12345, (uint16_t)80); PTF_ASSERT_TRUE(ip4Packet.insertLayer(&payloadLayer, tcpLayer, true)); - // Create a new packet and use insertLayer for the first layer in packet // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ pcpp::EthLayer ethLayer3(srcMac2, dstMac2, PCPP_ETHERTYPE_IP); - pcpp::Packet testPacket(1); + pcpp::Packet testPacket(1); PTF_ASSERT_TRUE(testPacket.insertLayer(nullptr, ðLayer3)); PTF_ASSERT_EQUAL(testPacket.getFirstLayer(), ðLayer3, ptr); PTF_ASSERT_NULL(testPacket.getFirstLayer()->getNextLayer()); PTF_ASSERT_EQUAL(ethLayer3.getDestMac(), dstMac2); -} // InsertDataToPacket - +} // InsertDataToPacket PTF_TEST_CASE(CreatePacketFromBuffer) { @@ -139,13 +135,13 @@ PTF_TEST_CASE(CreatePacketFromBuffer) // Delete the packet - the buffer should not be freed delete newPacket; - std::string expectedHexString = "bbbbbbbbbbbbaaaaaaaaaaaa08004500001e00000000000690b101010101141414140102030405060708090a0000"; + std::string expectedHexString = + "bbbbbbbbbbbbaaaaaaaaaaaa08004500001e00000000000690b101010101141414140102030405060708090a0000"; PTF_ASSERT_EQUAL(pcpp::byteArrayToHexString(buffer, bufferSize), expectedHexString); - delete [] buffer; - -} // CreatePacketFromBuffer + delete[] buffer; +} // CreatePacketFromBuffer PTF_TEST_CASE(InsertVlanToPacket) { @@ -164,8 +160,7 @@ PTF_TEST_CASE(InsertVlanToPacket) PTF_ASSERT_EQUAL(tcpPacket.getFirstLayer()->getNextLayer(), &vlanLayer, ptr); PTF_ASSERT_NOT_NULL(vlanLayer.getNextLayer()); PTF_ASSERT_EQUAL(vlanLayer.getNextLayer()->getProtocol(), pcpp::IPv4, enum); -} // InsertVlanToPacket - +} // InsertVlanToPacket PTF_TEST_CASE(RemoveLayerTest) { @@ -179,7 +174,6 @@ PTF_TEST_CASE(RemoveLayerTest) pcpp::Packet tcpPacket(&rawPacket1); - // a. Remove layer from the middle // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -190,7 +184,6 @@ PTF_TEST_CASE(RemoveLayerTest) PTF_ASSERT_EQUAL(tcpPacket.getFirstLayer()->getNextLayer()->getProtocol(), pcpp::TCP, enum); PTF_ASSERT_EQUAL(tcpPacket.getRawPacket()->getRawDataLen(), 271); - // b. Remove first layer // ~~~~~~~~~~~~~~~~~~~~~ @@ -201,7 +194,6 @@ PTF_TEST_CASE(RemoveLayerTest) PTF_ASSERT_NULL(tcpPacket.getFirstLayer()->getNextLayer()->getNextLayer()); PTF_ASSERT_EQUAL(tcpPacket.getRawPacket()->getRawDataLen(), 257); - // c. Remove last layer // ~~~~~~~~~~~~~~~~~~~~ PTF_ASSERT_TRUE(tcpPacket.removeLastLayer()); @@ -211,7 +203,6 @@ PTF_TEST_CASE(RemoveLayerTest) PTF_ASSERT_EQUAL(tcpPacket.getFirstLayer()->getProtocol(), pcpp::TCP, enum); PTF_ASSERT_EQUAL(tcpPacket.getRawPacket()->getRawDataLen(), 20); - // d. Remove a second layer of the same type // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -229,7 +220,6 @@ PTF_TEST_CASE(RemoveLayerTest) PTF_ASSERT_TRUE(vxlanPacket.isPacketOfType(pcpp::VXLAN)); PTF_ASSERT_EQUAL(vxlanPacket.getRawPacket()->getRawDataLen(), 50); - // e. Remove a layer that doesn't exist // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -238,7 +228,6 @@ PTF_TEST_CASE(RemoveLayerTest) PTF_ASSERT_FALSE(vxlanPacket.removeLayer(pcpp::Ethernet, 1)); pcpp::Logger::getInstance().enableLogs(); - // create packet and remove layers // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -259,7 +248,6 @@ PTF_TEST_CASE(RemoveLayerTest) pcpp::PayloadLayer payloadLayer(payload, 10); PTF_ASSERT_TRUE(testPacket.addLayer(&payloadLayer)); - // a. remove first layer // ~~~~~~~~~~~~~~~~~~~~~ @@ -270,7 +258,6 @@ PTF_TEST_CASE(RemoveLayerTest) PTF_ASSERT_TRUE(testPacket.isPacketOfType(pcpp::IPv4)); PTF_ASSERT_EQUAL(testPacket.getRawPacket()->getRawDataLen(), 30); - // b. remove last layer // ~~~~~~~~~~~~~~~~~~~~ @@ -281,7 +268,6 @@ PTF_TEST_CASE(RemoveLayerTest) PTF_ASSERT_FALSE(testPacket.isPacketOfType(pcpp::Ethernet)); PTF_ASSERT_EQUAL(testPacket.getRawPacket()->getRawDataLen(), 20); - // c. insert a layer // ~~~~~~~~~~~~~~~~~ @@ -292,7 +278,6 @@ PTF_TEST_CASE(RemoveLayerTest) PTF_ASSERT_TRUE(testPacket.isPacketOfType(pcpp::VLAN)); PTF_ASSERT_EQUAL(testPacket.getRawPacket()->getRawDataLen(), 24); - // d. remove the remaining layers (packet remains empty!) // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -305,7 +290,6 @@ PTF_TEST_CASE(RemoveLayerTest) PTF_ASSERT_FALSE(testPacket.isPacketOfType(pcpp::VLAN)); PTF_ASSERT_EQUAL(testPacket.getRawPacket()->getRawDataLen(), 0); - // Detach layer and add it to another packet // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -356,10 +340,9 @@ PTF_TEST_CASE(RemoveLayerTest) PTF_ASSERT_EQUAL(packetWithoutTunnel.getRawPacket()->getRawDataLen(), bufferLength4); PTF_ASSERT_BUF_COMPARE(packetWithoutTunnel.getRawPacket()->getRawData(), buffer4, bufferLength4); - delete [] buffer4; - -} // RemoveLayerTest + delete[] buffer4; +} // RemoveLayerTest PTF_TEST_CASE(CopyLayerAndPacketTest) { @@ -370,7 +353,7 @@ PTF_TEST_CASE(CopyLayerAndPacketTest) pcpp::Packet sampleHttpPacket(&rawPacket1); - //RawPacket copy c'tor / assignment operator test + // RawPacket copy c'tor / assignment operator test //----------------------------------------------- pcpp::RawPacket copyRawPacket; copyRawPacket = rawPacket1; @@ -378,33 +361,41 @@ PTF_TEST_CASE(CopyLayerAndPacketTest) PTF_ASSERT_TRUE(copyRawPacket.getRawData() != rawPacket1.getRawData()); PTF_ASSERT_BUF_COMPARE(copyRawPacket.getRawData(), rawPacket1.getRawData(), rawPacket1.getRawDataLen()); - //EthLayer copy c'tor test + // EthLayer copy c'tor test //------------------------ pcpp::EthLayer ethLayer = *sampleHttpPacket.getLayerOfType(); PTF_ASSERT_TRUE(sampleHttpPacket.getLayerOfType()->getLayerPayload() != ethLayer.getLayerPayload()); - PTF_ASSERT_BUF_COMPARE(ethLayer.getLayerPayload(), sampleHttpPacket.getLayerOfType()->getLayerPayload(), sampleHttpPacket.getLayerOfType()->getLayerPayloadSize()); - + PTF_ASSERT_BUF_COMPARE(ethLayer.getLayerPayload(), + sampleHttpPacket.getLayerOfType()->getLayerPayload(), + sampleHttpPacket.getLayerOfType()->getLayerPayloadSize()); - //TcpLayer copy c'tor test + // TcpLayer copy c'tor test //------------------------ READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/TcpPacketWithOptions2.dat"); pcpp::Packet sampleTcpPacketWithOptions(&rawPacket2); pcpp::TcpLayer tcpLayer = *sampleTcpPacketWithOptions.getLayerOfType(); PTF_ASSERT_TRUE(sampleTcpPacketWithOptions.getLayerOfType()->getData() != tcpLayer.getData()); - PTF_ASSERT_BUF_COMPARE(sampleTcpPacketWithOptions.getLayerOfType()->getData(), tcpLayer.getData(), sampleTcpPacketWithOptions.getLayerOfType()->getDataLen()); - PTF_ASSERT_EQUAL(tcpLayer.getTcpOptionCount(), sampleTcpPacketWithOptions.getLayerOfType()->getTcpOptionCount()); - PTF_ASSERT_TRUE(sampleTcpPacketWithOptions.getLayerOfType()->getTcpOption(pcpp::TcpOptionEnumType::Timestamp).getRecordBasePtr() != tcpLayer.getTcpOption(pcpp::TcpOptionEnumType::Timestamp).getRecordBasePtr()); - PTF_ASSERT_TRUE(sampleTcpPacketWithOptions.getLayerOfType()->getTcpOption(pcpp::TcpOptionEnumType::Timestamp) == tcpLayer.getTcpOption(pcpp::TcpOptionEnumType::Timestamp)); - - - //HttpLayer copy c'tor test + PTF_ASSERT_BUF_COMPARE(sampleTcpPacketWithOptions.getLayerOfType()->getData(), tcpLayer.getData(), + sampleTcpPacketWithOptions.getLayerOfType()->getDataLen()); + PTF_ASSERT_EQUAL(tcpLayer.getTcpOptionCount(), + sampleTcpPacketWithOptions.getLayerOfType()->getTcpOptionCount()); + PTF_ASSERT_TRUE(sampleTcpPacketWithOptions.getLayerOfType() + ->getTcpOption(pcpp::TcpOptionEnumType::Timestamp) + .getRecordBasePtr() != + tcpLayer.getTcpOption(pcpp::TcpOptionEnumType::Timestamp).getRecordBasePtr()); + PTF_ASSERT_TRUE( + sampleTcpPacketWithOptions.getLayerOfType()->getTcpOption(pcpp::TcpOptionEnumType::Timestamp) == + tcpLayer.getTcpOption(pcpp::TcpOptionEnumType::Timestamp)); + + // HttpLayer copy c'tor test //-------------------------- pcpp::HttpResponseLayer* sampleHttpLayer = sampleHttpPacket.getLayerOfType(); pcpp::HttpResponseLayer httpResLayer = *sampleHttpPacket.getLayerOfType(); PTF_ASSERT_TRUE(sampleHttpLayer->getFirstLine() != httpResLayer.getFirstLine()); - PTF_ASSERT_EQUAL(sampleHttpLayer->getFirstLine()->getStatusCode(), httpResLayer.getFirstLine()->getStatusCode(), enum); + PTF_ASSERT_EQUAL(sampleHttpLayer->getFirstLine()->getStatusCode(), httpResLayer.getFirstLine()->getStatusCode(), + enum); PTF_ASSERT_EQUAL(sampleHttpLayer->getFirstLine()->getSize(), httpResLayer.getFirstLine()->getSize()); PTF_ASSERT_EQUAL(sampleHttpLayer->getFirstLine()->getVersion(), httpResLayer.getFirstLine()->getVersion(), enum); @@ -424,16 +415,17 @@ PTF_TEST_CASE(CopyLayerAndPacketTest) PTF_ASSERT_NULL(curFieldInSample); PTF_ASSERT_NULL(curFieldInCopy); - - //Packet copy c'tor test - Ethernet + // Packet copy c'tor test - Ethernet //--------------------------------- pcpp::Packet samplePacketCopy(sampleHttpPacket); PTF_ASSERT_TRUE(samplePacketCopy.getFirstLayer() != sampleHttpPacket.getFirstLayer()); PTF_ASSERT_TRUE(samplePacketCopy.getLastLayer() != sampleHttpPacket.getLastLayer()); PTF_ASSERT_TRUE(samplePacketCopy.getRawPacket() != sampleHttpPacket.getRawPacket()); - PTF_ASSERT_EQUAL(samplePacketCopy.getRawPacket()->getRawDataLen(), sampleHttpPacket.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(samplePacketCopy.getRawPacket()->getRawData(), sampleHttpPacket.getRawPacket()->getRawData(), sampleHttpPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_EQUAL(samplePacketCopy.getRawPacket()->getRawDataLen(), + sampleHttpPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(samplePacketCopy.getRawPacket()->getRawData(), sampleHttpPacket.getRawPacket()->getRawData(), + sampleHttpPacket.getRawPacket()->getRawDataLen()); PTF_ASSERT_TRUE(samplePacketCopy.isPacketOfType(pcpp::Ethernet)); PTF_ASSERT_TRUE(samplePacketCopy.isPacketOfType(pcpp::IPv4)); PTF_ASSERT_TRUE(samplePacketCopy.isPacketOfType(pcpp::TCP)); @@ -446,25 +438,26 @@ PTF_TEST_CASE(CopyLayerAndPacketTest) PTF_ASSERT_EQUAL(curSamplePacketLayer->getHeaderLen(), curPacketCopyLayer->getHeaderLen()); PTF_ASSERT_EQUAL(curSamplePacketLayer->getLayerPayloadSize(), curPacketCopyLayer->getLayerPayloadSize()); PTF_ASSERT_EQUAL(curSamplePacketLayer->getDataLen(), curPacketCopyLayer->getDataLen()); - PTF_ASSERT_BUF_COMPARE(curSamplePacketLayer->getData(), curPacketCopyLayer->getData(), curSamplePacketLayer->getDataLen()); + PTF_ASSERT_BUF_COMPARE(curSamplePacketLayer->getData(), curPacketCopyLayer->getData(), + curSamplePacketLayer->getDataLen()); curSamplePacketLayer = curSamplePacketLayer->getNextLayer(); curPacketCopyLayer = curPacketCopyLayer->getNextLayer(); } auto samplePacketCopyHttpResponseLayer = samplePacketCopy.getLayerOfType(); auto contentTypeField = samplePacketCopyHttpResponseLayer->getFieldByName(PCPP_HTTP_CONTENT_TYPE_FIELD); - PTF_ASSERT_NOT_NULL(samplePacketCopyHttpResponseLayer->insertField(contentTypeField, "X-Forwarded-For", "10.20.30.40")); + PTF_ASSERT_NOT_NULL( + samplePacketCopyHttpResponseLayer->insertField(contentTypeField, "X-Forwarded-For", "10.20.30.40")); samplePacketCopy = sampleHttpPacket; samplePacketCopyHttpResponseLayer = samplePacketCopy.getLayerOfType(); contentTypeField = samplePacketCopyHttpResponseLayer->getFieldByName(PCPP_HTTP_CONTENT_TYPE_FIELD); - PTF_ASSERT_NOT_NULL(samplePacketCopyHttpResponseLayer->insertField(contentTypeField, "X-Forwarded-For", "10.20.30.40")); - + PTF_ASSERT_NOT_NULL( + samplePacketCopyHttpResponseLayer->insertField(contentTypeField, "X-Forwarded-For", "10.20.30.40")); PTF_ASSERT_NULL(curSamplePacketLayer); PTF_ASSERT_NULL(curPacketCopyLayer); - - //Packet copy c'tor test - Null/Loopback + // Packet copy c'tor test - Null/Loopback //-------------------------------------- READ_FILE_AND_CREATE_PACKET_LINKTYPE(3, "PacketExamples/NullLoopback1.dat", pcpp::LINKTYPE_NULL); @@ -476,8 +469,11 @@ PTF_TEST_CASE(CopyLayerAndPacketTest) PTF_ASSERT_TRUE(nullLoopbackPacketCopy.getFirstLayer() != nullLoopbackPacket.getFirstLayer()); PTF_ASSERT_TRUE(nullLoopbackPacketCopy.getLastLayer() != nullLoopbackPacket.getLastLayer()); PTF_ASSERT_TRUE(nullLoopbackPacketCopy.getRawPacket() != nullLoopbackPacket.getRawPacket()); - PTF_ASSERT_EQUAL(nullLoopbackPacketCopy.getRawPacket()->getRawDataLen(), nullLoopbackPacket.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(nullLoopbackPacketCopy.getRawPacket()->getRawData(), nullLoopbackPacket.getRawPacket()->getRawData(), nullLoopbackPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_EQUAL(nullLoopbackPacketCopy.getRawPacket()->getRawDataLen(), + nullLoopbackPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(nullLoopbackPacketCopy.getRawPacket()->getRawData(), + nullLoopbackPacket.getRawPacket()->getRawData(), + nullLoopbackPacket.getRawPacket()->getRawDataLen()); PTF_ASSERT_EQUAL(nullLoopbackPacketCopy.getRawPacket()->getLinkLayerType(), pcpp::LINKTYPE_NULL, enum); PTF_ASSERT_EQUAL(nullLoopbackPacketCopy.getFirstLayer()->getProtocol(), pcpp::NULL_LOOPBACK, enum); @@ -493,8 +489,7 @@ PTF_TEST_CASE(CopyLayerAndPacketTest) curPacketCopyLayer = curPacketCopyLayer->getNextLayer(); } - - //Packet copy c'tor test - SLL + // Packet copy c'tor test - SLL //---------------------------- READ_FILE_AND_CREATE_PACKET_LINKTYPE(4, "PacketExamples/SllPacket2.dat", pcpp::LINKTYPE_LINUX_SLL); @@ -507,7 +502,8 @@ PTF_TEST_CASE(CopyLayerAndPacketTest) PTF_ASSERT_TRUE(sllPacketCopy.getLastLayer() != sllPacket.getLastLayer()); PTF_ASSERT_TRUE(sllPacketCopy.getRawPacket() != sllPacket.getRawPacket()); PTF_ASSERT_EQUAL(sllPacketCopy.getRawPacket()->getRawDataLen(), sllPacket.getRawPacket()->getRawDataLen()); - PTF_ASSERT_BUF_COMPARE(sllPacketCopy.getRawPacket()->getRawData(), sllPacket.getRawPacket()->getRawData(), sllPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(sllPacketCopy.getRawPacket()->getRawData(), sllPacket.getRawPacket()->getRawData(), + sllPacket.getRawPacket()->getRawDataLen()); PTF_ASSERT_EQUAL(sllPacketCopy.getRawPacket()->getLinkLayerType(), pcpp::LINKTYPE_LINUX_SLL, enum); PTF_ASSERT_EQUAL(sllPacketCopy.getFirstLayer()->getProtocol(), pcpp::SLL, enum); @@ -523,8 +519,7 @@ PTF_TEST_CASE(CopyLayerAndPacketTest) curPacketCopyLayer = curPacketCopyLayer->getNextLayer(); } - - //DnsLayer copy c'tor and operator= test + // DnsLayer copy c'tor and operator= test //-------------------------------------- READ_FILE_AND_CREATE_PACKET(5, "PacketExamples/Dns2.dat"); @@ -539,9 +534,11 @@ PTF_TEST_CASE(CopyLayerAndPacketTest) PTF_ASSERT_EQUAL(copyDnsLayer.getFirstQuery()->getDnsType(), origDnsLayer->getFirstQuery()->getDnsType(), enum); PTF_ASSERT_EQUAL(copyDnsLayer.getAuthorityCount(), origDnsLayer->getAuthorityCount()); - PTF_ASSERT_EQUAL(copyDnsLayer.getAuthority("Yaels-iPhone.local", true)->getData()->toString(), origDnsLayer->getAuthority("Yaels-iPhone.local", true)->getData()->toString()); + PTF_ASSERT_EQUAL(copyDnsLayer.getAuthority("Yaels-iPhone.local", true)->getData()->toString(), + origDnsLayer->getAuthority("Yaels-iPhone.local", true)->getData()->toString()); - PTF_ASSERT_EQUAL(copyDnsLayer.getAdditionalRecord("", true)->getData()->toString(), origDnsLayer->getAdditionalRecord("", true)->getData()->toString()); + PTF_ASSERT_EQUAL(copyDnsLayer.getAdditionalRecord("", true)->getData()->toString(), + origDnsLayer->getAdditionalRecord("", true)->getData()->toString()); copyDnsLayer.addQuery("bla", pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_ANY); pcpp::IPv4DnsResourceData ipv4DnsData(std::string("1.1.1.1")); @@ -554,14 +551,15 @@ PTF_TEST_CASE(CopyLayerAndPacketTest) PTF_ASSERT_EQUAL(copyDnsLayer.getFirstQuery()->getDnsType(), origDnsLayer->getFirstQuery()->getDnsType(), enum); PTF_ASSERT_EQUAL(copyDnsLayer.getAuthorityCount(), origDnsLayer->getAuthorityCount()); - PTF_ASSERT_EQUAL(copyDnsLayer.getAuthority(".local", false)->getData()->toString(), origDnsLayer->getAuthority("iPhone.local", false)->getData()->toString()); + PTF_ASSERT_EQUAL(copyDnsLayer.getAuthority(".local", false)->getData()->toString(), + origDnsLayer->getAuthority("iPhone.local", false)->getData()->toString()); PTF_ASSERT_EQUAL(copyDnsLayer.getAnswerCount(), origDnsLayer->getAnswerCount()); - PTF_ASSERT_EQUAL(copyDnsLayer.getAdditionalRecord("", true)->getData()->toString(), origDnsLayer->getAdditionalRecord("", true)->getData()->toString()); - -} // CopyLayerAndPacketTest + PTF_ASSERT_EQUAL(copyDnsLayer.getAdditionalRecord("", true)->getData()->toString(), + origDnsLayer->getAdditionalRecord("", true)->getData()->toString()); +} // CopyLayerAndPacketTest PTF_TEST_CASE(PacketLayerLookupTest) { @@ -613,8 +611,7 @@ PTF_TEST_CASE(PacketLayerLookupTest) // try to get nonexistent layer PTF_ASSERT_NULL(vxlanPacket.getLayerOfType(true)); } -} // PacketLayerLookupTest - +} // PacketLayerLookupTest PTF_TEST_CASE(RawPacketTimeStampSetterTest) { @@ -627,8 +624,8 @@ PTF_TEST_CASE(RawPacketTimeStampSetterTest) timespec nsec_test_time; timespec expected_ts; - //test usec-precision setter - usec_test_time.tv_sec = 1583840642; //10.03.2020 15:44 + // test usec-precision setter + usec_test_time.tv_sec = 1583840642; // 10.03.2020 15:44 usec_test_time.tv_usec = 111222; expected_ts.tv_sec = usec_test_time.tv_sec; expected_ts.tv_nsec = usec_test_time.tv_usec * 1000; @@ -637,16 +634,15 @@ PTF_TEST_CASE(RawPacketTimeStampSetterTest) PTF_ASSERT_EQUAL(rawPacket1.getPacketTimeStamp().tv_sec, expected_ts.tv_sec); PTF_ASSERT_EQUAL(rawPacket1.getPacketTimeStamp().tv_nsec, expected_ts.tv_nsec); - //test nsec-precision setter - nsec_test_time.tv_sec = 1583842105; //10.03.2020 16:08 + // test nsec-precision setter + nsec_test_time.tv_sec = 1583842105; // 10.03.2020 16:08 nsec_test_time.tv_nsec = 111222987; expected_ts = nsec_test_time; PTF_ASSERT_TRUE(rawPacket1.setPacketTimeStamp(nsec_test_time)); PTF_ASSERT_EQUAL(rawPacket1.getPacketTimeStamp().tv_sec, expected_ts.tv_sec); PTF_ASSERT_EQUAL(rawPacket1.getPacketTimeStamp().tv_nsec, expected_ts.tv_nsec); -} // RawPacketTimeStampSetterTest - +} // RawPacketTimeStampSetterTest PTF_TEST_CASE(ParsePartialPacketTest) { @@ -739,8 +735,7 @@ PTF_TEST_CASE(ParsePartialPacketTest) PTF_ASSERT_EQUAL(curLayer->getProtocol(), pcpp::GREv0, enum); curLayer = curLayer->getNextLayer(); PTF_ASSERT_NULL(curLayer); -} // ParsePartialPacketTest - +} // ParsePartialPacketTest PTF_TEST_CASE(PacketTrailerTest) { @@ -769,10 +764,14 @@ PTF_TEST_CASE(PacketTrailerTest) PTF_ASSERT_EQUAL(trailerIPv6Packet.getLayerOfType()->getTrailerLen(), 4); PTF_ASSERT_EQUAL(trailerPPPoEDPacket.getLayerOfType()->getTrailerLen(), 28); - PTF_ASSERT_EQUAL(trailerArpPacket.getLayerOfType()->getTrailerDataAsHexString(), "742066726f6d2062726964676500203d3d20"); - PTF_ASSERT_EQUAL(trailerIPv4Packet.getLayerOfType()->getTrailerDataAsHexString(), "0101080a0000"); - PTF_ASSERT_EQUAL(trailerIPv6Packet.getLayerOfType()->getTrailerDataAsHexString(), "cdfcf105"); - PTF_ASSERT_EQUAL(trailerPPPoEDPacket.getLayerOfType()->getTrailerDataAsHexString(), "00000000000000000000000000000000000000000000000000000000"); + PTF_ASSERT_EQUAL(trailerArpPacket.getLayerOfType()->getTrailerDataAsHexString(), + "742066726f6d2062726964676500203d3d20"); + PTF_ASSERT_EQUAL(trailerIPv4Packet.getLayerOfType()->getTrailerDataAsHexString(), + "0101080a0000"); + PTF_ASSERT_EQUAL(trailerIPv6Packet.getLayerOfType()->getTrailerDataAsHexString(), + "cdfcf105"); + PTF_ASSERT_EQUAL(trailerPPPoEDPacket.getLayerOfType()->getTrailerDataAsHexString(), + "00000000000000000000000000000000000000000000000000000000"); PTF_ASSERT_EQUAL(trailerArpPacket.getLayerOfType()->getTrailerData()[3], 0x72, hex); PTF_ASSERT_EQUAL(trailerIPv4Packet.getLayerOfType()->getTrailerData()[2], 0x8, hex); @@ -791,7 +790,8 @@ PTF_TEST_CASE(PacketTrailerTest) PTF_ASSERT_NOT_NULL(ethLayer); PTF_ASSERT_NOT_NULL(ip6Layer); PTF_ASSERT_GREATER_THAN(ethLayer->getDataLen() - ethLayer->getHeaderLen(), ip6Layer->getDataLen()); - PTF_ASSERT_EQUAL(ip6Layer->getDataLen(), be16toh(ip6Layer->getIPv6Header()->payloadLength) + ip6Layer->getHeaderLen()); + PTF_ASSERT_EQUAL(ip6Layer->getDataLen(), + be16toh(ip6Layer->getIPv6Header()->payloadLength) + ip6Layer->getHeaderLen()); // add layer before trailer auto newVlanLayer = new pcpp::VlanLayer(123, true, 1, PCPP_ETHERTYPE_IPV6); @@ -860,7 +860,8 @@ PTF_TEST_CASE(PacketTrailerTest) PTF_ASSERT_EQUAL(trailerIPv4Packet.getLayerOfType()->getDataLen(), 6); // rebuild packet starting from trailer - auto newEthLayer = new pcpp::EthLayer(pcpp::MacAddress("30:46:9a:23:fb:fa"), pcpp::MacAddress("6c:f0:49:b2:de:6e"), PCPP_ETHERTYPE_IP); + auto newEthLayer = new pcpp::EthLayer(pcpp::MacAddress("30:46:9a:23:fb:fa"), pcpp::MacAddress("6c:f0:49:b2:de:6e"), + PCPP_ETHERTYPE_IP); PTF_ASSERT_TRUE(trailerIPv4Packet.insertLayer(nullptr, newEthLayer, true)); auto newIp4Layer = new pcpp::IPv4Layer(pcpp::IPv4Address("173.194.78.104"), pcpp::IPv4Address("10.0.0.1")); newIp4Layer->getIPv4Header()->ipId = htobe16(40382); @@ -893,7 +894,10 @@ PTF_TEST_CASE(PacketTrailerTest) // extend layer just before trailer pcpp::PPPoEDiscoveryLayer* pppoeDiscovery = trailerPPPoEDPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(pppoeDiscovery); - PTF_ASSERT_FALSE(pppoeDiscovery->addTag(pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder(pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_NAME, 0x42524153)).isNull()); + PTF_ASSERT_FALSE(pppoeDiscovery + ->addTag(pcpp::PPPoEDiscoveryLayer::PPPoETagBuilder( + pcpp::PPPoEDiscoveryLayer::PPPOE_TAG_AC_NAME, 0x42524153)) + .isNull()); trailerPPPoEDPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(trailerPPPoEDPacket.getLayerOfType()->getDataLen(), 68); PTF_ASSERT_EQUAL(trailerPPPoEDPacket.getLayerOfType()->getDataLen(), 26); @@ -917,20 +921,19 @@ PTF_TEST_CASE(PacketTrailerTest) PTF_ASSERT_EQUAL(trailerPPPoEDPacket.getLayerOfType()->getDataLen(), 48); PTF_ASSERT_EQUAL(trailerPPPoEDPacket.getLayerOfType()->getDataLen(), 6); PTF_ASSERT_EQUAL(trailerPPPoEDPacket.getLayerOfType()->getDataLen(), 28); -} // PacketTrailerTest - +} // PacketTrailerTest PTF_TEST_CASE(ResizeLayerTest) { uint8_t payload[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xa }; pcpp::PayloadLayer payloadLayer(payload, 10); - // Creating a packet - pcpp::Packet packet(1500); - PTF_ASSERT_TRUE(packet.addLayer(&payloadLayer)); + // Creating a packet + pcpp::Packet packet(1500); + PTF_ASSERT_TRUE(packet.addLayer(&payloadLayer)); // Starting Resize testing - PTF_ASSERT_EQUAL(packet.getRawPacket()->getRawDataLen(), 10); // Size of packet before resizing is not correct + PTF_ASSERT_EQUAL(packet.getRawPacket()->getRawDataLen(), 10); // Size of packet before resizing is not correct // // test shortening of packet and layer @@ -940,11 +943,13 @@ PTF_TEST_CASE(ResizeLayerTest) payloadLayer.setPayload(payload2, payload2_size); // check that resizing worked in terms of data length - PTF_ASSERT_EQUAL(packet.getRawPacket()->getRawDataLen(), (int)payload2_size); // Size of packet after first resizing (shortening) is not correct + PTF_ASSERT_EQUAL(packet.getRawPacket()->getRawDataLen(), + (int)payload2_size); // Size of packet after first resizing (shortening) is not correct // confirm that data has been correctly written to raw packet - const uint8_t* rawData = packet.getRawPacket()->getRawData() + (packet.getRawPacket()->getRawDataLen() - payload2_size); - PTF_ASSERT_EQUAL(rawData[0], 0x05); // Setting payload to new payload has failed. + const uint8_t* rawData = + packet.getRawPacket()->getRawData() + (packet.getRawPacket()->getRawDataLen() - payload2_size); + PTF_ASSERT_EQUAL(rawData[0], 0x05); // Setting payload to new payload has failed. PTF_ASSERT_EQUAL(rawData[1], 0x04); PTF_ASSERT_EQUAL(rawData[2], 0x03); PTF_ASSERT_EQUAL(rawData[3], 0x02); @@ -958,11 +963,13 @@ PTF_TEST_CASE(ResizeLayerTest) payloadLayer.setPayload(payload3, payload3_size); // check that resizing worked in terms of data length - PTF_ASSERT_EQUAL(packet.getRawPacket()->getRawDataLen(), (int)payload3_size); // Size of packet after second resizing (extension) is not correct + PTF_ASSERT_EQUAL(packet.getRawPacket()->getRawDataLen(), + (int)payload3_size); // Size of packet after second resizing (extension) is not correct // confirm that data has been correctly written to raw packet - const uint8_t* rawData2 = packet.getRawPacket()->getRawData() + (packet.getRawPacket()->getRawDataLen() - payload3_size); - PTF_ASSERT_EQUAL(rawData2[0], 0xDE); // Setting payload to new payload has failed. + const uint8_t* rawData2 = + packet.getRawPacket()->getRawData() + (packet.getRawPacket()->getRawDataLen() - payload3_size); + PTF_ASSERT_EQUAL(rawData2[0], 0xDE); // Setting payload to new payload has failed. PTF_ASSERT_EQUAL(rawData2[1], 0xAD); PTF_ASSERT_EQUAL(rawData2[2], 0xBE); PTF_ASSERT_EQUAL(rawData2[3], 0xEF); @@ -970,8 +977,7 @@ PTF_TEST_CASE(ResizeLayerTest) PTF_ASSERT_EQUAL(rawData2[5], 0xAD); PTF_ASSERT_EQUAL(rawData2[6], 0xBE); PTF_ASSERT_EQUAL(rawData2[7], 0xEF); -} // ResizeLayerTest - +} // ResizeLayerTest PTF_TEST_CASE(PrintPacketAndLayersTest) { @@ -981,9 +987,9 @@ PTF_TEST_CASE(PrintPacketAndLayersTest) // convert the timestamp to a printable format time_t nowtime = time.tv_sec; - struct tm *nowtm = nullptr; + struct tm* nowtm = nullptr; #if __cplusplus > 199711L && !defined(_WIN32) - // localtime_r is a thread-safe versions of localtime, + // localtime_r is a thread-safe versions of localtime, // but they're defined only in newer compilers (>= C++0x). // on Windows localtime is already thread-safe so there is not need // to use localtime_r @@ -1001,7 +1007,8 @@ PTF_TEST_CASE(PrintPacketAndLayersTest) READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/MplsPackets1.dat"); pcpp::Packet packet(&rawPacket1); - std::string expectedPacketHeaderString = "Packet length: 361 [Bytes], Arrival time: " + std::string(tmbuf) + ".000000000"; + std::string expectedPacketHeaderString = + "Packet length: 361 [Bytes], Arrival time: " + std::string(tmbuf) + ".000000000"; std::vector expectedLayerStrings; expectedLayerStrings.push_back("Ethernet II Layer, Src: 50:81:89:f9:d5:7b, Dst: 28:c2:ce:ba:97:e8"); expectedLayerStrings.push_back("VLAN Layer, Priority: 0, Vlan ID: 215, CFI: 0"); @@ -1040,8 +1047,7 @@ PTF_TEST_CASE(PrintPacketAndLayersTest) std::vector packetAsStringList; packet.toStringList(packetAsStringList); PTF_ASSERT_TRUE(packetAsStringList == expectedLayerStrings); -} // PrintPacketAndLayer - +} // PrintPacketAndLayer PTF_TEST_CASE(ProtocolFamilyMembershipTest) { diff --git a/Tests/Packet++Test/Tests/PacketUtilsTests.cpp b/Tests/Packet++Test/Tests/PacketUtilsTests.cpp index bd8ab1aaf5..9e7d4f4ba8 100644 --- a/Tests/Packet++Test/Tests/PacketUtilsTests.cpp +++ b/Tests/Packet++Test/Tests/PacketUtilsTests.cpp @@ -25,7 +25,6 @@ PTF_TEST_CASE(PacketUtilsHash5TupleUdp) srcDstPacket.addLayer(&udpLayer); srcDstPacket.computeCalculateFields(); - pcpp::IPv4Layer ipLayer2(dstIP, srcIP); ipLayer2.getIPv4Header()->ipId = htobe16(20300); ipLayer2.getIPv4Header()->fragmentOffset = htobe16(0x4000); @@ -48,7 +47,7 @@ PTF_TEST_CASE(PacketUtilsHash5TupleUdp) PTF_ASSERT_EQUAL(pcpp::hash5Tuple(&dstSrcPacket, false), 683027169); PTF_ASSERT_EQUAL(pcpp::hash5Tuple(&dstSrcPacket, true), 683027169); -} // PacketUtilsHash5TupleUdp +} // PacketUtilsHash5TupleUdp PTF_TEST_CASE(PacketUtilsHash5TupleTcp) { @@ -70,7 +69,6 @@ PTF_TEST_CASE(PacketUtilsHash5TupleTcp) srcDstPacket.addLayer(&tcpLayer); srcDstPacket.computeCalculateFields(); - pcpp::IPv4Layer ipLayer2(dstIP, srcIP); ipLayer2.getIPv4Header()->ipId = htobe16(20300); ipLayer2.getIPv4Header()->fragmentOffset = htobe16(0x4000); @@ -94,11 +92,10 @@ PTF_TEST_CASE(PacketUtilsHash5TupleTcp) PTF_ASSERT_EQUAL(pcpp::hash5Tuple(&srcDstPacket, false), 1576639238); PTF_ASSERT_EQUAL(pcpp::hash5Tuple(&srcDstPacket, true), 2243556734); - PTF_ASSERT_EQUAL(pcpp::hash5Tuple(&dstSrcPacket, false), 1576639238 ); - PTF_ASSERT_EQUAL(pcpp::hash5Tuple(&dstSrcPacket, true), 1576639238 ); - -} // PacketUtilsHash5TupleTcp + PTF_ASSERT_EQUAL(pcpp::hash5Tuple(&dstSrcPacket, false), 1576639238); + PTF_ASSERT_EQUAL(pcpp::hash5Tuple(&dstSrcPacket, true), 1576639238); +} // PacketUtilsHash5TupleTcp PTF_TEST_CASE(PacketUtilsHash5TupleIPv6) { @@ -113,7 +110,6 @@ PTF_TEST_CASE(PacketUtilsHash5TupleIPv6) srcDstPacket.addLayer(&udpLayer); srcDstPacket.computeCalculateFields(); - pcpp::IPv6Layer ipLayer2(dstIP, srcIP); pcpp::UdpLayer udpLayer2(1900, 63628); @@ -133,4 +129,4 @@ PTF_TEST_CASE(PacketUtilsHash5TupleIPv6) PTF_ASSERT_EQUAL(pcpp::hash5Tuple(&dstSrcPacket, false), 4288746927); PTF_ASSERT_EQUAL(pcpp::hash5Tuple(&dstSrcPacket, true), 4288746927); -} // PacketUtilsHash5TupleIPv6 +} // PacketUtilsHash5TupleIPv6 diff --git a/Tests/Packet++Test/Tests/RadiusTests.cpp b/Tests/Packet++Test/Tests/RadiusTests.cpp index 01339f8ae8..811ff95a2d 100644 --- a/Tests/Packet++Test/Tests/RadiusTests.cpp +++ b/Tests/Packet++Test/Tests/RadiusTests.cpp @@ -8,7 +8,6 @@ #include "RadiusLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(RadiusLayerParsingTest) { timeval time; @@ -30,7 +29,7 @@ PTF_TEST_CASE(RadiusLayerParsingTest) size_t attrDataSize[10] = { 4, 4, 4, 12, 17, 17, 4, 4, 17, 16 }; pcpp::RadiusAttribute radiusAttr = radiusLayer->getFirstAttribute(); PTF_PRINT_VERBOSE("Iterating over RADIUS attributes"); - for (int i=0; i<10; i++) + for (int i = 0; i < 10; i++) { PTF_PRINT_VERBOSE("Iteration #" << i); PTF_ASSERT_EQUAL(radiusAttr.getType(), attrTypes[i]); @@ -63,7 +62,7 @@ PTF_TEST_CASE(RadiusLayerParsingTest) size_t attrDataSize2[2] = { 4, 16 }; radiusAttr = radiusLayer->getFirstAttribute(); PTF_PRINT_VERBOSE("Iterating over RADIUS attributes"); - for (int i=0; i<2; i++) + for (int i = 0; i < 2; i++) { PTF_PRINT_VERBOSE("Iteration #" << i); PTF_ASSERT_EQUAL(radiusAttr.getType(), attrTypes2[i]); @@ -78,9 +77,7 @@ PTF_TEST_CASE(RadiusLayerParsingTest) radiusLayer = radiusPacket3.getLayerOfType(); PTF_ASSERT_NULL(radiusLayer); -} // RadiusLayerParsingTest - - +} // RadiusLayerParsingTest PTF_TEST_CASE(RadiusLayerCreationTest) { @@ -97,7 +94,8 @@ PTF_TEST_CASE(RadiusLayerCreationTest) pcpp::UdpLayer udpLayer(*radiusPacket.getLayerOfType()); pcpp::RadiusLayer radiusLayer(11, 5, "f050649184625d36f14c9075b7a48b83"); - pcpp::RadiusAttribute radiusNewAttr = radiusLayer.addAttribute(pcpp::RadiusAttributeBuilder(8, pcpp::IPv4Address("255.255.255.254"))); + pcpp::RadiusAttribute radiusNewAttr = + radiusLayer.addAttribute(pcpp::RadiusAttributeBuilder(8, pcpp::IPv4Address("255.255.255.254"))); PTF_ASSERT_FALSE(radiusNewAttr.isNull()); PTF_ASSERT_EQUAL(radiusNewAttr.getType(), 8); PTF_ASSERT_EQUAL(radiusNewAttr.getDataSize(), 4); @@ -124,17 +122,20 @@ PTF_TEST_CASE(RadiusLayerCreationTest) PTF_ASSERT_EQUAL(radiusNewAttr.getType(), 6); PTF_ASSERT_EQUAL(radiusNewAttr.getDataSize(), 4); - uint8_t attrValue1[] = { 0xc6, 0xd1, 0x95, 0x03, 0x2f, 0xdc, 0x30, 0x24, 0x0f, 0x73, 0x13, 0xb2, 0x31, 0xef, 0x1d, 0x77 }; + uint8_t attrValue1[] = { 0xc6, 0xd1, 0x95, 0x03, 0x2f, 0xdc, 0x30, 0x24, + 0x0f, 0x73, 0x13, 0xb2, 0x31, 0xef, 0x1d, 0x77 }; uint8_t attrValue1Len = 16; radiusNewAttr = radiusLayer.addAttribute(pcpp::RadiusAttributeBuilder(24, attrValue1, attrValue1Len)); PTF_ASSERT_FALSE(radiusNewAttr.isNull()); - uint8_t attrValue2[] = { 0x01, 0x01, 0x00, 0x16, 0x04, 0x10, 0x26, 0x6b, 0x0e, 0x9a, 0x58, 0x32, 0x2f, 0x4d, 0x01, 0xab, 0x25, 0xb3, 0x5f, 0x87, 0x94, 0x64 }; + uint8_t attrValue2[] = { 0x01, 0x01, 0x00, 0x16, 0x04, 0x10, 0x26, 0x6b, 0x0e, 0x9a, 0x58, + 0x32, 0x2f, 0x4d, 0x01, 0xab, 0x25, 0xb3, 0x5f, 0x87, 0x94, 0x64 }; uint8_t attrValue2Len = 22; radiusNewAttr = radiusLayer.addAttributeAfter(pcpp::RadiusAttributeBuilder(79, attrValue2, attrValue2Len), 18); PTF_ASSERT_FALSE(radiusNewAttr.isNull()); - uint8_t attrValue3[] = { 0x11, 0xb5, 0x04, 0x3c, 0x8a, 0x28, 0x87, 0x58, 0x17, 0x31, 0x33, 0xa5, 0xe0, 0x74, 0x34, 0xcf }; + uint8_t attrValue3[] = { 0x11, 0xb5, 0x04, 0x3c, 0x8a, 0x28, 0x87, 0x58, + 0x17, 0x31, 0x33, 0xa5, 0xe0, 0x74, 0x34, 0xcf }; uint8_t attrValue3Len = 16; radiusNewAttr = radiusLayer.addAttributeAfter(pcpp::RadiusAttributeBuilder(80, attrValue3, attrValue3Len), 79); PTF_ASSERT_FALSE(radiusNewAttr.isNull()); @@ -145,9 +146,7 @@ PTF_TEST_CASE(RadiusLayerCreationTest) pcpp::RadiusLayer* newRadiusLayer = newRadiusPacket.getLayerOfType(); PTF_ASSERT_EQUAL(origRadiusLayer->getDataLen(), newRadiusLayer->getDataLen()); PTF_ASSERT_BUF_COMPARE(origRadiusLayer->getData(), newRadiusLayer->getData(), origRadiusLayer->getDataLen()); -} // RadiusLayerCreationTest - - +} // RadiusLayerCreationTest PTF_TEST_CASE(RadiusLayerEditTest) { @@ -171,7 +170,8 @@ PTF_TEST_CASE(RadiusLayerEditTest) PTF_ASSERT_TRUE(radiusLayer->removeAttribute(80)); PTF_ASSERT_TRUE(radiusLayer->removeAttribute(24)); - pcpp::RadiusAttribute radiusNewAttr = radiusLayer->addAttributeAfter(pcpp::RadiusAttributeBuilder(18, std::string("Hello, John.McGuirk")), 6); + pcpp::RadiusAttribute radiusNewAttr = + radiusLayer->addAttributeAfter(pcpp::RadiusAttributeBuilder(18, std::string("Hello, John.McGuirk")), 6); PTF_ASSERT_FALSE(radiusNewAttr.isNull()); uint8_t attrValue1[] = { 0x03, 0x01, 0x00, 0x04 }; @@ -179,7 +179,8 @@ PTF_TEST_CASE(RadiusLayerEditTest) radiusNewAttr = radiusLayer->addAttributeAfter(pcpp::RadiusAttributeBuilder(79, attrValue1, attrValue1Len), 18); PTF_ASSERT_FALSE(radiusNewAttr.isNull()); - uint8_t attrValue2[] = { 0xb9, 0xc4, 0xae, 0x62, 0x13, 0xa7, 0x1d, 0x32, 0x12, 0x5e, 0xf7, 0xca, 0x4e, 0x4c, 0x63, 0x60 }; + uint8_t attrValue2[] = { 0xb9, 0xc4, 0xae, 0x62, 0x13, 0xa7, 0x1d, 0x32, + 0x12, 0x5e, 0xf7, 0xca, 0x4e, 0x4c, 0x63, 0x60 }; uint8_t attrValue2Len = 16; radiusNewAttr = radiusLayer->addAttributeAfter(pcpp::RadiusAttributeBuilder(80, attrValue2, attrValue2Len), 79); PTF_ASSERT_FALSE(radiusNewAttr.isNull()); @@ -193,7 +194,6 @@ PTF_TEST_CASE(RadiusLayerEditTest) PTF_ASSERT_EQUAL(msg2OrigRadiusLayer->getDataLen(), radiusLayer->getDataLen()); PTF_ASSERT_BUF_COMPARE(msg2OrigRadiusLayer->getData(), radiusLayer->getData(), msg2OrigRadiusLayer->getDataLen()); - // remove all attributes test PTF_ASSERT_TRUE(msg2OrigRadiusLayer->removeAllAttributes()); @@ -203,4 +203,4 @@ PTF_TEST_CASE(RadiusLayerEditTest) PTF_ASSERT_TRUE(msg2OrigRadiusLayer->getFirstAttribute().isNull()); PTF_ASSERT_TRUE(msg2OrigRadiusLayer->getAttribute(6).isNull()); PTF_ASSERT_TRUE(msg2OrigRadiusLayer->getAttribute(80).isNull()); -} // RadiusLayerEditTest +} // RadiusLayerEditTest diff --git a/Tests/Packet++Test/Tests/S7CommTests.cpp b/Tests/Packet++Test/Tests/S7CommTests.cpp index b644ed51fa..e7bc2267a4 100644 --- a/Tests/Packet++Test/Tests/S7CommTests.cpp +++ b/Tests/Packet++Test/Tests/S7CommTests.cpp @@ -5,7 +5,6 @@ #include "S7CommLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(S7CommLayerParsingTest) { timeval time; @@ -14,7 +13,7 @@ PTF_TEST_CASE(S7CommLayerParsingTest) pcpp::Packet s7CommLayerTest(&rawPacket1); PTF_ASSERT_TRUE(s7CommLayerTest.isPacketOfType(pcpp::S7COMM)); - auto *S7CommLayer = s7CommLayerTest.getLayerOfType(); + auto* S7CommLayer = s7CommLayerTest.getLayerOfType(); PTF_ASSERT_NOT_NULL(S7CommLayer); PTF_ASSERT_EQUAL(S7CommLayer->getProtocolId(), 50); @@ -26,14 +25,14 @@ PTF_TEST_CASE(S7CommLayerParsingTest) PTF_ASSERT_EQUAL(S7CommLayer->toString(), "S7Comm Layer, Userdata"); PTF_ASSERT_EQUAL(S7CommLayer->getParameter()->getDataLength(), 12); - uint8_t expectedParameterData[] = {0, 1, 18, 8, 18, 132, 1, 1, 0, 0, 0, 0}; + uint8_t expectedParameterData[] = { 0, 1, 18, 8, 18, 132, 1, 1, 0, 0, 0, 0 }; PTF_ASSERT_BUF_COMPARE(S7CommLayer->getParameter()->getData(), expectedParameterData, 12); READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/s7comm_ack_data.dat"); pcpp::Packet s7CommLayerTest2(&rawPacket2); PTF_ASSERT_TRUE(s7CommLayerTest2.isPacketOfType(pcpp::S7COMM)); - auto *s7commLayer = s7CommLayerTest2.getLayerOfType(); + auto* s7commLayer = s7CommLayerTest2.getLayerOfType(); PTF_ASSERT_NOT_NULL(s7commLayer); PTF_ASSERT_EQUAL(s7commLayer->getProtocolId(), 50); PTF_ASSERT_EQUAL(s7commLayer->getMsgType(), 3); @@ -51,10 +50,9 @@ PTF_TEST_CASE(S7CommLayerParsingTest) PTF_ASSERT_EQUAL(s7commLayer->getErrorClass(), 7); PTF_ASSERT_EQUAL(s7commLayer->getErrorCode(), 6); PTF_ASSERT_EQUAL(s7commLayer->getParameter()->getDataLength(), 2); - uint8_t expectedErrorParameterData[] = {4, 1}; + uint8_t expectedErrorParameterData[] = { 4, 1 }; PTF_ASSERT_BUF_COMPARE(s7commLayer->getParameter()->getData(), expectedErrorParameterData, 2); -} // S7CommLayerParsingTest - +} // S7CommLayerParsingTest PTF_TEST_CASE(S7CommLayerCreationTest) { @@ -84,4 +82,4 @@ PTF_TEST_CASE(S7CommLayerCreationTest) PTF_ASSERT_EQUAL(newS7commLayer2.getErrorCode(), 2); PTF_ASSERT_EQUAL(newS7commLayer2.getHeaderLen(), 82); PTF_ASSERT_EQUAL(newS7commLayer2.toString(), "S7Comm Layer, Ack-Data"); -} // S7CommLayerCreationTest +} // S7CommLayerCreationTest diff --git a/Tests/Packet++Test/Tests/SSHTests.cpp b/Tests/Packet++Test/Tests/SSHTests.cpp index d7e7a19b83..fb87c84d48 100644 --- a/Tests/Packet++Test/Tests/SSHTests.cpp +++ b/Tests/Packet++Test/Tests/SSHTests.cpp @@ -14,16 +14,17 @@ PTF_TEST_CASE(SSHParsingTest) // SSH Identification PTF_ASSERT_TRUE(sshIdentificationPacket.isPacketOfType(pcpp::SSH)); - pcpp::SSHIdentificationMessage* sshIdentLayer = sshIdentificationPacket.getLayerOfType(); + pcpp::SSHIdentificationMessage* sshIdentLayer = + sshIdentificationPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(sshIdentLayer); PTF_ASSERT_EQUAL(sshIdentLayer->getIdentificationMessage(), "SSH-2.0-OpenSSH_5.3"); - // SSH Key Exchange Init READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/SSHKexInit.dat"); pcpp::Packet sshKexInitPacket(&rawPacket2); PTF_ASSERT_TRUE(sshKexInitPacket.isPacketOfType(pcpp::SSH)); - pcpp::SSHKeyExchangeInitMessage* sshKexInitLayer = sshKexInitPacket.getLayerOfType(); + pcpp::SSHKeyExchangeInitMessage* sshKexInitLayer = + sshKexInitPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(sshKexInitLayer); PTF_ASSERT_EQUAL(sshKexInitLayer->getHeaderLen(), 904); PTF_ASSERT_EQUAL(sshKexInitLayer->getPaddingLength(), 4); @@ -32,19 +33,30 @@ PTF_TEST_CASE(SSHParsingTest) PTF_ASSERT_EQUAL(sshKexInitLayer->getMessageTypeStr(), "Key Exchange Init"); PTF_ASSERT_EQUAL(sshKexInitLayer->toString(), "SSH Layer, Handshake Message: Key Exchange Init"); PTF_ASSERT_EQUAL(sshKexInitLayer->getCookieAsHexStream(), "0e7b9a0807ea71e0945dd1fdbfa41929"); - PTF_ASSERT_EQUAL(sshKexInitLayer->getKeyExchangeAlgorithms(), "diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1"); - PTF_ASSERT_EQUAL(sshKexInitLayer->getServerHostKeyAlgorithms(), "ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,ssh-rsa,ssh-dss"); - PTF_ASSERT_EQUAL(sshKexInitLayer->getEncryptionAlgorithmsClientToServer(), "aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se"); - PTF_ASSERT_EQUAL(sshKexInitLayer->getEncryptionAlgorithmsServerToClient(), "aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se"); - PTF_ASSERT_EQUAL(sshKexInitLayer->getMacAlgorithmsClientToServer(), "hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96"); - PTF_ASSERT_EQUAL(sshKexInitLayer->getMacAlgorithmsServerToClient(), "hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96"); + PTF_ASSERT_EQUAL(sshKexInitLayer->getKeyExchangeAlgorithms(), + "diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-" + "sha1,diffie-hellman-group1-sha1"); + PTF_ASSERT_EQUAL(sshKexInitLayer->getServerHostKeyAlgorithms(), + "ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-" + "cert-v00@openssh.com,ssh-rsa,ssh-dss"); + PTF_ASSERT_EQUAL(sshKexInitLayer->getEncryptionAlgorithmsClientToServer(), + "aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-" + "cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se"); + PTF_ASSERT_EQUAL(sshKexInitLayer->getEncryptionAlgorithmsServerToClient(), + "aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-" + "cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se"); + PTF_ASSERT_EQUAL( + sshKexInitLayer->getMacAlgorithmsClientToServer(), + "hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96"); + PTF_ASSERT_EQUAL( + sshKexInitLayer->getMacAlgorithmsServerToClient(), + "hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96"); PTF_ASSERT_EQUAL(sshKexInitLayer->getCompressionAlgorithmsClientToServer(), "none,zlib@openssh.com,zlib"); PTF_ASSERT_EQUAL(sshKexInitLayer->getCompressionAlgorithmsServerToClient(), "none,zlib@openssh.com,zlib"); PTF_ASSERT_EQUAL(sshKexInitLayer->getLanguagesClientToServer(), ""); PTF_ASSERT_EQUAL(sshKexInitLayer->getLanguagesServerToClient(), ""); PTF_ASSERT_FALSE(sshKexInitLayer->isFirstKexPacketFollows()); - READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/SSHNewKeysAndKexDH.dat"); pcpp::Packet sshNewKeysKexDHPacket(&rawPacket3); PTF_ASSERT_TRUE(sshNewKeysKexDHPacket.isPacketOfType(pcpp::SSH)); @@ -56,7 +68,8 @@ PTF_TEST_CASE(SSHParsingTest) PTF_ASSERT_EQUAL(sshHandshakeMessage->getSSHHandshakeMessageLength(), 691); PTF_ASSERT_EQUAL(sshHandshakeMessage->getMessageType(), pcpp::SSHHandshakeMessage::SSH_MSG_KEX_DH_GEX_REPLY, enum); PTF_ASSERT_EQUAL(sshHandshakeMessage->getMessageTypeStr(), "Diffie-Hellman Group Exchange Reply"); - PTF_ASSERT_EQUAL(sshHandshakeMessage->toString(), "SSH Layer, Handshake Message: Diffie-Hellman Group Exchange Reply"); + PTF_ASSERT_EQUAL(sshHandshakeMessage->toString(), + "SSH Layer, Handshake Message: Diffie-Hellman Group Exchange Reply"); // SSH New Keys sshHandshakeMessage = sshNewKeysKexDHPacket.getNextLayerOfType(sshHandshakeMessage); @@ -68,7 +81,6 @@ PTF_TEST_CASE(SSHParsingTest) PTF_ASSERT_EQUAL(sshHandshakeMessage->getMessageTypeStr(), "New Keys"); PTF_ASSERT_EQUAL(sshHandshakeMessage->toString(), "SSH Layer, Handshake Message: New Keys"); - // SSH DH Group Exchange Init READ_FILE_AND_CREATE_PACKET(4, "PacketExamples/SSHDHGexInit.dat"); pcpp::Packet sshDHGexInit(&rawPacket4); @@ -80,8 +92,8 @@ PTF_TEST_CASE(SSHParsingTest) PTF_ASSERT_EQUAL(sshHandshakeMessage->getSSHHandshakeMessageLength(), 133); PTF_ASSERT_EQUAL(sshHandshakeMessage->getMessageType(), pcpp::SSHHandshakeMessage::SSH_MSG_KEX_DH_GEX_INIT, enum); PTF_ASSERT_EQUAL(sshHandshakeMessage->getMessageTypeStr(), "Diffie-Hellman Group Exchange Init"); - PTF_ASSERT_EQUAL(sshHandshakeMessage->toString(), "SSH Layer, Handshake Message: Diffie-Hellman Group Exchange Init"); - + PTF_ASSERT_EQUAL(sshHandshakeMessage->toString(), + "SSH Layer, Handshake Message: Diffie-Hellman Group Exchange Init"); // SSH Encrypted Message READ_FILE_AND_CREATE_PACKET(5, "PacketExamples/SSHEncryptedMessage.dat"); @@ -93,7 +105,6 @@ PTF_TEST_CASE(SSHParsingTest) PTF_ASSERT_EQUAL(sshEncryptedMsgLayer->toString(), "SSH Layer, Encrypted Message"); } - PTF_TEST_CASE(SSHMalformedParsingTest) { timeval time; @@ -127,21 +138,31 @@ PTF_TEST_CASE(SSHMalformedParsingTest) PTF_ASSERT_NULL(sshMessageMalformedTypePacket.getLayerOfType()); PTF_ASSERT_NOT_NULL(sshMessageMalformedTypePacket.getLayerOfType()); - //KexInit with malformed size of MacAlgorithmsClientToServer (size is greater than the size of the rest of the layer) + // KexInit with malformed size of MacAlgorithmsClientToServer (size is greater than the size of the rest of the + // layer) READ_FILE_AND_CREATE_PACKET(5, "PacketExamples/SSHKexInit_Malformed.dat"); pcpp::Packet sshKexInitMalformedPacket(&rawPacket5); PTF_ASSERT_TRUE(sshKexInitMalformedPacket.isPacketOfType(pcpp::SSH)); - pcpp::SSHKeyExchangeInitMessage* sshKexInitLayer = sshKexInitMalformedPacket.getLayerOfType(); + pcpp::SSHKeyExchangeInitMessage* sshKexInitLayer = + sshKexInitMalformedPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(sshKexInitLayer); PTF_ASSERT_EQUAL(sshKexInitLayer->getHeaderLen(), 904); PTF_ASSERT_EQUAL(sshKexInitLayer->getPaddingLength(), 4); PTF_ASSERT_EQUAL(sshKexInitLayer->getSSHHandshakeMessageLength(), 894); PTF_ASSERT_EQUAL(sshKexInitLayer->getMessageType(), pcpp::SSHHandshakeMessage::SSH_MSG_KEX_INIT, enum); PTF_ASSERT_EQUAL(sshKexInitLayer->getCookieAsHexStream(), "0e7b9a0807ea71e0945dd1fdbfa41929"); - PTF_ASSERT_EQUAL(sshKexInitLayer->getKeyExchangeAlgorithms(), "diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1"); - PTF_ASSERT_EQUAL(sshKexInitLayer->getServerHostKeyAlgorithms(), "ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,ssh-rsa,ssh-dss"); - PTF_ASSERT_EQUAL(sshKexInitLayer->getEncryptionAlgorithmsClientToServer(), "aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se"); - PTF_ASSERT_EQUAL(sshKexInitLayer->getEncryptionAlgorithmsServerToClient(), "aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se"); + PTF_ASSERT_EQUAL(sshKexInitLayer->getKeyExchangeAlgorithms(), + "diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-" + "sha1,diffie-hellman-group1-sha1"); + PTF_ASSERT_EQUAL(sshKexInitLayer->getServerHostKeyAlgorithms(), + "ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-" + "cert-v00@openssh.com,ssh-rsa,ssh-dss"); + PTF_ASSERT_EQUAL(sshKexInitLayer->getEncryptionAlgorithmsClientToServer(), + "aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-" + "cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se"); + PTF_ASSERT_EQUAL(sshKexInitLayer->getEncryptionAlgorithmsServerToClient(), + "aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-" + "cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se"); PTF_ASSERT_EQUAL(sshKexInitLayer->getMacAlgorithmsClientToServer(), ""); PTF_ASSERT_EQUAL(sshKexInitLayer->getMacAlgorithmsServerToClient(), ""); PTF_ASSERT_EQUAL(sshKexInitLayer->getCompressionAlgorithmsClientToServer(), ""); diff --git a/Tests/Packet++Test/Tests/SSLTests.cpp b/Tests/Packet++Test/Tests/SSLTests.cpp index 1ca311bcea..1ac2574fca 100644 --- a/Tests/Packet++Test/Tests/SSLTests.cpp +++ b/Tests/Packet++Test/Tests/SSLTests.cpp @@ -7,7 +7,6 @@ #include #include - PTF_TEST_CASE(SSLClientHelloParsingTest) { timeval time; @@ -20,7 +19,8 @@ PTF_TEST_CASE(SSLClientHelloParsingTest) pcpp::SSLHandshakeLayer* handshakeLayer = clientHelloPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(handshakeLayer); PTF_ASSERT_EQUAL(handshakeLayer->getHandshakeMessagesCount(), 1); - pcpp::SSLClientHelloMessage* clientHelloMessage = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLClientHelloMessage* clientHelloMessage = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_EQUAL(handshakeLayer->getHandshakeMessageAt(0), clientHelloMessage, ptr); PTF_ASSERT_NOT_NULL(clientHelloMessage); PTF_ASSERT_EQUAL(handshakeLayer->getRecordType(), pcpp::SSL_HANDSHAKE, enum); @@ -35,75 +35,41 @@ PTF_TEST_CASE(SSLClientHelloParsingTest) PTF_ASSERT_NULL(clientHelloMessage->getSessionID()); PTF_ASSERT_EQUAL(clientHelloMessage->getCipherSuiteCount(), 11); - uint16_t cipherSuiteIDs[11] = { 0xc02b, 0xc02f, 0xc00a, 0xc009, 0xc013, 0xc014, 0x0033, 0x0039, 0x002f, 0x0035, 0x000a }; - std::string cipherSuiteNames[11] = { - "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", - "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", - "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", - "TLS_RSA_WITH_AES_256_CBC_SHA", - "TLS_RSA_WITH_3DES_EDE_CBC_SHA" - }; + uint16_t cipherSuiteIDs[11] = { 0xc02b, 0xc02f, 0xc00a, 0xc009, 0xc013, 0xc014, + 0x0033, 0x0039, 0x002f, 0x0035, 0x000a }; + std::string cipherSuiteNames[11] = { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", + "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", + "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", + "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", + "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", + "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", + "TLS_RSA_WITH_AES_128_CBC_SHA", + "TLS_RSA_WITH_AES_256_CBC_SHA", + "TLS_RSA_WITH_3DES_EDE_CBC_SHA" }; pcpp::SSLKeyExchangeAlgorithm cipherSuiteKey[11] = { - pcpp::SSL_KEYX_ECDHE, - pcpp::SSL_KEYX_ECDHE, - pcpp::SSL_KEYX_ECDHE, - pcpp::SSL_KEYX_ECDHE, - pcpp::SSL_KEYX_ECDHE, - pcpp::SSL_KEYX_ECDHE, - pcpp::SSL_KEYX_DHE, - pcpp::SSL_KEYX_DHE, - pcpp::SSL_KEYX_RSA, - pcpp::SSL_KEYX_RSA, - pcpp::SSL_KEYX_RSA + pcpp::SSL_KEYX_ECDHE, pcpp::SSL_KEYX_ECDHE, pcpp::SSL_KEYX_ECDHE, pcpp::SSL_KEYX_ECDHE, + pcpp::SSL_KEYX_ECDHE, pcpp::SSL_KEYX_ECDHE, pcpp::SSL_KEYX_DHE, pcpp::SSL_KEYX_DHE, + pcpp::SSL_KEYX_RSA, pcpp::SSL_KEYX_RSA, pcpp::SSL_KEYX_RSA }; pcpp::SSLAuthenticationAlgorithm cipherSuiteAuth[11] = { - pcpp::SSL_AUTH_ECDSA, - pcpp::SSL_AUTH_RSA, - pcpp::SSL_AUTH_ECDSA, - pcpp::SSL_AUTH_ECDSA, - pcpp::SSL_AUTH_RSA, - pcpp::SSL_AUTH_RSA, - pcpp::SSL_AUTH_RSA, - pcpp::SSL_AUTH_RSA, - pcpp::SSL_AUTH_RSA, - pcpp::SSL_AUTH_RSA, - pcpp::SSL_AUTH_RSA + pcpp::SSL_AUTH_ECDSA, pcpp::SSL_AUTH_RSA, pcpp::SSL_AUTH_ECDSA, pcpp::SSL_AUTH_ECDSA, + pcpp::SSL_AUTH_RSA, pcpp::SSL_AUTH_RSA, pcpp::SSL_AUTH_RSA, pcpp::SSL_AUTH_RSA, + pcpp::SSL_AUTH_RSA, pcpp::SSL_AUTH_RSA, pcpp::SSL_AUTH_RSA }; pcpp::SSLSymetricEncryptionAlgorithm cipherSuiteSym[11] = { - pcpp::SSL_SYM_AES_128_GCM, - pcpp::SSL_SYM_AES_128_GCM, - pcpp::SSL_SYM_AES_256_CBC, - pcpp::SSL_SYM_AES_128_CBC, - pcpp::SSL_SYM_AES_128_CBC, - pcpp::SSL_SYM_AES_256_CBC, - pcpp::SSL_SYM_AES_128_CBC, - pcpp::SSL_SYM_AES_256_CBC, - pcpp::SSL_SYM_AES_128_CBC, - pcpp::SSL_SYM_AES_256_CBC, - pcpp::SSL_SYM_3DES_EDE_CBC + pcpp::SSL_SYM_AES_128_GCM, pcpp::SSL_SYM_AES_128_GCM, pcpp::SSL_SYM_AES_256_CBC, pcpp::SSL_SYM_AES_128_CBC, + pcpp::SSL_SYM_AES_128_CBC, pcpp::SSL_SYM_AES_256_CBC, pcpp::SSL_SYM_AES_128_CBC, pcpp::SSL_SYM_AES_256_CBC, + pcpp::SSL_SYM_AES_128_CBC, pcpp::SSL_SYM_AES_256_CBC, pcpp::SSL_SYM_3DES_EDE_CBC }; - pcpp::SSLHashingAlgorithm cipherSuiteHash[11] = { - pcpp::SSL_HASH_SHA256, - pcpp::SSL_HASH_SHA256, - pcpp::SSL_HASH_SHA, - pcpp::SSL_HASH_SHA, - pcpp::SSL_HASH_SHA, - pcpp::SSL_HASH_SHA, - pcpp::SSL_HASH_SHA, - pcpp::SSL_HASH_SHA, - pcpp::SSL_HASH_SHA, - pcpp::SSL_HASH_SHA, - pcpp::SSL_HASH_SHA - }; + pcpp::SSLHashingAlgorithm cipherSuiteHash[11] = { pcpp::SSL_HASH_SHA256, pcpp::SSL_HASH_SHA256, pcpp::SSL_HASH_SHA, + pcpp::SSL_HASH_SHA, pcpp::SSL_HASH_SHA, pcpp::SSL_HASH_SHA, + pcpp::SSL_HASH_SHA, pcpp::SSL_HASH_SHA, pcpp::SSL_HASH_SHA, + pcpp::SSL_HASH_SHA, pcpp::SSL_HASH_SHA }; PTF_PRINT_VERBOSE("Iterating over cipher suites"); for (int i = 0; i < clientHelloMessage->getCipherSuiteCount(); i++) @@ -128,17 +94,20 @@ PTF_TEST_CASE(SSLClientHelloParsingTest) pcpp::SSLExtension* ext = clientHelloMessage->getExtension(0); PTF_ASSERT_EQUAL(ext->getType(), pcpp::SSL_EXT_SERVER_NAME, enum); - pcpp::SSLServerNameIndicationExtension* serverNameExt = clientHelloMessage->getExtensionOfType(); + pcpp::SSLServerNameIndicationExtension* serverNameExt = + clientHelloMessage->getExtensionOfType(); PTF_ASSERT_NOT_NULL(serverNameExt); PTF_ASSERT_EQUAL(serverNameExt->getHostName(), "www.google.com"); - pcpp::TLSECPointFormatExtension* ecPointFormatExt = clientHelloMessage->getExtensionOfType(); + pcpp::TLSECPointFormatExtension* ecPointFormatExt = + clientHelloMessage->getExtensionOfType(); PTF_ASSERT_NOT_NULL(ecPointFormatExt); std::vector ecPointFormatList = ecPointFormatExt->getECPointFormatList(); PTF_ASSERT_EQUAL(ecPointFormatList.size(), 1); PTF_ASSERT_EQUAL(ecPointFormatList.at(0), 0); - pcpp::TLSSupportedGroupsExtension* supportedGroupsExt = clientHelloMessage->getExtensionOfType(); + pcpp::TLSSupportedGroupsExtension* supportedGroupsExt = + clientHelloMessage->getExtensionOfType(); PTF_ASSERT_NOT_NULL(supportedGroupsExt); std::vector supportedGroups = supportedGroupsExt->getSupportedGroups(); PTF_ASSERT_EQUAL(supportedGroups.size(), 3); @@ -146,9 +115,15 @@ PTF_TEST_CASE(SSLClientHelloParsingTest) PTF_ASSERT_EQUAL(supportedGroups.at(1), 24); PTF_ASSERT_EQUAL(supportedGroups.at(2), 25); - pcpp::SSLExtensionType extTypes[9] = { pcpp::SSL_EXT_SERVER_NAME, pcpp::SSL_EXT_RENEGOTIATION_INFO, pcpp::SSL_EXT_SUPPORTED_GROUPS, pcpp::SSL_EXT_EC_POINT_FORMATS, - pcpp::SSL_EXT_SESSIONTICKET_TLS, pcpp::SSL_EXT_Unknown, pcpp::SSL_EXT_APPLICATION_LAYER_PROTOCOL_NEGOTIATION, pcpp::SSL_EXT_STATUS_REQUEST, - pcpp::SSL_EXT_SIGNATURE_ALGORITHMS }; + pcpp::SSLExtensionType extTypes[9] = { pcpp::SSL_EXT_SERVER_NAME, + pcpp::SSL_EXT_RENEGOTIATION_INFO, + pcpp::SSL_EXT_SUPPORTED_GROUPS, + pcpp::SSL_EXT_EC_POINT_FORMATS, + pcpp::SSL_EXT_SESSIONTICKET_TLS, + pcpp::SSL_EXT_Unknown, + pcpp::SSL_EXT_APPLICATION_LAYER_PROTOCOL_NEGOTIATION, + pcpp::SSL_EXT_STATUS_REQUEST, + pcpp::SSL_EXT_SIGNATURE_ALGORITHMS }; uint16_t extLength[9] = { 19, 1, 8, 2, 0, 0, 23, 5, 22 }; @@ -161,9 +136,7 @@ PTF_TEST_CASE(SSLClientHelloParsingTest) PTF_ASSERT_EQUAL(curExt->getLength(), extLength[i]); PTF_ASSERT_EQUAL(clientHelloMessage->getExtensionOfType(extTypes[i]), curExt, ptr); } -} // SSLClientHelloParsingTest - - +} // SSLClientHelloParsingTest PTF_TEST_CASE(SSLExtensionWithZeroSizeTest) { @@ -175,7 +148,8 @@ PTF_TEST_CASE(SSLExtensionWithZeroSizeTest) pcpp::SSLHandshakeLayer* handshakeLayer = clientHelloPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(handshakeLayer); - pcpp::SSLClientHelloMessage* clientHelloMessage = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLClientHelloMessage* clientHelloMessage = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(clientHelloMessage); PTF_ASSERT_EQUAL(clientHelloMessage->getExtensionCount(), 7); @@ -186,8 +160,7 @@ PTF_TEST_CASE(SSLExtensionWithZeroSizeTest) PTF_ASSERT_EQUAL(zeroSizeExt->getTotalLength(), 4); PTF_ASSERT_NULL(zeroSizeExt->getData()); -} // SSLExtensionWithZeroSizeTest - +} // SSLExtensionWithZeroSizeTest PTF_TEST_CASE(SSLAppDataParsingTest) { @@ -222,9 +195,7 @@ PTF_TEST_CASE(SSLAppDataParsingTest) PTF_ASSERT_EQUAL(appDataLayer->getEncryptedData()[40], 0xec, hex); PTF_ASSERT_NULL(appDataLayer->getNextLayer()); -} // SSLAppDataParsingTest - - +} // SSLAppDataParsingTest PTF_TEST_CASE(SSLAlertParsingTest) { @@ -255,9 +226,7 @@ PTF_TEST_CASE(SSLAlertParsingTest) PTF_ASSERT_EQUAL(encAlertLayer->getAlertDescription(), pcpp::SSL_ALERT_ENCRYPTED, enum); PTF_ASSERT_EQUAL(encAlertLayer->getRecordLayer()->length, be16toh(26)); PTF_ASSERT_EQUAL(encAlertLayer->getHeaderLen(), 31); -} // SSLAlertParsingTest - - +} // SSLAlertParsingTest /** * Testing: server-hello, change-cipher-spec, encrypted handshake message @@ -274,7 +243,8 @@ PTF_TEST_CASE(SSLMultipleRecordParsingTest) pcpp::SSLHandshakeLayer* handshakeLayer = multipleRecordsPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(handshakeLayer); PTF_ASSERT_EQUAL(handshakeLayer->getHandshakeMessagesCount(), 1); - pcpp::SSLServerHelloMessage* serverHelloMessage = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLServerHelloMessage* serverHelloMessage = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(serverHelloMessage); PTF_ASSERT_EQUAL(serverHelloMessage->getSessionIDLength(), 32); PTF_ASSERT_EQUAL(serverHelloMessage->getSessionID()[0], 0xbf, hex); @@ -285,7 +255,9 @@ PTF_TEST_CASE(SSLMultipleRecordParsingTest) PTF_ASSERT_EQUAL(serverHelloMessage->getExtensionCount(), 3); uint16_t extensionsLength[3] = { 1, 5, 2 }; uint16_t totalExtensionsLength[3] = { 5, 9, 6 }; - pcpp::SSLExtensionType extensionTypes[3] = { pcpp::SSL_EXT_RENEGOTIATION_INFO, pcpp::SSL_EXT_APPLICATION_LAYER_PROTOCOL_NEGOTIATION, pcpp::SSL_EXT_EC_POINT_FORMATS }; + pcpp::SSLExtensionType extensionTypes[3] = { pcpp::SSL_EXT_RENEGOTIATION_INFO, + pcpp::SSL_EXT_APPLICATION_LAYER_PROTOCOL_NEGOTIATION, + pcpp::SSL_EXT_EC_POINT_FORMATS }; uint8_t extensionDataFirstByte[3] = { 0, 0, 1 }; PTF_PRINT_VERBOSE("iterating over SSL extensions"); for (int i = 0; i < 3; i++) @@ -297,7 +269,8 @@ PTF_TEST_CASE(SSLMultipleRecordParsingTest) PTF_ASSERT_EQUAL(curExt->getType(), extensionTypes[i], enum); PTF_ASSERT_EQUAL(curExt->getData()[0], extensionDataFirstByte[i]); } - pcpp::TLSECPointFormatExtension* ecPointFormatExt = serverHelloMessage->getExtensionOfType(); + pcpp::TLSECPointFormatExtension* ecPointFormatExt = + serverHelloMessage->getExtensionOfType(); PTF_ASSERT_NOT_NULL(ecPointFormatExt); std::vector ecPointFormatList = ecPointFormatExt->getECPointFormatList(); PTF_ASSERT_EQUAL(ecPointFormatList.size(), 1); @@ -316,9 +289,7 @@ PTF_TEST_CASE(SSLMultipleRecordParsingTest) PTF_ASSERT_NOT_NULL(unknownMessage); PTF_ASSERT_EQUAL(unknownMessage->getHandshakeType(), pcpp::SSL_HANDSHAKE_UNKNOWN, enum); PTF_ASSERT_EQUAL(unknownMessage->getMessageLength(), 40); -} // SSLMultipleRecordParsingTest - - +} // SSLMultipleRecordParsingTest /** * Testing: client-key-exchange @@ -337,7 +308,8 @@ PTF_TEST_CASE(SSLMultipleRecordParsing2Test) PTF_ASSERT_NOT_NULL(handshakeLayer); PTF_ASSERT_EQUAL(handshakeLayer->getHandshakeMessagesCount(), 1); - pcpp::SSLClientKeyExchangeMessage* clientKeyExMsg = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLClientKeyExchangeMessage* clientKeyExMsg = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(clientKeyExMsg); PTF_ASSERT_EQUAL(clientKeyExMsg->getHandshakeType(), pcpp::SSL_CLIENT_KEY_EXCHANGE, enum); PTF_ASSERT_EQUAL(clientKeyExMsg->getMessageLength(), 70); @@ -345,9 +317,7 @@ PTF_TEST_CASE(SSLMultipleRecordParsing2Test) PTF_ASSERT_EQUAL(clientKeyExMsg->getClientKeyExchangeParams()[0], 0x41, hex); PTF_ASSERT_EQUAL(clientKeyExMsg->getClientKeyExchangeParams()[10], 0xf2, hex); PTF_ASSERT_EQUAL(clientKeyExMsg->getClientKeyExchangeParams()[65], 0xdc, hex); -} // SSLMultipleRecordParsing2Test - - +} // SSLMultipleRecordParsing2Test /** * Testing - certificate, certificate-request @@ -378,7 +348,7 @@ PTF_TEST_CASE(SSLMultipleRecordParsing3Test) PTF_ASSERT_NOT_NULL(cert); PTF_ASSERT_TRUE(cert->allDataExists()); PTF_ASSERT_EQUAL(cert->getDataLength(), 1509); - std::string certBuffer(cert->getData(), cert->getData()+cert->getDataLength()); + std::string certBuffer(cert->getData(), cert->getData() + cert->getDataLength()); std::size_t pos = certBuffer.find("LDAP Intermediate CA"); PTF_ASSERT_TRUE(pos != std::string::npos); pos = certBuffer.find("Internal Development CA"); @@ -387,18 +357,19 @@ PTF_TEST_CASE(SSLMultipleRecordParsing3Test) PTF_ASSERT_NOT_NULL(cert); PTF_ASSERT_TRUE(cert->allDataExists()); PTF_ASSERT_EQUAL(cert->getDataLength(), 1728); - certBuffer = std::string(cert->getData(), cert->getData()+cert->getDataLength()); + certBuffer = std::string(cert->getData(), cert->getData() + cert->getDataLength()); pos = certBuffer.find("Internal Development CA"); PTF_ASSERT_TRUE(pos != std::string::npos); cert = certMsg->getCertificate(2); PTF_ASSERT_NOT_NULL(cert); PTF_ASSERT_TRUE(cert->allDataExists()); PTF_ASSERT_EQUAL(cert->getDataLength(), 1713); - certBuffer = std::string(cert->getData(), cert->getData()+cert->getDataLength()); + certBuffer = std::string(cert->getData(), cert->getData() + cert->getDataLength()); pos = certBuffer.find("Internal Development CA"); PTF_ASSERT_TRUE(pos != std::string::npos); - pcpp::SSLCertificateRequestMessage* certReqMsg = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLCertificateRequestMessage* certReqMsg = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_TRUE(certReqMsg->isMessageComplete()); PTF_ASSERT_EQUAL(certReqMsg->getHandshakeType(), pcpp::SSL_CERTIFICATE_REQUEST, enum); PTF_ASSERT_EQUAL(certReqMsg->getCertificateTypes().size(), 2); @@ -409,9 +380,7 @@ PTF_TEST_CASE(SSLMultipleRecordParsing3Test) PTF_ASSERT_EQUAL(certReqMsg->getCertificateAuthorityData()[1], 0x6c, hex); PTF_ASSERT_EQUAL(certReqMsg->getCertificateAuthorityData()[14], 0x2, hex); PTF_ASSERT_EQUAL(certReqMsg->getCertificateAuthorityData()[47], 0x13, hex); -} // SSLMultipleRecordParsing3Test - - +} // SSLMultipleRecordParsing3Test /** * Testing: server-key-exchange, server-hello-done @@ -430,7 +399,8 @@ PTF_TEST_CASE(SSLMultipleRecordParsing4Test) PTF_ASSERT_NOT_NULL(handshakeLayer); PTF_ASSERT_EQUAL(handshakeLayer->getHandshakeMessagesCount(), 1); - pcpp::SSLServerKeyExchangeMessage* serverKeyExMsg = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLServerKeyExchangeMessage* serverKeyExMsg = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(serverKeyExMsg); PTF_ASSERT_EQUAL(serverKeyExMsg->getHandshakeType(), pcpp::SSL_SERVER_KEY_EXCHANGE, enum); PTF_ASSERT_EQUAL(serverKeyExMsg->getMessageLength(), 333); @@ -442,14 +412,13 @@ PTF_TEST_CASE(SSLMultipleRecordParsing4Test) handshakeLayer = multipleRecordsPacket.getNextLayerOfType(handshakeLayer); PTF_ASSERT_NOT_NULL(handshakeLayer); PTF_ASSERT_EQUAL(handshakeLayer->getHandshakeMessagesCount(), 1); - pcpp::SSLServerHelloDoneMessage* serverHelloDoneMsg = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLServerHelloDoneMessage* serverHelloDoneMsg = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(serverHelloDoneMsg); PTF_ASSERT_EQUAL(serverHelloDoneMsg->getHandshakeType(), pcpp::SSL_SERVER_DONE, enum); PTF_ASSERT_EQUAL(serverHelloDoneMsg->getMessageLength(), 4); PTF_ASSERT_EQUAL(serverHelloDoneMsg, handshakeLayer->getHandshakeMessageAt(0), ptr); -} // SSLMultipleRecordParsing4Test - - +} // SSLMultipleRecordParsing4Test /** * Testing: change-cipher-spec, encrypted-handshake-message, application-data @@ -485,9 +454,7 @@ PTF_TEST_CASE(SSLMultipleRecordParsing5Test) PTF_ASSERT_EQUAL(appDataLayer->getEncryptedData()[16], 0x07, hex); PTF_ASSERT_EQUAL(appDataLayer->getEncryptedData()[61], 0x92, hex); PTF_ASSERT_NULL(appDataLayer->getNextLayer()); -} // SSLMultipleRecordParsing5Test - - +} // SSLMultipleRecordParsing5Test PTF_TEST_CASE(SSLPartialCertificateParseTest) { @@ -527,9 +494,7 @@ PTF_TEST_CASE(SSLPartialCertificateParseTest) cert = certMsg->getCertificate(0); PTF_ASSERT_FALSE(cert->allDataExists()); PTF_ASSERT_EQUAL(cert->getDataLength(), 1268); -} // SSLPartialCertificateParseTest - - +} // SSLPartialCertificateParseTest PTF_TEST_CASE(SSLNewSessionTicketParseTest) { @@ -545,7 +510,8 @@ PTF_TEST_CASE(SSLNewSessionTicketParseTest) PTF_ASSERT_NOT_NULL(handshakeLayer); PTF_ASSERT_EQUAL(handshakeLayer->getHandshakeMessagesCount(), 1); - pcpp::SSLNewSessionTicketMessage* newSessionTicketMsg = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLNewSessionTicketMessage* newSessionTicketMsg = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(newSessionTicketMsg); PTF_ASSERT_TRUE(newSessionTicketMsg->isMessageComplete()); PTF_ASSERT_EQUAL(newSessionTicketMsg->getHandshakeType(), pcpp::SSL_NEW_SESSION_TICKET, enum); @@ -553,8 +519,7 @@ PTF_TEST_CASE(SSLNewSessionTicketParseTest) PTF_ASSERT_EQUAL(newSessionTicketMsg->getSessionTicketData()[0], 0, hex); PTF_ASSERT_EQUAL(newSessionTicketMsg->getSessionTicketData()[16], 0xf9, hex); PTF_ASSERT_EQUAL(newSessionTicketMsg->getSessionTicketData()[213], 0x75, hex); -} // SSLNewSessionTicketParseTest - +} // SSLNewSessionTicketParseTest PTF_TEST_CASE(SSLMalformedPacketParsing) { @@ -567,11 +532,11 @@ PTF_TEST_CASE(SSLMalformedPacketParsing) pcpp::SSLHandshakeLayer* handshakeLayer = badSSLPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(handshakeLayer); - pcpp::SSLClientHelloMessage* clientHelloMessage = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLClientHelloMessage* clientHelloMessage = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(clientHelloMessage); PTF_ASSERT_EQUAL(clientHelloMessage->getExtensionCount(), 1); -} // SSLMalformedPacketParsing - +} // SSLMalformedPacketParsing PTF_TEST_CASE(TLS1_3ParsingTest) { @@ -585,29 +550,19 @@ PTF_TEST_CASE(TLS1_3ParsingTest) pcpp::Packet tls13ClientHello2(&rawPacket2); uint16_t cipherSuiteIDs[3] = { 0x1302, 0x1303, 0x1301 }; - std::string cipherSuiteNames[3] = - { - "TLS_AES_256_GCM_SHA384", - "TLS_CHACHA20_POLY1305_SHA256", - "TLS_AES_128_GCM_SHA256" - }; - pcpp::SSLSymetricEncryptionAlgorithm cipherSuiteSym[3] = - { - pcpp::SSL_SYM_AES_256_GCM, - pcpp::SSL_SYM_CHACHA20_POLY1305, - pcpp::SSL_SYM_AES_128_GCM - }; + std::string cipherSuiteNames[3] = { "TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256", + "TLS_AES_128_GCM_SHA256" }; + pcpp::SSLSymetricEncryptionAlgorithm cipherSuiteSym[3] = { pcpp::SSL_SYM_AES_256_GCM, + pcpp::SSL_SYM_CHACHA20_POLY1305, + pcpp::SSL_SYM_AES_128_GCM }; - pcpp::SSLHashingAlgorithm cipherSuiteHash[3] = - { - pcpp::SSL_HASH_SHA384, - pcpp::SSL_HASH_SHA256, - pcpp::SSL_HASH_SHA256 - }; + pcpp::SSLHashingAlgorithm cipherSuiteHash[3] = { pcpp::SSL_HASH_SHA384, pcpp::SSL_HASH_SHA256, + pcpp::SSL_HASH_SHA256 }; pcpp::SSLHandshakeLayer* handshakeLayer = tls13ClientHello1.getLayerOfType(); PTF_ASSERT_NOT_NULL(handshakeLayer); - pcpp::SSLClientHelloMessage* clientHelloMsg = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLClientHelloMessage* clientHelloMsg = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(clientHelloMsg); PTF_ASSERT_EQUAL(clientHelloMsg->getCipherSuiteCount(), 4); for (int i = 0; i < 3; i++) @@ -620,7 +575,8 @@ PTF_TEST_CASE(TLS1_3ParsingTest) PTF_ASSERT_EQUAL(clientHelloMsg->getCipherSuite(i)->getAuthAlg(), pcpp::SSL_AUTH_NULL, enum); } - pcpp::SSLSupportedVersionsExtension* supportedVersionsExt = clientHelloMsg->getExtensionOfType(); + pcpp::SSLSupportedVersionsExtension* supportedVersionsExt = + clientHelloMsg->getExtensionOfType(); PTF_ASSERT_NOT_NULL(supportedVersionsExt); std::vector versionVec = supportedVersionsExt->getSupportedVersions(); PTF_ASSERT_EQUAL(versionVec.size(), 3); @@ -629,7 +585,8 @@ PTF_TEST_CASE(TLS1_3ParsingTest) PTF_ASSERT_EQUAL(versionVec[2].asEnum(), pcpp::SSLVersion::TLS1_3_D26, enum); PTF_ASSERT_EQUAL(versionVec[0].asEnum(true), pcpp::SSLVersion::TLS1_3, enum); - pcpp::TLSECPointFormatExtension* ecPointFormatExt = clientHelloMsg->getExtensionOfType(); + pcpp::TLSECPointFormatExtension* ecPointFormatExt = + clientHelloMsg->getExtensionOfType(); PTF_ASSERT_NOT_NULL(ecPointFormatExt); std::vector ecPointFormatList = ecPointFormatExt->getECPointFormatList(); PTF_ASSERT_EQUAL(ecPointFormatList.size(), 3); @@ -637,7 +594,8 @@ PTF_TEST_CASE(TLS1_3ParsingTest) PTF_ASSERT_EQUAL(ecPointFormatList.at(1), 1); PTF_ASSERT_EQUAL(ecPointFormatList.at(2), 2); - pcpp::TLSSupportedGroupsExtension* supportedGroupsExt = clientHelloMsg->getExtensionOfType(); + pcpp::TLSSupportedGroupsExtension* supportedGroupsExt = + clientHelloMsg->getExtensionOfType(); PTF_ASSERT_NOT_NULL(supportedGroupsExt); std::vector supportedGroups = supportedGroupsExt->getSupportedGroups(); PTF_ASSERT_EQUAL(supportedGroups.size(), 5); @@ -647,7 +605,6 @@ PTF_TEST_CASE(TLS1_3ParsingTest) PTF_ASSERT_EQUAL(supportedGroups.at(3), 25); PTF_ASSERT_EQUAL(supportedGroups.at(4), 24); - handshakeLayer = tls13ClientHello2.getLayerOfType(); PTF_ASSERT_NOT_NULL(handshakeLayer); clientHelloMsg = handshakeLayer->getHandshakeMessageOfType(); @@ -665,7 +622,6 @@ PTF_TEST_CASE(TLS1_3ParsingTest) PTF_ASSERT_EQUAL(versionVec[0].asEnum(), pcpp::SSLVersion::TLS1_3, enum); PTF_ASSERT_EQUAL(versionVec[1].asEnum(), pcpp::SSLVersion::TLS1_2, enum); - READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/tls1_3_server_hello1.dat"); READ_FILE_AND_CREATE_PACKET(4, "PacketExamples/tls1_3_server_hello2.dat"); @@ -674,7 +630,8 @@ PTF_TEST_CASE(TLS1_3ParsingTest) handshakeLayer = tls13ServerHello1.getLayerOfType(); PTF_ASSERT_NOT_NULL(handshakeLayer); - pcpp::SSLServerHelloMessage* serverHelloMsg = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLServerHelloMessage* serverHelloMsg = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(serverHelloMsg); PTF_ASSERT_EQUAL(serverHelloMsg->getCipherSuite()->asString(), cipherSuiteNames[0]); @@ -686,7 +643,6 @@ PTF_TEST_CASE(TLS1_3ParsingTest) PTF_ASSERT_EQUAL(versionVec[0].asEnum(), pcpp::SSLVersion::TLS1_3_D28, enum); PTF_ASSERT_EQUAL(serverHelloMsg->getHandshakeVersion().asEnum(true), pcpp::SSLVersion::TLS1_3, enum); - handshakeLayer = tls13ServerHello2.getLayerOfType(); PTF_ASSERT_NOT_NULL(handshakeLayer); serverHelloMsg = handshakeLayer->getHandshakeMessageOfType(); @@ -700,8 +656,7 @@ PTF_TEST_CASE(TLS1_3ParsingTest) PTF_ASSERT_EQUAL(versionVec.size(), 1); PTF_ASSERT_EQUAL(versionVec[0].asEnum(), pcpp::SSLVersion::TLS1_3, enum); PTF_ASSERT_EQUAL(serverHelloMsg->getHandshakeVersion().asEnum(true), pcpp::SSLVersion::TLS1_3, enum); -} // TLS1_3ParsingTest - +} // TLS1_3ParsingTest PTF_TEST_CASE(TLSCipherSuiteTest) { @@ -724,8 +679,7 @@ PTF_TEST_CASE(TLSCipherSuiteTest) PTF_ASSERT_EQUAL(cipherSuiteByID->getID(), cipherSuiteID); PTF_ASSERT_EQUAL(cipherSuiteByName, cipherSuiteByID, ptr); } -} // TLSCipherSuiteTest - +} // TLSCipherSuiteTest PTF_TEST_CASE(ClientHelloTLSFingerprintTest) { @@ -737,14 +691,15 @@ PTF_TEST_CASE(ClientHelloTLSFingerprintTest) pcpp::SSLHandshakeLayer* handshakeLayer = tls13ClientHello1.getLayerOfType(); PTF_ASSERT_NOT_NULL(handshakeLayer); - pcpp::SSLClientHelloMessage* clientHelloMsg = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLClientHelloMessage* clientHelloMsg = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(clientHelloMsg); pcpp::SSLClientHelloMessage::ClientHelloTLSFingerprint tlsFingerprint = clientHelloMsg->generateTLSFingerprint(); - PTF_ASSERT_EQUAL(tlsFingerprint.toString(), "771,4866-4867-4865-255,0-11-10-35-22-23-13-43-45-51,29-23-30-25-24,0-1-2"); + PTF_ASSERT_EQUAL(tlsFingerprint.toString(), + "771,4866-4867-4865-255,0-11-10-35-22-23-13-43-45-51,29-23-30-25-24,0-1-2"); PTF_ASSERT_EQUAL(tlsFingerprint.toMD5(), "a66e498c488aa0523759691248cdfb01"); - READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/tls_grease.dat"); pcpp::Packet tlsGreaseClientHello(&rawPacket2); @@ -754,10 +709,11 @@ PTF_TEST_CASE(ClientHelloTLSFingerprintTest) PTF_ASSERT_NOT_NULL(clientHelloMsg); tlsFingerprint = clientHelloMsg->generateTLSFingerprint(); - PTF_ASSERT_EQUAL(tlsFingerprint.toString(), "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-21,29-23-24,0"); + PTF_ASSERT_EQUAL(tlsFingerprint.toString(), + "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-" + "11-35-16-5-13-18-51-45-43-27-21,29-23-24,0"); PTF_ASSERT_EQUAL(tlsFingerprint.toMD5(), "b32309a26951912be7dba376398abc3b"); -} // ClientHelloTLSFingerprintTest - +} // ClientHelloTLSFingerprintTest PTF_TEST_CASE(ServerHelloTLSFingerprintTest) { @@ -770,14 +726,15 @@ PTF_TEST_CASE(ServerHelloTLSFingerprintTest) pcpp::SSLHandshakeLayer* handshakeLayer = multipleRecordsPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(handshakeLayer); - pcpp::SSLServerHelloMessage* serverHelloMessage = handshakeLayer->getHandshakeMessageOfType(); + pcpp::SSLServerHelloMessage* serverHelloMessage = + handshakeLayer->getHandshakeMessageOfType(); PTF_ASSERT_NOT_NULL(serverHelloMessage); - pcpp::SSLServerHelloMessage::ServerHelloTLSFingerprint tlsFingerprint = serverHelloMessage->generateTLSFingerprint(); + pcpp::SSLServerHelloMessage::ServerHelloTLSFingerprint tlsFingerprint = + serverHelloMessage->generateTLSFingerprint(); PTF_ASSERT_EQUAL(tlsFingerprint.toString(), "771,49195,65281-16-11"); PTF_ASSERT_EQUAL(tlsFingerprint.toMD5(), "554786d4c84f8a7953b7e453c6371067"); - READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/tls_server_hello.dat"); pcpp::Packet serverHelloPacket(&rawPacket2); @@ -790,4 +747,4 @@ PTF_TEST_CASE(ServerHelloTLSFingerprintTest) tlsFingerprint = serverHelloMessage->generateTLSFingerprint(); PTF_ASSERT_EQUAL(tlsFingerprint.toString(), "771,49195,23-65281-11-35-16"); PTF_ASSERT_EQUAL(tlsFingerprint.toMD5(), "eca9b8f0f3eae50309eaf901cb822d9b"); -} // ServerHelloTLSFingerprintTest +} // ServerHelloTLSFingerprintTest diff --git a/Tests/Packet++Test/Tests/SipSdpTests.cpp b/Tests/Packet++Test/Tests/SipSdpTests.cpp index 27ba32a4b1..d8ed0ce3d8 100644 --- a/Tests/Packet++Test/Tests/SipSdpTests.cpp +++ b/Tests/Packet++Test/Tests/SipSdpTests.cpp @@ -10,42 +10,44 @@ #include "PayloadLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(SipRequestParseMethodTest) { - PTF_ASSERT_EQUAL(pcpp::SipRequestFirstLine::parseMethod(nullptr, 0), pcpp::SipRequestLayer::SipMethod::SipMethodUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::SipRequestFirstLine::parseMethod(std::string("ACK").c_str(), 3), pcpp::SipRequestLayer::SipMethod::SipMethodUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::SipRequestFirstLine::parseMethod(nullptr, 0), + pcpp::SipRequestLayer::SipMethod::SipMethodUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::SipRequestFirstLine::parseMethod(std::string("ACK").c_str(), 3), + pcpp::SipRequestLayer::SipMethod::SipMethodUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::SipRequestFirstLine::parseMethod(std::string("CANCEL").c_str(), 6), pcpp::SipRequestLayer::SipMethod::SipMethodUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::SipRequestFirstLine::parseMethod(std::string("CANCEL").c_str(), 6), + pcpp::SipRequestLayer::SipMethod::SipMethodUnknown, enum); std::vector> possibleMethods = { - {"INVITE", pcpp::SipRequestLayer::SipMethod::SipINVITE }, - {"ACK", pcpp::SipRequestLayer::SipMethod::SipACK }, - {"BYE", pcpp::SipRequestLayer::SipMethod::SipBYE }, - {"CANCEL", pcpp::SipRequestLayer::SipMethod::SipCANCEL }, - {"REGISTER", pcpp::SipRequestLayer::SipMethod::SipREGISTER }, - {"PRACK", pcpp::SipRequestLayer::SipMethod::SipPRACK }, - {"OPTIONS", pcpp::SipRequestLayer::SipMethod::SipOPTIONS }, - {"SUBSCRIBE", pcpp::SipRequestLayer::SipMethod::SipSUBSCRIBE }, - {"NOTIFY", pcpp::SipRequestLayer::SipMethod::SipNOTIFY }, - {"PUBLISH", pcpp::SipRequestLayer::SipMethod::SipPUBLISH }, - {"INFO", pcpp::SipRequestLayer::SipMethod::SipINFO }, - {"REFER", pcpp::SipRequestLayer::SipMethod::SipREFER }, - {"MESSAGE", pcpp::SipRequestLayer::SipMethod::SipMESSAGE }, - {"UPDATE", pcpp::SipRequestLayer::SipMethod::SipUPDATE }, - {"UPDATE", pcpp::SipRequestLayer::SipMethod::SipUPDATE }, + { "INVITE", pcpp::SipRequestLayer::SipMethod::SipINVITE }, + { "ACK", pcpp::SipRequestLayer::SipMethod::SipACK }, + { "BYE", pcpp::SipRequestLayer::SipMethod::SipBYE }, + { "CANCEL", pcpp::SipRequestLayer::SipMethod::SipCANCEL }, + { "REGISTER", pcpp::SipRequestLayer::SipMethod::SipREGISTER }, + { "PRACK", pcpp::SipRequestLayer::SipMethod::SipPRACK }, + { "OPTIONS", pcpp::SipRequestLayer::SipMethod::SipOPTIONS }, + { "SUBSCRIBE", pcpp::SipRequestLayer::SipMethod::SipSUBSCRIBE }, + { "NOTIFY", pcpp::SipRequestLayer::SipMethod::SipNOTIFY }, + { "PUBLISH", pcpp::SipRequestLayer::SipMethod::SipPUBLISH }, + { "INFO", pcpp::SipRequestLayer::SipMethod::SipINFO }, + { "REFER", pcpp::SipRequestLayer::SipMethod::SipREFER }, + { "MESSAGE", pcpp::SipRequestLayer::SipMethod::SipMESSAGE }, + { "UPDATE", pcpp::SipRequestLayer::SipMethod::SipUPDATE }, + { "UPDATE", pcpp::SipRequestLayer::SipMethod::SipUPDATE }, }; - for (const std::pair &method : possibleMethods ) + for (const std::pair& method : possibleMethods) { std::string firstLine = method.first + " "; - PTF_ASSERT_EQUAL(pcpp::SipRequestFirstLine::parseMethod(firstLine.c_str(), firstLine.length()), method.second, enum); + PTF_ASSERT_EQUAL(pcpp::SipRequestFirstLine::parseMethod(firstLine.c_str(), firstLine.length()), method.second, + enum); } - PTF_ASSERT_EQUAL(pcpp::SipRequestFirstLine::parseMethod(std::string("UNKNOWN ").c_str(), 8), pcpp::SipRequestLayer::SipMethod::SipMethodUnknown, enum); -} // SipRequestParseMethodTest - - + PTF_ASSERT_EQUAL(pcpp::SipRequestFirstLine::parseMethod(std::string("UNKNOWN ").c_str(), 8), + pcpp::SipRequestLayer::SipMethod::SipMethodUnknown, enum); +} // SipRequestParseMethodTest PTF_TEST_CASE(SipRequestLayerParsingTest) { @@ -82,14 +84,17 @@ PTF_TEST_CASE(SipRequestLayerParsingTest) PTF_ASSERT_EQUAL(sipReqLayer->getFirstLine()->getSize(), 47); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_FROM_FIELD)); - PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_FROM_FIELD)->getFieldValue(), ";tag=GR52RWG346-34"); + PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_FROM_FIELD)->getFieldValue(), + ";tag=GR52RWG346-34"); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_CONTACT_FIELD)); PTF_ASSERT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_CONTACT_FIELD, 1)); PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_CONTACT_FIELD)->getFieldValue(), ""); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD)); - PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD)->getFieldValue(), "SIP/2.0/UDP 200.57.7.195;branch=z9hG4bKff9b46fb055c0521cc24024da96cd290"); + PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD)->getFieldValue(), + "SIP/2.0/UDP 200.57.7.195;branch=z9hG4bKff9b46fb055c0521cc24024da96cd290"); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD, 1)); - PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD, 1)->getFieldValue(), "SIP/2.0/UDP 200.57.7.195:55061;branch=z9hG4bK291d90e31a47b225bd0ddff4353e9cc0"); + PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD, 1)->getFieldValue(), + "SIP/2.0/UDP 200.57.7.195:55061;branch=z9hG4bK291d90e31a47b225bd0ddff4353e9cc0"); PTF_ASSERT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD, 2)); PTF_ASSERT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD, 100)); PTF_ASSERT_NULL(sipReqLayer->getFieldByName("BlaBla")); @@ -101,7 +106,6 @@ PTF_TEST_CASE(SipRequestLayerParsingTest) PTF_ASSERT_EQUAL(sipReqLayer->getLayerPayloadSize(), 229); PTF_ASSERT_EQUAL(sipReqLayer->getContentLength(), 229); - sipReqLayer = sipReqPacket2.getLayerOfType(); PTF_ASSERT_EQUAL(sipReqLayer->getFirstLine()->getMethod(), pcpp::SipRequestLayer::SipCANCEL, enum); @@ -110,7 +114,8 @@ PTF_TEST_CASE(SipRequestLayerParsingTest) PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_MAX_FORWARDS_FIELD)); PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_MAX_FORWARDS_FIELD)->getFieldValue(), "70"); - PTF_ASSERT_TRUE(sipReqLayer->getNextField(sipReqLayer->getFieldByName(PCPP_SIP_MAX_FORWARDS_FIELD))->isEndOfHeader()); + PTF_ASSERT_TRUE( + sipReqLayer->getNextField(sipReqLayer->getFieldByName(PCPP_SIP_MAX_FORWARDS_FIELD))->isEndOfHeader()); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_CSEQ_FIELD)); PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_CSEQ_FIELD)->getFieldValue(), "2 CANCEL"); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_TO_FIELD)); @@ -118,7 +123,6 @@ PTF_TEST_CASE(SipRequestLayerParsingTest) PTF_ASSERT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_TO_FIELD, 2)); PTF_ASSERT_TRUE(sipReqLayer->isHeaderComplete()); - sipReqLayer = sipReqPacket3.getLayerOfType(); PTF_ASSERT_EQUAL(sipReqLayer->getFirstLine()->getMethod(), pcpp::SipRequestLayer::SipACK, enum); @@ -127,16 +131,17 @@ PTF_TEST_CASE(SipRequestLayerParsingTest) PTF_ASSERT_FALSE(sipReqLayer->isHeaderComplete()); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD, 1)); - PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD, 1)->getFieldValue(), "SIP/2.0/UDP 213.192.59.78:5080;rport=5080;branch=z9hG4bKjBiNGaOX"); + PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD, 1)->getFieldValue(), + "SIP/2.0/UDP 213.192.59.78:5080;rport=5080;branch=z9hG4bKjBiNGaOX"); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_CALL_ID_FIELD)); - PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_CALL_ID_FIELD)->getFieldValue(), "2091060b-146f-e011-809a-0019cb53db77@admind-desktop"); + PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_CALL_ID_FIELD)->getFieldValue(), + "2091060b-146f-e011-809a-0019cb53db77@admind-desktop"); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName("P-hint")); PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName("P-hint")->getFieldValue(), "rr-enforced"); PTF_ASSERT_NULL(sipReqLayer->getNextField(sipReqLayer->getFieldByName("P-hint"))); PTF_ASSERT_EQUAL(sipReqLayer->getContentLength(), 0); PTF_ASSERT_EQUAL(sipReqLayer->getFieldCount(), 9); - sipReqLayer = sipReqPacket4.getLayerOfType(); PTF_ASSERT_EQUAL(sipReqLayer->getFirstLine()->getMethod(), pcpp::SipRequestLayer::SipBYE, enum); @@ -145,16 +150,18 @@ PTF_TEST_CASE(SipRequestLayerParsingTest) PTF_ASSERT_FALSE(sipReqLayer->isHeaderComplete()); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_USER_AGENT_FIELD)); - PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_USER_AGENT_FIELD)->getFieldValue(), "FreeSWITCH-mod_sofia/1.6.12-20-b91a0a6~64bit"); + PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_USER_AGENT_FIELD)->getFieldValue(), + "FreeSWITCH-mod_sofia/1.6.12-20-b91a0a6~64bit"); PTF_ASSERT_NOT_NULL(sipReqLayer->getFieldByName(PCPP_SIP_REASON_FIELD)); - PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_REASON_FIELD)->getFieldValue(), "Q.850;cause=16;text=\"NORMAL_CLEARING\""); - PTF_ASSERT_EQUAL(sipReqLayer->getNextField(sipReqLayer->getFieldByName(PCPP_SIP_REASON_FIELD))->getFieldName(), "Content-Lengt"); - PTF_ASSERT_EQUAL(sipReqLayer->getNextField(sipReqLayer->getFieldByName(PCPP_SIP_REASON_FIELD))->getFieldValue(), ""); + PTF_ASSERT_EQUAL(sipReqLayer->getFieldByName(PCPP_SIP_REASON_FIELD)->getFieldValue(), + "Q.850;cause=16;text=\"NORMAL_CLEARING\""); + PTF_ASSERT_EQUAL(sipReqLayer->getNextField(sipReqLayer->getFieldByName(PCPP_SIP_REASON_FIELD))->getFieldName(), + "Content-Lengt"); + PTF_ASSERT_EQUAL(sipReqLayer->getNextField(sipReqLayer->getFieldByName(PCPP_SIP_REASON_FIELD))->getFieldValue(), + ""); PTF_ASSERT_EQUAL(sipReqLayer->getFieldCount(), 11); -} // SipRequestLayerParsingTest - - +} // SipRequestLayerParsingTest PTF_TEST_CASE(SipRequestLayerCreationTest) { @@ -175,8 +182,10 @@ PTF_TEST_CASE(SipRequestLayerCreationTest) PTF_ASSERT_NOT_NULL(sipReqLayer.addField(PCPP_SIP_CALL_ID_FIELD, "12013223@200.57.7.195")); PTF_ASSERT_NOT_NULL(sipReqLayer.addField(PCPP_SIP_CONTENT_TYPE_FIELD, "application/sdp")); PTF_ASSERT_TRUE(sipReqLayer.addEndOfHeader()); - PTF_ASSERT_NOT_NULL(sipReqLayer.insertField(nullptr, PCPP_SIP_VIA_FIELD, "SIP/2.0/UDP 200.57.7.195:55061;branch=z9hG4bK291d90e31a47b225bd0ddff4353e9cc0")); - PTF_ASSERT_NOT_NULL(sipReqLayer.insertField(nullptr, PCPP_SIP_VIA_FIELD, "SIP/2.0/UDP 200.57.7.195;branch=z9hG4bKff9b46fb055c0521cc24024da96cd290")); + PTF_ASSERT_NOT_NULL(sipReqLayer.insertField( + nullptr, PCPP_SIP_VIA_FIELD, "SIP/2.0/UDP 200.57.7.195:55061;branch=z9hG4bK291d90e31a47b225bd0ddff4353e9cc0")); + PTF_ASSERT_NOT_NULL(sipReqLayer.insertField( + nullptr, PCPP_SIP_VIA_FIELD, "SIP/2.0/UDP 200.57.7.195;branch=z9hG4bKff9b46fb055c0521cc24024da96cd290")); pcpp::HeaderField* callIDField = sipReqLayer.getFieldByName(PCPP_SIP_CALL_ID_FIELD); PTF_ASSERT_NOT_NULL(callIDField); pcpp::HeaderField* newField = sipReqLayer.insertField(callIDField, PCPP_SIP_CSEQ_FIELD, "1 INVITE"); @@ -185,15 +194,16 @@ PTF_TEST_CASE(SipRequestLayerCreationTest) PTF_ASSERT_NOT_NULL(newField); pcpp::HeaderField* secondViaField = sipReqLayer.getFieldByName(PCPP_SIP_VIA_FIELD, 0); PTF_ASSERT_NOT_NULL(secondViaField); - newField = sipReqLayer.insertField(secondViaField, PCPP_SIP_FROM_FIELD, ";tag=GR52RWG346-34"); + newField = sipReqLayer.insertField(secondViaField, PCPP_SIP_FROM_FIELD, + ";tag=GR52RWG346-34"); PTF_ASSERT_NOT_NULL(newField); - newField = sipReqLayer.insertField(newField, PCPP_SIP_TO_FIELD, "\"francisco@bestel.com\" "); + newField = sipReqLayer.insertField(newField, PCPP_SIP_TO_FIELD, + "\"francisco@bestel.com\" "); PTF_ASSERT_NOT_NULL(newField); pcpp::HeaderField* contentLengthField = sipReqLayer.setContentLength(229, PCPP_SIP_CONTENT_TYPE_FIELD); PTF_ASSERT_NOT_NULL(contentLengthField); contentLengthField->setFieldValue(" 229"); - pcpp::Packet newSipPacket; PTF_ASSERT_TRUE(newSipPacket.addLayer(ðLayer)); PTF_ASSERT_TRUE(newSipPacket.addLayer(&ip4Layer)); @@ -201,16 +211,16 @@ PTF_TEST_CASE(SipRequestLayerCreationTest) PTF_ASSERT_TRUE(newSipPacket.addLayer(&sipReqLayer)); pcpp::SipRequestLayer* samplePacketSipLayer = sipReqSamplePacket.getLayerOfType(); - auto payloadLayer = new pcpp::PayloadLayer(samplePacketSipLayer->getLayerPayload(), samplePacketSipLayer->getLayerPayloadSize()); + auto payloadLayer = + new pcpp::PayloadLayer(samplePacketSipLayer->getLayerPayload(), samplePacketSipLayer->getLayerPayloadSize()); PTF_ASSERT_TRUE(newSipPacket.addLayer(payloadLayer, true)); newSipPacket.computeCalculateFields(); PTF_ASSERT_EQUAL(newSipPacket.getRawPacket()->getRawDataLen(), bufferLength1); - PTF_ASSERT_BUF_COMPARE(newSipPacket.getRawPacket()->getRawData(), buffer1, newSipPacket.getRawPacket()->getRawDataLen()); -} // SipRequestLayerCreationTest - - + PTF_ASSERT_BUF_COMPARE(newSipPacket.getRawPacket()->getRawData(), buffer1, + newSipPacket.getRawPacket()->getRawDataLen()); +} // SipRequestLayerCreationTest PTF_TEST_CASE(SipRequestLayerEditTest) { @@ -238,7 +248,9 @@ PTF_TEST_CASE(SipRequestLayerEditTest) PTF_ASSERT_FALSE(sipReqLayer->getFirstLine()->setUri("")); pcpp::Logger::getInstance().enableLogs(); - PTF_ASSERT_TRUE(sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD, 1)->setFieldValue("SIP/2.0/UDP 178.45.73.241:5060;branch=z9hG4bKb26f2c0b-146f-e011-809a-0019cb53db77;rport")); + PTF_ASSERT_TRUE( + sipReqLayer->getFieldByName(PCPP_SIP_VIA_FIELD, 1) + ->setFieldValue("SIP/2.0/UDP 178.45.73.241:5060;branch=z9hG4bKb26f2c0b-146f-e011-809a-0019cb53db77;rport")); PTF_ASSERT_TRUE(sipReqLayer->getFieldByName(PCPP_SIP_MAX_FORWARDS_FIELD)->setFieldValue("70")); PTF_ASSERT_TRUE(sipReqLayer->removeField(PCPP_SIP_VIA_FIELD, 0)); PTF_ASSERT_TRUE(sipReqLayer->removeField(PCPP_SIP_RECORD_ROUTE_FIELD)); @@ -247,9 +259,12 @@ PTF_TEST_CASE(SipRequestLayerEditTest) PTF_ASSERT_NOT_NULL(sipReqLayer->setContentLength(0, PCPP_SIP_TO_FIELD)); PTF_ASSERT_TRUE(sipReqLayer->removeField(PCPP_SIP_CALL_ID_FIELD)); PTF_ASSERT_TRUE(sipReqLayer->removeField(PCPP_SIP_CSEQ_FIELD)); - PTF_ASSERT_NOT_NULL(sipReqLayer->insertField(PCPP_SIP_FROM_FIELD, PCPP_SIP_CALL_ID_FIELD, "2091060b-146f-e011-809a-0019cb53db77@admind-desktop")); + PTF_ASSERT_NOT_NULL(sipReqLayer->insertField(PCPP_SIP_FROM_FIELD, PCPP_SIP_CALL_ID_FIELD, + "2091060b-146f-e011-809a-0019cb53db77@admind-desktop")); PTF_ASSERT_NOT_NULL(sipReqLayer->insertField("", PCPP_SIP_CSEQ_FIELD, "2 CANCEL")); - PTF_ASSERT_TRUE(sipReqLayer->getFieldByName(PCPP_SIP_FROM_FIELD)->setFieldValue("\"sam netmon \" ;tag=bc86060b-146f-e011-809a-0019cb53db77")); + PTF_ASSERT_TRUE( + sipReqLayer->getFieldByName(PCPP_SIP_FROM_FIELD) + ->setFieldValue("\"sam netmon \" ;tag=bc86060b-146f-e011-809a-0019cb53db77")); PTF_ASSERT_TRUE(sipReqLayer->getFieldByName(PCPP_SIP_TO_FIELD)->setFieldValue("")); editedPacket.computeCalculateFields(); @@ -264,106 +279,107 @@ PTF_TEST_CASE(SipRequestLayerEditTest) PTF_ASSERT_EQUAL(secondSipReqLayer->getFirstLine()->getVersion(), sipReqLayer->getFirstLine()->getVersion()); PTF_ASSERT_EQUAL(secondSipReqLayer->getFieldCount(), sipReqLayer->getFieldCount()); PTF_ASSERT_BUF_COMPARE(secondSipReqLayer->getData(), sipReqLayer->getData(), secondSipReqLayer->getHeaderLen()); -} // SipRequestLayerEditTest - - +} // SipRequestLayerEditTest PTF_TEST_CASE(SipResponseParseStatusCodeTest) { - PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseStatusCode(nullptr, 0), pcpp::SipResponseLayer::SipResponseStatusCode::SipStatusCodeUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseStatusCode(std::string("abc").c_str(), 3), pcpp::SipResponseLayer::SipResponseStatusCode::SipStatusCodeUnknown, enum); - PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseStatusCode(std::string("SIP/x.y200 ").c_str(), 12), pcpp::SipResponseLayer::SipResponseStatusCode::SipStatusCodeUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseStatusCode(nullptr, 0), + pcpp::SipResponseLayer::SipResponseStatusCode::SipStatusCodeUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseStatusCode(std::string("abc").c_str(), 3), + pcpp::SipResponseLayer::SipResponseStatusCode::SipStatusCodeUnknown, enum); + PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseStatusCode(std::string("SIP/x.y200 ").c_str(), 12), + pcpp::SipResponseLayer::SipResponseStatusCode::SipStatusCodeUnknown, enum); std::vector> possibleStatusCodes = { - {"100", pcpp::SipResponseLayer::SipResponseStatusCode::Sip100Trying }, - {"180", pcpp::SipResponseLayer::SipResponseStatusCode::Sip180Ringing }, - {"181", pcpp::SipResponseLayer::SipResponseStatusCode::Sip181CallisBeingForwarded }, - {"182", pcpp::SipResponseLayer::SipResponseStatusCode::Sip182Queued }, - {"183", pcpp::SipResponseLayer::SipResponseStatusCode::Sip183SessioninProgress }, - {"199", pcpp::SipResponseLayer::SipResponseStatusCode::Sip199EarlyDialogTerminated }, - {"200", pcpp::SipResponseLayer::SipResponseStatusCode::Sip200OK }, - {"202", pcpp::SipResponseLayer::SipResponseStatusCode::Sip202Accepted }, - {"204", pcpp::SipResponseLayer::SipResponseStatusCode::Sip204NoNotification }, - {"300", pcpp::SipResponseLayer::SipResponseStatusCode::Sip300MultipleChoices }, - {"301", pcpp::SipResponseLayer::SipResponseStatusCode::Sip301MovedPermanently }, - {"302", pcpp::SipResponseLayer::SipResponseStatusCode::Sip302MovedTemporarily }, - {"305", pcpp::SipResponseLayer::SipResponseStatusCode::Sip305UseProxy }, - {"380", pcpp::SipResponseLayer::SipResponseStatusCode::Sip380AlternativeService }, - {"400", pcpp::SipResponseLayer::SipResponseStatusCode::Sip400BadRequest }, - {"401", pcpp::SipResponseLayer::SipResponseStatusCode::Sip401Unauthorized }, - {"402", pcpp::SipResponseLayer::SipResponseStatusCode::Sip402PaymentRequired }, - {"403", pcpp::SipResponseLayer::SipResponseStatusCode::Sip403Forbidden }, - {"404", pcpp::SipResponseLayer::SipResponseStatusCode::Sip404NotFound }, - {"405", pcpp::SipResponseLayer::SipResponseStatusCode::Sip405MethodNotAllowed }, - {"406", pcpp::SipResponseLayer::SipResponseStatusCode::Sip406NotAcceptable }, - {"407", pcpp::SipResponseLayer::SipResponseStatusCode::Sip407ProxyAuthenticationRequired }, - {"408", pcpp::SipResponseLayer::SipResponseStatusCode::Sip408RequestTimeout }, - {"409", pcpp::SipResponseLayer::SipResponseStatusCode::Sip409Conflict }, - {"410", pcpp::SipResponseLayer::SipResponseStatusCode::Sip410Gone }, - {"411", pcpp::SipResponseLayer::SipResponseStatusCode::Sip411LengthRequired }, - {"412", pcpp::SipResponseLayer::SipResponseStatusCode::Sip412ConditionalRequestFailed }, - {"413", pcpp::SipResponseLayer::SipResponseStatusCode::Sip413RequestEntityTooLarge }, - {"414", pcpp::SipResponseLayer::SipResponseStatusCode::Sip414RequestURITooLong }, - {"415", pcpp::SipResponseLayer::SipResponseStatusCode::Sip415UnsupportedMediaType }, - {"416", pcpp::SipResponseLayer::SipResponseStatusCode::Sip416UnsupportedURIScheme }, - {"417", pcpp::SipResponseLayer::SipResponseStatusCode::Sip417UnknownResourcePriority }, - {"420", pcpp::SipResponseLayer::SipResponseStatusCode::Sip420BadExtension }, - {"421", pcpp::SipResponseLayer::SipResponseStatusCode::Sip421ExtensionRequired }, - {"422", pcpp::SipResponseLayer::SipResponseStatusCode::Sip422SessionIntervalTooSmall }, - {"423", pcpp::SipResponseLayer::SipResponseStatusCode::Sip423IntervalTooBrief }, - {"424", pcpp::SipResponseLayer::SipResponseStatusCode::Sip424BadLocationInformation }, - {"425", pcpp::SipResponseLayer::SipResponseStatusCode::Sip425BadAlertMessage }, - {"428", pcpp::SipResponseLayer::SipResponseStatusCode::Sip428UseIdentityHeader }, - {"429", pcpp::SipResponseLayer::SipResponseStatusCode::Sip429ProvideReferrerIdentity }, - {"430", pcpp::SipResponseLayer::SipResponseStatusCode::Sip430FlowFailed }, - {"433", pcpp::SipResponseLayer::SipResponseStatusCode::Sip433AnonymityDisallowed }, - {"436", pcpp::SipResponseLayer::SipResponseStatusCode::Sip436BadIdentityInfo }, - {"437", pcpp::SipResponseLayer::SipResponseStatusCode::Sip437UnsupportedCertificate }, - {"438", pcpp::SipResponseLayer::SipResponseStatusCode::Sip438InvalidIdentityHeader }, - {"439", pcpp::SipResponseLayer::SipResponseStatusCode::Sip439FirstHopLacksOutboundSupport }, - {"440", pcpp::SipResponseLayer::SipResponseStatusCode::Sip440MaxBreadthExceeded }, - {"469", pcpp::SipResponseLayer::SipResponseStatusCode::Sip469BadInfoPackage }, - {"470", pcpp::SipResponseLayer::SipResponseStatusCode::Sip470ConsentNeeded }, - {"480", pcpp::SipResponseLayer::SipResponseStatusCode::Sip480TemporarilyUnavailable }, - {"481", pcpp::SipResponseLayer::SipResponseStatusCode::Sip481Call_TransactionDoesNotExist }, - {"482", pcpp::SipResponseLayer::SipResponseStatusCode::Sip482LoopDetected }, - {"483", pcpp::SipResponseLayer::SipResponseStatusCode::Sip483TooManyHops }, - {"484", pcpp::SipResponseLayer::SipResponseStatusCode::Sip484AddressIncomplete }, - {"485", pcpp::SipResponseLayer::SipResponseStatusCode::Sip485Ambiguous }, - {"486", pcpp::SipResponseLayer::SipResponseStatusCode::Sip486BusyHere }, - {"487", pcpp::SipResponseLayer::SipResponseStatusCode::Sip487RequestTerminated }, - {"488", pcpp::SipResponseLayer::SipResponseStatusCode::Sip488NotAcceptableHere }, - {"489", pcpp::SipResponseLayer::SipResponseStatusCode::Sip489BadEvent }, - {"491", pcpp::SipResponseLayer::SipResponseStatusCode::Sip491RequestPending }, - {"493", pcpp::SipResponseLayer::SipResponseStatusCode::Sip493Undecipherable }, - {"494", pcpp::SipResponseLayer::SipResponseStatusCode::Sip494SecurityAgreementRequired }, - {"500", pcpp::SipResponseLayer::SipResponseStatusCode::Sip500ServerInternalError }, - {"501", pcpp::SipResponseLayer::SipResponseStatusCode::Sip501NotImplemented }, - {"502", pcpp::SipResponseLayer::SipResponseStatusCode::Sip502BadGateway }, - {"503", pcpp::SipResponseLayer::SipResponseStatusCode::Sip503ServiceUnavailable }, - {"504", pcpp::SipResponseLayer::SipResponseStatusCode::Sip504ServerTimeout }, - {"505", pcpp::SipResponseLayer::SipResponseStatusCode::Sip505VersionNotSupported }, - {"513", pcpp::SipResponseLayer::SipResponseStatusCode::Sip513MessageTooLarge }, - {"555", pcpp::SipResponseLayer::SipResponseStatusCode::Sip555PushNotificationServiceNotSupported }, - {"580", pcpp::SipResponseLayer::SipResponseStatusCode::Sip580PreconditionFailure }, - {"600", pcpp::SipResponseLayer::SipResponseStatusCode::Sip600BusyEverywhere }, - {"603", pcpp::SipResponseLayer::SipResponseStatusCode::Sip603Decline }, - {"604", pcpp::SipResponseLayer::SipResponseStatusCode::Sip604DoesNotExistAnywhere }, - {"606", pcpp::SipResponseLayer::SipResponseStatusCode::Sip606NotAcceptable }, - {"607", pcpp::SipResponseLayer::SipResponseStatusCode::Sip607Unwanted }, - {"608", pcpp::SipResponseLayer::SipResponseStatusCode::Sip608Rejected } + { "100", pcpp::SipResponseLayer::SipResponseStatusCode::Sip100Trying }, + { "180", pcpp::SipResponseLayer::SipResponseStatusCode::Sip180Ringing }, + { "181", pcpp::SipResponseLayer::SipResponseStatusCode::Sip181CallisBeingForwarded }, + { "182", pcpp::SipResponseLayer::SipResponseStatusCode::Sip182Queued }, + { "183", pcpp::SipResponseLayer::SipResponseStatusCode::Sip183SessioninProgress }, + { "199", pcpp::SipResponseLayer::SipResponseStatusCode::Sip199EarlyDialogTerminated }, + { "200", pcpp::SipResponseLayer::SipResponseStatusCode::Sip200OK }, + { "202", pcpp::SipResponseLayer::SipResponseStatusCode::Sip202Accepted }, + { "204", pcpp::SipResponseLayer::SipResponseStatusCode::Sip204NoNotification }, + { "300", pcpp::SipResponseLayer::SipResponseStatusCode::Sip300MultipleChoices }, + { "301", pcpp::SipResponseLayer::SipResponseStatusCode::Sip301MovedPermanently }, + { "302", pcpp::SipResponseLayer::SipResponseStatusCode::Sip302MovedTemporarily }, + { "305", pcpp::SipResponseLayer::SipResponseStatusCode::Sip305UseProxy }, + { "380", pcpp::SipResponseLayer::SipResponseStatusCode::Sip380AlternativeService }, + { "400", pcpp::SipResponseLayer::SipResponseStatusCode::Sip400BadRequest }, + { "401", pcpp::SipResponseLayer::SipResponseStatusCode::Sip401Unauthorized }, + { "402", pcpp::SipResponseLayer::SipResponseStatusCode::Sip402PaymentRequired }, + { "403", pcpp::SipResponseLayer::SipResponseStatusCode::Sip403Forbidden }, + { "404", pcpp::SipResponseLayer::SipResponseStatusCode::Sip404NotFound }, + { "405", pcpp::SipResponseLayer::SipResponseStatusCode::Sip405MethodNotAllowed }, + { "406", pcpp::SipResponseLayer::SipResponseStatusCode::Sip406NotAcceptable }, + { "407", pcpp::SipResponseLayer::SipResponseStatusCode::Sip407ProxyAuthenticationRequired }, + { "408", pcpp::SipResponseLayer::SipResponseStatusCode::Sip408RequestTimeout }, + { "409", pcpp::SipResponseLayer::SipResponseStatusCode::Sip409Conflict }, + { "410", pcpp::SipResponseLayer::SipResponseStatusCode::Sip410Gone }, + { "411", pcpp::SipResponseLayer::SipResponseStatusCode::Sip411LengthRequired }, + { "412", pcpp::SipResponseLayer::SipResponseStatusCode::Sip412ConditionalRequestFailed }, + { "413", pcpp::SipResponseLayer::SipResponseStatusCode::Sip413RequestEntityTooLarge }, + { "414", pcpp::SipResponseLayer::SipResponseStatusCode::Sip414RequestURITooLong }, + { "415", pcpp::SipResponseLayer::SipResponseStatusCode::Sip415UnsupportedMediaType }, + { "416", pcpp::SipResponseLayer::SipResponseStatusCode::Sip416UnsupportedURIScheme }, + { "417", pcpp::SipResponseLayer::SipResponseStatusCode::Sip417UnknownResourcePriority }, + { "420", pcpp::SipResponseLayer::SipResponseStatusCode::Sip420BadExtension }, + { "421", pcpp::SipResponseLayer::SipResponseStatusCode::Sip421ExtensionRequired }, + { "422", pcpp::SipResponseLayer::SipResponseStatusCode::Sip422SessionIntervalTooSmall }, + { "423", pcpp::SipResponseLayer::SipResponseStatusCode::Sip423IntervalTooBrief }, + { "424", pcpp::SipResponseLayer::SipResponseStatusCode::Sip424BadLocationInformation }, + { "425", pcpp::SipResponseLayer::SipResponseStatusCode::Sip425BadAlertMessage }, + { "428", pcpp::SipResponseLayer::SipResponseStatusCode::Sip428UseIdentityHeader }, + { "429", pcpp::SipResponseLayer::SipResponseStatusCode::Sip429ProvideReferrerIdentity }, + { "430", pcpp::SipResponseLayer::SipResponseStatusCode::Sip430FlowFailed }, + { "433", pcpp::SipResponseLayer::SipResponseStatusCode::Sip433AnonymityDisallowed }, + { "436", pcpp::SipResponseLayer::SipResponseStatusCode::Sip436BadIdentityInfo }, + { "437", pcpp::SipResponseLayer::SipResponseStatusCode::Sip437UnsupportedCertificate }, + { "438", pcpp::SipResponseLayer::SipResponseStatusCode::Sip438InvalidIdentityHeader }, + { "439", pcpp::SipResponseLayer::SipResponseStatusCode::Sip439FirstHopLacksOutboundSupport }, + { "440", pcpp::SipResponseLayer::SipResponseStatusCode::Sip440MaxBreadthExceeded }, + { "469", pcpp::SipResponseLayer::SipResponseStatusCode::Sip469BadInfoPackage }, + { "470", pcpp::SipResponseLayer::SipResponseStatusCode::Sip470ConsentNeeded }, + { "480", pcpp::SipResponseLayer::SipResponseStatusCode::Sip480TemporarilyUnavailable }, + { "481", pcpp::SipResponseLayer::SipResponseStatusCode::Sip481Call_TransactionDoesNotExist }, + { "482", pcpp::SipResponseLayer::SipResponseStatusCode::Sip482LoopDetected }, + { "483", pcpp::SipResponseLayer::SipResponseStatusCode::Sip483TooManyHops }, + { "484", pcpp::SipResponseLayer::SipResponseStatusCode::Sip484AddressIncomplete }, + { "485", pcpp::SipResponseLayer::SipResponseStatusCode::Sip485Ambiguous }, + { "486", pcpp::SipResponseLayer::SipResponseStatusCode::Sip486BusyHere }, + { "487", pcpp::SipResponseLayer::SipResponseStatusCode::Sip487RequestTerminated }, + { "488", pcpp::SipResponseLayer::SipResponseStatusCode::Sip488NotAcceptableHere }, + { "489", pcpp::SipResponseLayer::SipResponseStatusCode::Sip489BadEvent }, + { "491", pcpp::SipResponseLayer::SipResponseStatusCode::Sip491RequestPending }, + { "493", pcpp::SipResponseLayer::SipResponseStatusCode::Sip493Undecipherable }, + { "494", pcpp::SipResponseLayer::SipResponseStatusCode::Sip494SecurityAgreementRequired }, + { "500", pcpp::SipResponseLayer::SipResponseStatusCode::Sip500ServerInternalError }, + { "501", pcpp::SipResponseLayer::SipResponseStatusCode::Sip501NotImplemented }, + { "502", pcpp::SipResponseLayer::SipResponseStatusCode::Sip502BadGateway }, + { "503", pcpp::SipResponseLayer::SipResponseStatusCode::Sip503ServiceUnavailable }, + { "504", pcpp::SipResponseLayer::SipResponseStatusCode::Sip504ServerTimeout }, + { "505", pcpp::SipResponseLayer::SipResponseStatusCode::Sip505VersionNotSupported }, + { "513", pcpp::SipResponseLayer::SipResponseStatusCode::Sip513MessageTooLarge }, + { "555", pcpp::SipResponseLayer::SipResponseStatusCode::Sip555PushNotificationServiceNotSupported }, + { "580", pcpp::SipResponseLayer::SipResponseStatusCode::Sip580PreconditionFailure }, + { "600", pcpp::SipResponseLayer::SipResponseStatusCode::Sip600BusyEverywhere }, + { "603", pcpp::SipResponseLayer::SipResponseStatusCode::Sip603Decline }, + { "604", pcpp::SipResponseLayer::SipResponseStatusCode::Sip604DoesNotExistAnywhere }, + { "606", pcpp::SipResponseLayer::SipResponseStatusCode::Sip606NotAcceptable }, + { "607", pcpp::SipResponseLayer::SipResponseStatusCode::Sip607Unwanted }, + { "608", pcpp::SipResponseLayer::SipResponseStatusCode::Sip608Rejected } }; - for (const std::pair &statusCode : possibleStatusCodes ) + for (const std::pair& statusCode : possibleStatusCodes) { std::string firstLine = "SIP/x.y " + statusCode.first + " "; - PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseStatusCode(firstLine.c_str(), firstLine.length()), statusCode.second, enum); + PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseStatusCode(firstLine.c_str(), firstLine.length()), + statusCode.second, enum); } - PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseStatusCode(std::string("SIP/x.y 999 ").c_str(), 12), pcpp::SipResponseLayer::SipResponseStatusCode::SipStatusCodeUnknown, enum); -} // SipResponseParseStatusCodeTest - - + PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseStatusCode(std::string("SIP/x.y 999 ").c_str(), 12), + pcpp::SipResponseLayer::SipResponseStatusCode::SipStatusCodeUnknown, enum); +} // SipResponseParseStatusCodeTest PTF_TEST_CASE(SipResponseParseVersionCodeTest) { @@ -378,9 +394,7 @@ PTF_TEST_CASE(SipResponseParseVersionCodeTest) PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseVersion(std::string("SIP/2.01").c_str(), 8), ""); PTF_ASSERT_EQUAL(pcpp::SipResponseFirstLine::parseVersion(std::string("SIP/2.0 ").c_str(), 8), "SIP/2.0"); -} // SipResponseParseVersionCodeTest - - +} // SipResponseParseVersionCodeTest PTF_TEST_CASE(SipResponseLayerParsingTest) { @@ -423,7 +437,8 @@ PTF_TEST_CASE(SipResponseLayerParsingTest) PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getSize(), 20); PTF_ASSERT_NOT_NULL(sipRespLayer->getFieldByName(PCPP_SIP_FROM_FIELD)); - PTF_ASSERT_EQUAL(sipRespLayer->getFieldByName(PCPP_SIP_FROM_FIELD)->getFieldValue(), ";tag=GR52RWG346-34"); + PTF_ASSERT_EQUAL(sipRespLayer->getFieldByName(PCPP_SIP_FROM_FIELD)->getFieldValue(), + ";tag=GR52RWG346-34"); PTF_ASSERT_NOT_NULL(sipRespLayer->getFieldByName(PCPP_SIP_CALL_ID_FIELD)); PTF_ASSERT_EQUAL(sipRespLayer->getFieldByName(PCPP_SIP_CALL_ID_FIELD)->getFieldValue(), "12013223@200.57.7.195"); PTF_ASSERT_NOT_NULL(sipRespLayer->getFieldByName(PCPP_SIP_SERVER_FIELD)); @@ -432,7 +447,6 @@ PTF_TEST_CASE(SipResponseLayerParsingTest) PTF_ASSERT_EQUAL(sipRespLayer->getFieldByName(PCPP_SIP_CONTENT_LENGTH_FIELD)->getFieldValue(), "0"); PTF_ASSERT_EQUAL(sipRespLayer->getContentLength(), 0); - sipRespLayer = sipRespPacket2.getLayerOfType(); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCode(), pcpp::SipResponseLayer::Sip180Ringing, enum); @@ -443,12 +457,12 @@ PTF_TEST_CASE(SipResponseLayerParsingTest) PTF_ASSERT_EQUAL(sipRespLayer->getFirstField()->getFieldName(), PCPP_SIP_VIA_FIELD); PTF_ASSERT_NOT_NULL(sipRespLayer->getFieldByName(PCPP_SIP_VIA_FIELD)); - PTF_ASSERT_EQUAL(sipRespLayer->getFieldByName(PCPP_SIP_VIA_FIELD)->getFieldValue(), "SIP/2.0/UDP 200.57.7.195;branch=z9hG4bKff9b46fb055c0521cc24024da96cd290"); + PTF_ASSERT_EQUAL(sipRespLayer->getFieldByName(PCPP_SIP_VIA_FIELD)->getFieldValue(), + "SIP/2.0/UDP 200.57.7.195;branch=z9hG4bKff9b46fb055c0521cc24024da96cd290"); PTF_ASSERT_NOT_NULL(sipRespLayer->getFieldByName(PCPP_SIP_CSEQ_FIELD)); PTF_ASSERT_EQUAL(sipRespLayer->getFieldByName(PCPP_SIP_CSEQ_FIELD)->getFieldValue(), "1 INVITE"); PTF_ASSERT_EQUAL(sipRespLayer->getContentLength(), 0); - sipRespLayer = sipRespPacket3.getLayerOfType(); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCode(), pcpp::SipResponseLayer::Sip200OK, enum); @@ -461,7 +475,6 @@ PTF_TEST_CASE(SipResponseLayerParsingTest) PTF_ASSERT_EQUAL(sipRespLayer->getFieldByName(PCPP_SIP_CONTENT_TYPE_FIELD)->getFieldValue(), "application/sdp"); PTF_ASSERT_EQUAL(sipRespLayer->getContentLength(), 298); - sipRespLayer = sipRespPacket4.getLayerOfType(); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCode(), pcpp::SipResponseLayer::Sip401Unauthorized, enum); @@ -471,13 +484,15 @@ PTF_TEST_CASE(SipResponseLayerParsingTest) PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getSize(), 26); PTF_ASSERT_NOT_NULL(sipRespLayer->getFieldByName(PCPP_SIP_WWW_AUTHENTICATE_FIELD)); - PTF_ASSERT_EQUAL(sipRespLayer->getFieldByName(PCPP_SIP_WWW_AUTHENTICATE_FIELD)->getFieldValue(), "Digest realm=\"ims.hom\",nonce=\"021fa2db5ff06518\",opaque=\"627f7bb95d5e2dcd\",algorithm=MD5,qop=\"auth\""); + PTF_ASSERT_EQUAL( + sipRespLayer->getFieldByName(PCPP_SIP_WWW_AUTHENTICATE_FIELD)->getFieldValue(), + "Digest realm=\"ims.hom\",nonce=\"021fa2db5ff06518\",opaque=\"627f7bb95d5e2dcd\",algorithm=MD5,qop=\"auth\""); PTF_ASSERT_EQUAL(sipRespLayer->getContentLength(), 0); - sipRespLayer = sipRespPacket7.getLayerOfType(); - PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCode(), pcpp::SipResponseLayer::Sip503ServiceUnavailable, enum); + PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCode(), pcpp::SipResponseLayer::Sip503ServiceUnavailable, + enum); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCodeAsInt(), 503); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCodeString(), "Service Unavailable"); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getVersion(), "SIP/2.0"); @@ -486,9 +501,7 @@ PTF_TEST_CASE(SipResponseLayerParsingTest) PTF_ASSERT_NOT_NULL(sipRespLayer->getFieldByName(PCPP_SIP_RETRY_AFTER_FIELD)); PTF_ASSERT_EQUAL(sipRespLayer->getFieldByName(PCPP_SIP_RETRY_AFTER_FIELD)->getFieldValue(), "0"); PTF_ASSERT_EQUAL(sipRespLayer->getContentLength(), 0); -} // SipResponseLayerParsingTest - - +} // SipResponseLayerParsingTest PTF_TEST_CASE(SipResponseLayerCreationTest) { @@ -513,10 +526,13 @@ PTF_TEST_CASE(SipResponseLayerCreationTest) contentLengthField->setFieldValue(" 0"); PTF_ASSERT_NOT_NULL(sipRespLayer.addEndOfHeader()); PTF_ASSERT_NOT_NULL(sipRespLayer.insertField(nullptr, PCPP_SIP_CALL_ID_FIELD, "93803593")); - PTF_ASSERT_NOT_NULL(sipRespLayer.insertField(nullptr, PCPP_SIP_VIA_FIELD, "SIP/2.0/UDP 10.3.160.214:5060;rport=5060;received=10.3.160.214;branch=z9hG4bK19266132")); + PTF_ASSERT_NOT_NULL(sipRespLayer.insertField( + nullptr, PCPP_SIP_VIA_FIELD, + "SIP/2.0/UDP 10.3.160.214:5060;rport=5060;received=10.3.160.214;branch=z9hG4bK19266132")); pcpp::HeaderField* fromField = sipRespLayer.getFieldByName(PCPP_SIP_FROM_FIELD); PTF_ASSERT_NOT_NULL(fromField); - PTF_ASSERT_NOT_NULL(sipRespLayer.insertField(fromField, PCPP_SIP_TO_FIELD, ";tag=z9hG4bKPjoKb0QlsN0Z-v4iW63WRm5UfjLn.Gm81V")); + PTF_ASSERT_NOT_NULL(sipRespLayer.insertField( + fromField, PCPP_SIP_TO_FIELD, ";tag=z9hG4bKPjoKb0QlsN0Z-v4iW63WRm5UfjLn.Gm81V")); pcpp::Packet newSipPacket; PTF_ASSERT_TRUE(newSipPacket.addLayer(ðLayer)); @@ -529,10 +545,9 @@ PTF_TEST_CASE(SipResponseLayerCreationTest) newSipPacket.getLayerOfType()->getUdpHeader()->headerChecksum = 0xced8; PTF_ASSERT_EQUAL(newSipPacket.getRawPacket()->getRawDataLen(), bufferLength6); - PTF_ASSERT_BUF_COMPARE(newSipPacket.getRawPacket()->getRawData(), buffer6, newSipPacket.getRawPacket()->getRawDataLen()); -} // SipResponseLayerCreationTest - - + PTF_ASSERT_BUF_COMPARE(newSipPacket.getRawPacket()->getRawData(), buffer6, + newSipPacket.getRawPacket()->getRawDataLen()); +} // SipResponseLayerCreationTest PTF_TEST_CASE(SipResponseLayerEditTest) { @@ -553,12 +568,14 @@ PTF_TEST_CASE(SipResponseLayerEditTest) PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCode(), pcpp::SipResponseLayer::Sip202Accepted, enum); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getSize(), 22); PTF_ASSERT_TRUE(sipRespLayer->getFirstLine()->setStatusCode(pcpp::SipResponseLayer::Sip415UnsupportedMediaType)); - PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCode(), pcpp::SipResponseLayer::Sip415UnsupportedMediaType, enum); + PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCode(), pcpp::SipResponseLayer::Sip415UnsupportedMediaType, + enum); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getSize(), 36); PTF_ASSERT_TRUE(sipRespLayer->getFirstLine()->setStatusCode(pcpp::SipResponseLayer::Sip603Decline)); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCode(), pcpp::SipResponseLayer::Sip603Decline, enum); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getSize(), 21); - PTF_ASSERT_TRUE(sipRespLayer->getFirstLine()->setStatusCode(pcpp::SipResponseLayer::Sip603Decline, "Some other string")); + PTF_ASSERT_TRUE( + sipRespLayer->getFirstLine()->setStatusCode(pcpp::SipResponseLayer::Sip603Decline, "Some other string")); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getStatusCode(), pcpp::SipResponseLayer::Sip603Decline, enum); PTF_ASSERT_EQUAL(sipRespLayer->getFirstLine()->getSize(), 31); PTF_ASSERT_TRUE(sipRespLayer->getFirstLine()->setStatusCode(pcpp::SipResponseLayer::Sip401Unauthorized)); @@ -572,15 +589,20 @@ PTF_TEST_CASE(SipResponseLayerEditTest) PTF_ASSERT_TRUE(sipRespLayer->removeField(PCPP_SIP_VIA_FIELD, 1)); PTF_ASSERT_TRUE(sipRespLayer->removeField(PCPP_SIP_CONTACT_FIELD)); PTF_ASSERT_TRUE(sipRespLayer->removeField(PCPP_SIP_CALL_ID_FIELD)); - PTF_ASSERT_TRUE(sipRespLayer->getFieldByName(PCPP_SIP_VIA_FIELD)->setFieldValue("SIP/2.0/UDP 10.3.160.214:5060;rport=5060;received=10.3.160.214;branch=z9hG4bK758266975")); + PTF_ASSERT_TRUE( + sipRespLayer->getFieldByName(PCPP_SIP_VIA_FIELD) + ->setFieldValue("SIP/2.0/UDP 10.3.160.214:5060;rport=5060;received=10.3.160.214;branch=z9hG4bK758266975")); PTF_ASSERT_TRUE(sipRespLayer->removeField(PCPP_SIP_CONTENT_TYPE_FIELD)); PTF_ASSERT_TRUE(sipRespLayer->removeField(PCPP_SIP_SERVER_FIELD)); PTF_ASSERT_NOT_NULL(sipRespLayer->setContentLength(0)); - PTF_ASSERT_TRUE(sipRespLayer->getFieldByName(PCPP_SIP_FROM_FIELD)->setFieldValue(";tag=1597735002")); - PTF_ASSERT_TRUE(sipRespLayer->getFieldByName(PCPP_SIP_TO_FIELD)->setFieldValue(";tag=z9hG4bKPjNwtzXu2EwWIjxR8qftv00jzO9arV-iyh")); + PTF_ASSERT_TRUE( + sipRespLayer->getFieldByName(PCPP_SIP_FROM_FIELD)->setFieldValue(";tag=1597735002")); + PTF_ASSERT_TRUE(sipRespLayer->getFieldByName(PCPP_SIP_TO_FIELD) + ->setFieldValue(";tag=z9hG4bKPjNwtzXu2EwWIjxR8qftv00jzO9arV-iyh")); PTF_ASSERT_TRUE(sipRespLayer->getFieldByName(PCPP_SIP_CSEQ_FIELD)->setFieldValue("1 REGISTER")); - PTF_ASSERT_NOT_NULL(sipRespLayer->insertField(PCPP_SIP_CSEQ_FIELD, PCPP_SIP_WWW_AUTHENTICATE_FIELD, - "Digest realm=\"ims.hom\",nonce=\"021fa2db5ff06518\",opaque=\"627f7bb95d5e2dcd\",algorithm=MD5,qop=\"auth\"")); + PTF_ASSERT_NOT_NULL(sipRespLayer->insertField( + PCPP_SIP_CSEQ_FIELD, PCPP_SIP_WWW_AUTHENTICATE_FIELD, + "Digest realm=\"ims.hom\",nonce=\"021fa2db5ff06518\",opaque=\"627f7bb95d5e2dcd\",algorithm=MD5,qop=\"auth\"")); PTF_ASSERT_NOT_NULL(sipRespLayer->insertField(PCPP_SIP_VIA_FIELD, PCPP_SIP_CALL_ID_FIELD, "434981653")); PTF_ASSERT_TRUE(sipRespLayer->getFieldByName(PCPP_SIP_CONTENT_LENGTH_FIELD)->setFieldValue(" 0")); @@ -588,12 +610,11 @@ PTF_TEST_CASE(SipResponseLayerEditTest) PTF_ASSERT_EQUAL(secondSipRespLayer->getHeaderLen(), sipRespLayer->getHeaderLen()); PTF_ASSERT_EQUAL(secondSipRespLayer->getFirstLine()->getSize(), sipRespLayer->getFirstLine()->getSize()); - PTF_ASSERT_EQUAL(secondSipRespLayer->getFirstLine()->getStatusCode(), sipRespLayer->getFirstLine()->getStatusCode(), enum); + PTF_ASSERT_EQUAL(secondSipRespLayer->getFirstLine()->getStatusCode(), sipRespLayer->getFirstLine()->getStatusCode(), + enum); PTF_ASSERT_EQUAL(secondSipRespLayer->getFieldCount(), sipRespLayer->getFieldCount()); PTF_ASSERT_BUF_COMPARE(secondSipRespLayer->getData(), sipRespLayer->getData(), secondSipRespLayer->getHeaderLen()); -} // SipResponseLayerEditTest - - +} // SipResponseLayerEditTest PTF_TEST_CASE(SdpLayerParsingTest) { @@ -615,13 +636,16 @@ PTF_TEST_CASE(SdpLayerParsingTest) PTF_ASSERT_NOT_NULL(sdpLayer->getFieldByName(PCPP_SDP_PROTOCOL_VERSION_FIELD)); PTF_ASSERT_EQUAL(sdpLayer->getFieldByName(PCPP_SDP_PROTOCOL_VERSION_FIELD)->getFieldValue(), "0"); PTF_ASSERT_NOT_NULL(sdpLayer->getFieldByName(PCPP_SDP_ORIGINATOR_FIELD)); - PTF_ASSERT_EQUAL(sdpLayer->getFieldByName(PCPP_SDP_ORIGINATOR_FIELD)->getFieldValue(), "Clarent 120386 120387 IN IP4 200.57.7.196"); + PTF_ASSERT_EQUAL(sdpLayer->getFieldByName(PCPP_SDP_ORIGINATOR_FIELD)->getFieldValue(), + "Clarent 120386 120387 IN IP4 200.57.7.196"); PTF_ASSERT_NOT_NULL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_NAME_FIELD)); - PTF_ASSERT_EQUAL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_NAME_FIELD)->getFieldValue(), "audio 40376 RTP/AVP 8 18 4 0"); + PTF_ASSERT_EQUAL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_NAME_FIELD)->getFieldValue(), + "audio 40376 RTP/AVP 8 18 4 0"); PTF_ASSERT_NOT_NULL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_ATTRIBUTE_FIELD)); PTF_ASSERT_EQUAL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_ATTRIBUTE_FIELD)->getFieldValue(), "rtpmap:8 PCMA/8000"); PTF_ASSERT_NOT_NULL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_ATTRIBUTE_FIELD, 2)); - PTF_ASSERT_EQUAL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_ATTRIBUTE_FIELD, 2)->getFieldValue(), "rtpmap:4 G723/8000"); + PTF_ASSERT_EQUAL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_ATTRIBUTE_FIELD, 2)->getFieldValue(), + "rtpmap:4 G723/8000"); PTF_ASSERT_NOT_NULL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_ATTRIBUTE_FIELD, 4)); PTF_ASSERT_EQUAL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_ATTRIBUTE_FIELD, 4)->getFieldValue(), "SendRecv"); PTF_ASSERT_NULL(sdpLayer->getFieldByName(PCPP_SDP_MEDIA_ATTRIBUTE_FIELD, 5)); @@ -645,8 +669,7 @@ PTF_TEST_CASE(SdpLayerParsingTest) PTF_ASSERT_EQUAL(sdpLayer->getOwnerIPv4Address(), pcpp::IPv4Address("10.33.6.100")); PTF_ASSERT_EQUAL(sdpLayer->getMediaPort("audio"), 6010); PTF_ASSERT_EQUAL(sdpLayer->getMediaPort("image"), 6012); -} // SdpLayerParsingTest - +} // SdpLayerParsingTest PTF_TEST_CASE(SipNotSdpLayerParsingTest) { @@ -665,7 +688,7 @@ PTF_TEST_CASE(SipNotSdpLayerParsingTest) PTF_ASSERT_EQUAL(nextLayer->getProtocol(), pcpp::GenericPayload); PTF_ASSERT_FALSE(notSdpPacket.isPacketOfType(pcpp::SDP)); -} // SipNotSdpLayerParsingTest +} // SipNotSdpLayerParsingTest PTF_TEST_CASE(SdpLayerCreationTest) { @@ -725,9 +748,7 @@ PTF_TEST_CASE(SdpLayerCreationTest) PTF_ASSERT_EQUAL(copiedSdpLayer.getFieldCount(), 18); PTF_ASSERT_EQUAL(copiedSdpLayer.getHeaderLen(), 406); PTF_ASSERT_BUF_COMPARE(copiedSdpLayer.getData(), sdpLayerPtr->getData(), sdpLayerPtr->getHeaderLen()); -} // SdpLayerCreationTest - - +} // SdpLayerCreationTest PTF_TEST_CASE(SdpLayerEditTest) { @@ -743,7 +764,8 @@ PTF_TEST_CASE(SdpLayerEditTest) pcpp::SdpLayer* sdpLayer = sourceSdpPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(sdpLayer); - PTF_ASSERT_TRUE(sdpLayer->getFieldByName(PCPP_SDP_ORIGINATOR_FIELD)->setFieldValue("IPP 782647527 782647407 IN IP4 10.33.6.100")); + PTF_ASSERT_TRUE(sdpLayer->getFieldByName(PCPP_SDP_ORIGINATOR_FIELD) + ->setFieldValue("IPP 782647527 782647407 IN IP4 10.33.6.100")); PTF_ASSERT_TRUE(sdpLayer->getFieldByName(PCPP_SDP_SESSION_NAME_FIELD)->setFieldValue("Phone-Call")); PTF_ASSERT_TRUE(sdpLayer->getFieldByName(PCPP_SDP_CONNECTION_INFO_FIELD)->setFieldValue("IN IP4 10.33.6.100")); PTF_ASSERT_TRUE(sdpLayer->removeField(PCPP_SDP_MEDIA_NAME_FIELD)); @@ -779,4 +801,4 @@ PTF_TEST_CASE(SdpLayerEditTest) PTF_ASSERT_EQUAL(sdpLayer->getMediaPort("audio"), targetSdpLayer->getMediaPort("audio")); PTF_ASSERT_EQUAL(sdpLayer->getMediaPort("image"), targetSdpLayer->getMediaPort("image")); PTF_ASSERT_BUF_COMPARE(sdpLayer->getData(), targetSdpLayer->getData(), targetSdpLayer->getHeaderLen()); -} // SdpLayerEditTest +} // SdpLayerEditTest diff --git a/Tests/Packet++Test/Tests/Sll2Tests.cpp b/Tests/Packet++Test/Tests/Sll2Tests.cpp index 052de8daba..64e6b417b7 100644 --- a/Tests/Packet++Test/Tests/Sll2Tests.cpp +++ b/Tests/Packet++Test/Tests/Sll2Tests.cpp @@ -37,8 +37,7 @@ PTF_TEST_CASE(Sll2PacketParsingTest) pcpp::MacAddress macAddrRef("d2:cf:c2:50:15:ea"); PTF_ASSERT_EQUAL(macAddrRef, macAddrFromPacket); PTF_ASSERT_EQUAL(macAddrRef, sll2Layer->getLinkLayerAsMacAddress()); -} // Sll2PacketParsingTest - +} // Sll2PacketParsingTest PTF_TEST_CASE(Sll2PacketCreationTest) { @@ -46,8 +45,7 @@ PTF_TEST_CASE(Sll2PacketCreationTest) sll2Layer.setProtocolType(PCPP_ETHERTYPE_IP); sll2Layer.setMacAddressAsLinkLayer(pcpp::MacAddress("d2:cf:c2:50:15:ea")); - pcpp::IPv4Layer ipLayer(pcpp::IPv4Address(std::string("7.249.151.114")), - pcpp::IPv4Address("116.63.66.108")); + pcpp::IPv4Layer ipLayer(pcpp::IPv4Address(std::string("7.249.151.114")), pcpp::IPv4Address("116.63.66.108")); ipLayer.getIPv4Header()->fragmentOffset = 0x40; ipLayer.getIPv4Header()->ipId = htobe16(35618); ipLayer.getIPv4Header()->timeToLive = 64; @@ -74,5 +72,5 @@ PTF_TEST_CASE(Sll2PacketCreationTest) PTF_ASSERT_FALSE(sll2Layer.setLinkLayerAddr(tempBuf, 9)); pcpp::Logger::getInstance().enableLogs(); - delete [] buffer1; -} // Sll2PacketCreationTest + delete[] buffer1; +} // Sll2PacketCreationTest diff --git a/Tests/Packet++Test/Tests/SllNullLoopbackTests.cpp b/Tests/Packet++Test/Tests/SllNullLoopbackTests.cpp index 3cca58180d..87aa8352d4 100644 --- a/Tests/Packet++Test/Tests/SllNullLoopbackTests.cpp +++ b/Tests/Packet++Test/Tests/SllNullLoopbackTests.cpp @@ -12,7 +12,6 @@ #include "PayloadLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(SllPacketParsingTest) { timeval time; @@ -37,9 +36,7 @@ PTF_TEST_CASE(SllPacketParsingTest) pcpp::MacAddress macAddrRef("00:12:44:1e:74:00"); PTF_ASSERT_EQUAL(macAddrRef, macAddrFromPacket); PTF_ASSERT_EQUAL(sllLayer->getSllHeader()->protocol_type, htobe16(PCPP_ETHERTYPE_IPV6)); -} // SllPacketParsingTest - - +} // SllPacketParsingTest PTF_TEST_CASE(SllPacketCreationTest) { @@ -58,9 +55,12 @@ PTF_TEST_CASE(SllPacketCreationTest) tcpLayer.getTcpHeader()->ackNumber = htobe32(0x7633e977); tcpLayer.getTcpHeader()->ackFlag = 1; tcpLayer.getTcpHeader()->windowSize = htobe16(4098); - PTF_ASSERT_TRUE(tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NopEolOptionEnumType::Nop)).isNotNull()); - PTF_ASSERT_TRUE(tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NopEolOptionEnumType::Nop)).isNotNull()); - pcpp::TcpOption tsOption = tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionEnumType::Timestamp, nullptr, PCPP_TCPOLEN_TIMESTAMP-2)); + PTF_ASSERT_TRUE( + tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NopEolOptionEnumType::Nop)).isNotNull()); + PTF_ASSERT_TRUE( + tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NopEolOptionEnumType::Nop)).isNotNull()); + pcpp::TcpOption tsOption = tcpLayer.addTcpOption( + pcpp::TcpOptionBuilder(pcpp::TcpOptionEnumType::Timestamp, nullptr, PCPP_TCPOLEN_TIMESTAMP - 2)); PTF_ASSERT_TRUE(tsOption.isNotNull()); tsOption.setValue(htobe32(0x0402383b)); tsOption.setValue(htobe32(0x03ff37f5), 4); @@ -72,16 +72,13 @@ PTF_TEST_CASE(SllPacketCreationTest) sllPacket.computeCalculateFields(); - READ_FILE_INTO_BUFFER(1, "PacketExamples/SllPacket2.dat"); PTF_ASSERT_EQUAL(sllPacket.getRawPacket()->getRawDataLen(), bufferLength1); PTF_ASSERT_BUF_COMPARE(sllPacket.getRawPacket()->getRawData(), buffer1, bufferLength1); - delete [] buffer1; -} // SllPacketCreationTest - - + delete[] buffer1; +} // SllPacketCreationTest PTF_TEST_CASE(NullLoopbackTest) { @@ -92,7 +89,6 @@ PTF_TEST_CASE(NullLoopbackTest) READ_FILE_AND_CREATE_PACKET_LINKTYPE(2, "PacketExamples/NullLoopback2.dat", pcpp::LINKTYPE_NULL); READ_FILE_AND_CREATE_PACKET_LINKTYPE(3, "PacketExamples/NullLoopback3.dat", pcpp::LINKTYPE_NULL); - pcpp::Packet nullPacket1(&rawPacket1); pcpp::Packet nullPacket2(&rawPacket2); pcpp::Packet nullPacket3(&rawPacket3); @@ -132,7 +128,9 @@ PTF_TEST_CASE(NullLoopbackTest) pcpp::UdpLayer newUdpLayer(55369, 8612); - uint8_t payload[] = { 0x42, 0x4a, 0x4e, 0x42, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + uint8_t payload[] = { + 0x42, 0x4a, 0x4e, 0x42, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; pcpp::PayloadLayer newPayloadLayer(payload, 16); pcpp::Packet newNullPacket(1); @@ -145,4 +143,4 @@ PTF_TEST_CASE(NullLoopbackTest) PTF_ASSERT_EQUAL(newNullPacket.getRawPacket()->getRawDataLen(), bufferLength2); PTF_ASSERT_BUF_COMPARE(newNullPacket.getRawPacket()->getRawData(), buffer2, bufferLength2); -} // NullLoopbackTest +} // NullLoopbackTest diff --git a/Tests/Packet++Test/Tests/SmtpTests.cpp b/Tests/Packet++Test/Tests/SmtpTests.cpp index 9912daf195..35a516edb5 100644 --- a/Tests/Packet++Test/Tests/SmtpTests.cpp +++ b/Tests/Packet++Test/Tests/SmtpTests.cpp @@ -17,7 +17,7 @@ PTF_TEST_CASE(SmtpParsingTests) // Command READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/smtpCommand.dat"); pcpp::Packet smtpPacket1(&rawPacket1); - auto *smtpLayer1 = smtpPacket1.getLayerOfType(); + auto* smtpLayer1 = smtpPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(smtpLayer1); PTF_ASSERT_EQUAL(smtpLayer1->getHeaderLen(), 12); @@ -31,7 +31,7 @@ PTF_TEST_CASE(SmtpParsingTests) // Response packet READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/smtpResponse.dat"); pcpp::Packet smtpPacket2(&rawPacket2); - auto *smtpLayer2 = smtpPacket2.getLayerOfType(); + auto* smtpLayer2 = smtpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(smtpLayer2); PTF_ASSERT_EQUAL(smtpLayer2->getHeaderLen(), 18); @@ -45,28 +45,25 @@ PTF_TEST_CASE(SmtpParsingTests) // Multiline READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/smtpMultiLine.dat"); pcpp::Packet smtpPacket3(&rawPacket3); - auto *smtpLayer3 = smtpPacket3.getLayerOfType(); + auto* smtpLayer3 = smtpPacket3.getLayerOfType(); PTF_ASSERT_NOT_NULL(smtpLayer3); PTF_ASSERT_EQUAL(smtpLayer3->getHeaderLen(), 181); PTF_ASSERT_EQUAL(smtpLayer3->getStatusCode(), pcpp::SmtpResponseLayer::SmtpStatusCode::SERVICE_READY, enumclass); PTF_ASSERT_EQUAL(smtpLayer3->getStatusCodeString(), "220"); - PTF_ASSERT_EQUAL( - smtpLayer3->getStatusOption(), - "xc90.websitewelcome.com ESMTP Exim 4.69 #1 Mon, 05 Oct 2009 01:05:54 -0500 We do not authorize " - "the use of this system to transport unsolicited, and/or bulk e-mail."); - PTF_ASSERT_EQUAL( - smtpLayer3->getStatusOption(false), - "xc90.websitewelcome.com ESMTP Exim 4.69 #1 Mon, 05 Oct 2009 01:05:54 -0500 \r\n" - "We do not authorize the use of this system to transport unsolicited, \r\nand/or bulk e-mail." - ) + PTF_ASSERT_EQUAL(smtpLayer3->getStatusOption(), + "xc90.websitewelcome.com ESMTP Exim 4.69 #1 Mon, 05 Oct 2009 01:05:54 -0500 We do not authorize " + "the use of this system to transport unsolicited, and/or bulk e-mail."); + PTF_ASSERT_EQUAL(smtpLayer3->getStatusOption(false), + "xc90.websitewelcome.com ESMTP Exim 4.69 #1 Mon, 05 Oct 2009 01:05:54 -0500 \r\n" + "We do not authorize the use of this system to transport unsolicited, \r\nand/or bulk e-mail.") PTF_ASSERT_EQUAL(smtpLayer3->toString(), "SMTP response layer, status code: Service ready"); PTF_ASSERT_TRUE(smtpLayer3->isMultiLine()); // IPv6 READ_FILE_AND_CREATE_PACKET(4, "PacketExamples/smtpIpv6.dat"); pcpp::Packet smtpPacket4(&rawPacket4); - auto *smtpLayer4 = smtpPacket4.getLayerOfType(); + auto* smtpLayer4 = smtpPacket4.getLayerOfType(); PTF_ASSERT_NOT_NULL(smtpLayer4); PTF_ASSERT_EQUAL(smtpLayer4->getHeaderLen(), 51); @@ -80,7 +77,7 @@ PTF_TEST_CASE(SmtpParsingTests) // Username and Password packets. They should return Unknown since there is no command in packets READ_FILE_AND_CREATE_PACKET(5, "PacketExamples/smtpUser.dat"); pcpp::Packet smtpPacket5(&rawPacket5); - auto *smtpLayer5 = smtpPacket5.getLayerOfType(); + auto* smtpLayer5 = smtpPacket5.getLayerOfType(); PTF_ASSERT_EQUAL(smtpLayer5->getHeaderLen(), 30); PTF_ASSERT_EQUAL(smtpLayer5->getCommand(), pcpp::SmtpRequestLayer::SmtpCommand::UNK, enumclass); @@ -92,7 +89,7 @@ PTF_TEST_CASE(SmtpParsingTests) READ_FILE_AND_CREATE_PACKET(6, "PacketExamples/smtpPassword.dat"); pcpp::Packet smtpPacket6(&rawPacket6); - auto *smtpLayer6 = smtpPacket6.getLayerOfType(); + auto* smtpLayer6 = smtpPacket6.getLayerOfType(); PTF_ASSERT_EQUAL(smtpLayer6->getHeaderLen(), 18); PTF_ASSERT_EQUAL(smtpLayer6->getCommand(), pcpp::SmtpRequestLayer::SmtpCommand::UNK, enumclass); @@ -104,86 +101,88 @@ PTF_TEST_CASE(SmtpParsingTests) // Command descriptions std::vector> possibleCommandCodes = { - {static_cast(0), "Unknown command"}, - {pcpp::SmtpRequestLayer::SmtpCommand::DATA, "Starting mail body"}, - {pcpp::SmtpRequestLayer::SmtpCommand::EHLO, "Initiate conversation"}, - {pcpp::SmtpRequestLayer::SmtpCommand::EXPN, "Expand the mailing list"}, - {pcpp::SmtpRequestLayer::SmtpCommand::HELO, "Initiate conversation"}, - {pcpp::SmtpRequestLayer::SmtpCommand::HELP, "Ask information"}, - {pcpp::SmtpRequestLayer::SmtpCommand::MAIL, "Sender indication"}, - {pcpp::SmtpRequestLayer::SmtpCommand::NOOP, "No operation"}, - {pcpp::SmtpRequestLayer::SmtpCommand::QUIT, "Close conversation"}, - {pcpp::SmtpRequestLayer::SmtpCommand::RCPT, "Receiver indication"}, - {pcpp::SmtpRequestLayer::SmtpCommand::RSET, "Abort transaction"}, - {pcpp::SmtpRequestLayer::SmtpCommand::VRFY, "Identify user"}, - {pcpp::SmtpRequestLayer::SmtpCommand::STARTTLS, "Start TLS handshake"}, - {pcpp::SmtpRequestLayer::SmtpCommand::TURN, "Reverse the role of sender and receiver"}, - {pcpp::SmtpRequestLayer::SmtpCommand::SEND, "Send mail to terminal"}, - {pcpp::SmtpRequestLayer::SmtpCommand::SOML, "Send mail to terminal or to mailbox"}, - {pcpp::SmtpRequestLayer::SmtpCommand::SAML, "Send mail to terminal and mailbox"}, - {pcpp::SmtpRequestLayer::SmtpCommand::AUTH, "Authenticate client and server"}, - {pcpp::SmtpRequestLayer::SmtpCommand::ATRN, "Reverse the role of sender and receiver"}, - {pcpp::SmtpRequestLayer::SmtpCommand::BDAT, "Submit mail contents"}, - {pcpp::SmtpRequestLayer::SmtpCommand::ETRN, "Request to start SMTP queue processing"}, - {pcpp::SmtpRequestLayer::SmtpCommand::XADR, "Release status of the channel"}, - {pcpp::SmtpRequestLayer::SmtpCommand::XCIR, "Release status of the circuit checking facility"}, - {pcpp::SmtpRequestLayer::SmtpCommand::XSTA, "Release status of the number of messages in channel queues"}, - {pcpp::SmtpRequestLayer::SmtpCommand::XGEN, - "Release status of whether a compiled configuration and character set are in use"}}; - - for (const auto &entry : possibleCommandCodes) + { static_cast(0), "Unknown command" }, + { pcpp::SmtpRequestLayer::SmtpCommand::DATA, "Starting mail body" }, + { pcpp::SmtpRequestLayer::SmtpCommand::EHLO, "Initiate conversation" }, + { pcpp::SmtpRequestLayer::SmtpCommand::EXPN, "Expand the mailing list" }, + { pcpp::SmtpRequestLayer::SmtpCommand::HELO, "Initiate conversation" }, + { pcpp::SmtpRequestLayer::SmtpCommand::HELP, "Ask information" }, + { pcpp::SmtpRequestLayer::SmtpCommand::MAIL, "Sender indication" }, + { pcpp::SmtpRequestLayer::SmtpCommand::NOOP, "No operation" }, + { pcpp::SmtpRequestLayer::SmtpCommand::QUIT, "Close conversation" }, + { pcpp::SmtpRequestLayer::SmtpCommand::RCPT, "Receiver indication" }, + { pcpp::SmtpRequestLayer::SmtpCommand::RSET, "Abort transaction" }, + { pcpp::SmtpRequestLayer::SmtpCommand::VRFY, "Identify user" }, + { pcpp::SmtpRequestLayer::SmtpCommand::STARTTLS, "Start TLS handshake" }, + { pcpp::SmtpRequestLayer::SmtpCommand::TURN, "Reverse the role of sender and receiver" }, + { pcpp::SmtpRequestLayer::SmtpCommand::SEND, "Send mail to terminal" }, + { pcpp::SmtpRequestLayer::SmtpCommand::SOML, "Send mail to terminal or to mailbox" }, + { pcpp::SmtpRequestLayer::SmtpCommand::SAML, "Send mail to terminal and mailbox" }, + { pcpp::SmtpRequestLayer::SmtpCommand::AUTH, "Authenticate client and server" }, + { pcpp::SmtpRequestLayer::SmtpCommand::ATRN, "Reverse the role of sender and receiver" }, + { pcpp::SmtpRequestLayer::SmtpCommand::BDAT, "Submit mail contents" }, + { pcpp::SmtpRequestLayer::SmtpCommand::ETRN, "Request to start SMTP queue processing" }, + { pcpp::SmtpRequestLayer::SmtpCommand::XADR, "Release status of the channel" }, + { pcpp::SmtpRequestLayer::SmtpCommand::XCIR, "Release status of the circuit checking facility" }, + { pcpp::SmtpRequestLayer::SmtpCommand::XSTA, "Release status of the number of messages in channel queues" }, + { pcpp::SmtpRequestLayer::SmtpCommand::XGEN, + "Release status of whether a compiled configuration and character set are in use" } + }; + + for (const auto& entry : possibleCommandCodes) { PTF_ASSERT_EQUAL(pcpp::SmtpRequestLayer::getCommandInfo(entry.first), entry.second); } // Status descriptions std::vector> possibleStatusCodes = { - {static_cast(0), "Unknown status code"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::SYSTEM_STATUS, "System status, or system help reply"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::HELP_MESSAGE, "Help message"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::SERVICE_READY, "Service ready"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::SERVICE_CLOSE, "Service closing transmission channel"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::AUTH_SUCCESS, "Authentication successful"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::COMPLETED, "Requested mail action okay, completed"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::WILL_FORWARD, "User not local; will forward to "}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::CANNOT_VERIFY, - "Cannot VRFY user, but will accept message and attempt delivery"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::AUTH_INPUT, "AUTH input"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::MAIL_INPUT, "Start mail input; end with ."}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::SERVICE_UNAVAILABLE, - "Service not available, closing transmission channel"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::PASS_NEEDED, "A password transition is needed"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::MAILBOX_UNAVAILABLE_TEMP, - "Requested mail action not taken: mailbox unavailable (mail busy or temporarily blocked)"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::ABORT_LOCAL_ERROR, - "Requested action aborted: local error in processing"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::INSUFFICIENT_STORAGE, - "Requested action not taken: insufficient system storage"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::TEMP_AUTH_FAILED, "Temporary authentication failed"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::PARAM_NOT_ACCOMMODATED, "Server unable to accommodate parameters"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::CMD_NOT_RECOGNIZED, "Syntax error, command unrecognized"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::SYNTAX_ERROR_PARAM, "Syntax error in parameters or arguments"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::CMD_NOT_IMPLEMENTED, "Command not implemented"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::CMD_BAD_SEQUENCE, "Bad sequence of commands"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::PARAM_NOT_IMPLEMENTED, "Command parameter not implemented"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::MAIL_NOT_ACCEPTED, "Server does not accept mail"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::ENCRYPT_NEED, "Encryption needed"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::AUTH_REQUIRED, "Authentication required"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::AUTH_TOO_WEAK, "Authentication mechanism is too weak"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::AUTH_CRED_INVALID, "Authentication credentials invalid"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::ENCRYPT_REQUIRED, - "Encryption required for requested authentication mechanism"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::MAILBOX_UNAVAILABLE, - "Requested action not taken: mailbox unavailable"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::USER_NOT_LOCAL, "User not local; please try "}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::EXCEED_STORAGE, - "Requested mail action aborted: exceeded storage allocation"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::NAME_NOT_ALLOWED, - "Requested action not taken: mailbox name not allowed"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::TRANSACTION_FAIL, "Transaction failed"}, - {pcpp::SmtpResponseLayer::SmtpStatusCode::DOMAIN_NOT_ACCEPT, "Domain does not accept mail"}}; - - for (const auto &entry : possibleStatusCodes) + { static_cast(0), "Unknown status code" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::SYSTEM_STATUS, "System status, or system help reply" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::HELP_MESSAGE, "Help message" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::SERVICE_READY, "Service ready" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::SERVICE_CLOSE, "Service closing transmission channel" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::AUTH_SUCCESS, "Authentication successful" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::COMPLETED, "Requested mail action okay, completed" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::WILL_FORWARD, "User not local; will forward to " }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::CANNOT_VERIFY, + "Cannot VRFY user, but will accept message and attempt delivery" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::AUTH_INPUT, "AUTH input" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::MAIL_INPUT, "Start mail input; end with ." }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::SERVICE_UNAVAILABLE, + "Service not available, closing transmission channel" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::PASS_NEEDED, "A password transition is needed" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::MAILBOX_UNAVAILABLE_TEMP, + "Requested mail action not taken: mailbox unavailable (mail busy or temporarily blocked)" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::ABORT_LOCAL_ERROR, + "Requested action aborted: local error in processing" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::INSUFFICIENT_STORAGE, + "Requested action not taken: insufficient system storage" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::TEMP_AUTH_FAILED, "Temporary authentication failed" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::PARAM_NOT_ACCOMMODATED, "Server unable to accommodate parameters" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::CMD_NOT_RECOGNIZED, "Syntax error, command unrecognized" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::SYNTAX_ERROR_PARAM, "Syntax error in parameters or arguments" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::CMD_NOT_IMPLEMENTED, "Command not implemented" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::CMD_BAD_SEQUENCE, "Bad sequence of commands" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::PARAM_NOT_IMPLEMENTED, "Command parameter not implemented" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::MAIL_NOT_ACCEPTED, "Server does not accept mail" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::ENCRYPT_NEED, "Encryption needed" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::AUTH_REQUIRED, "Authentication required" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::AUTH_TOO_WEAK, "Authentication mechanism is too weak" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::AUTH_CRED_INVALID, "Authentication credentials invalid" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::ENCRYPT_REQUIRED, + "Encryption required for requested authentication mechanism" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::MAILBOX_UNAVAILABLE, + "Requested action not taken: mailbox unavailable" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::USER_NOT_LOCAL, "User not local; please try " }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::EXCEED_STORAGE, + "Requested mail action aborted: exceeded storage allocation" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::NAME_NOT_ALLOWED, + "Requested action not taken: mailbox name not allowed" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::TRANSACTION_FAIL, "Transaction failed" }, + { pcpp::SmtpResponseLayer::SmtpStatusCode::DOMAIN_NOT_ACCEPT, "Domain does not accept mail" } + }; + + for (const auto& entry : possibleStatusCodes) { PTF_ASSERT_EQUAL(pcpp::SmtpResponseLayer::getStatusCodeAsString(entry.first), entry.second); } @@ -246,7 +245,7 @@ PTF_TEST_CASE(SmtpEditTests) READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/smtpCommandEdited.dat"); pcpp::Packet smtpPacket1(&rawPacket1); - auto *smtpLayer1 = smtpPacket1.getLayerOfType(); + auto* smtpLayer1 = smtpPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(smtpLayer1); smtpLayer1->setCommand(pcpp::SmtpRequestLayer::SmtpCommand::EHLO); @@ -256,13 +255,13 @@ PTF_TEST_CASE(SmtpEditTests) pcpp::Packet smtpEditedPacket1(&rawPacket2); PTF_ASSERT_EQUAL(smtpPacket1.getRawPacket()->getRawDataLen(), smtpEditedPacket1.getRawPacket()->getRawDataLen()); PTF_ASSERT_BUF_COMPARE(smtpPacket1.getRawPacket()->getRawData(), smtpEditedPacket1.getRawPacket()->getRawData(), - smtpPacket1.getRawPacket()->getRawDataLen()); + smtpPacket1.getRawPacket()->getRawDataLen()); // Response multiline READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/smtpMultiLine.dat"); pcpp::Packet smtpPacket2(&rawPacket3); - auto *smtpLayer2 = smtpPacket2.getLayerOfType(); + auto* smtpLayer2 = smtpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(smtpLayer2); smtpLayer2->setStatusCode(pcpp::SmtpResponseLayer::SmtpStatusCode::ABORT_LOCAL_ERROR); smtpLayer2->setStatusOption("Test Option Line 1\r\n451 Test Option Line 2"); @@ -273,5 +272,5 @@ PTF_TEST_CASE(SmtpEditTests) PTF_ASSERT_EQUAL(smtpPacket2.getRawPacket()->getRawDataLen(), smtpEditedPacket2.getRawPacket()->getRawDataLen()); PTF_ASSERT_BUF_COMPARE(smtpPacket2.getRawPacket()->getRawData(), smtpEditedPacket2.getRawPacket()->getRawData(), - smtpPacket2.getRawPacket()->getRawDataLen()); + smtpPacket2.getRawPacket()->getRawDataLen()); } diff --git a/Tests/Packet++Test/Tests/SomeIpSdTests.cpp b/Tests/Packet++Test/Tests/SomeIpSdTests.cpp index 50254bbe18..3e4a437287 100644 --- a/Tests/Packet++Test/Tests/SomeIpSdTests.cpp +++ b/Tests/Packet++Test/Tests/SomeIpSdTests.cpp @@ -62,7 +62,7 @@ PTF_TEST_CASE(SomeIpSdParsingTest) PTF_ASSERT_EQUAL((uint8_t)option->getType(), (uint8_t)pcpp::SomeIpSdOption::OptionType::IPv4Endpoint); PTF_ASSERT_EQUAL(option->getDataPtr()[1], 0x09); - pcpp::SomeIpSdIPv4Option* ipv4Option = (pcpp::SomeIpSdIPv4Option*) option; + pcpp::SomeIpSdIPv4Option* ipv4Option = (pcpp::SomeIpSdIPv4Option*)option; PTF_ASSERT_EQUAL(ipv4Option->getIpAddress(), pcpp::IPv4Address("160.48.199.28")); PTF_ASSERT_EQUAL(ipv4Option->getProtocol(), pcpp::SomeIpSdProtocolType::SD_UDP); PTF_ASSERT_EQUAL(ipv4Option->getPort(), 30502); @@ -110,19 +110,21 @@ PTF_TEST_CASE(SomeIpSdParsingTest) PTF_ASSERT_EQUAL((uint8_t)option2_1->getType(), (uint8_t)pcpp::SomeIpSdOption::OptionType::IPv6Endpoint); PTF_ASSERT_EQUAL(option2_1->getDataPtr()[1], 0x15); - pcpp::SomeIpSdIPv6Option* ipv6Option2_1 = (pcpp::SomeIpSdIPv6Option*) option2_1; + pcpp::SomeIpSdIPv6Option* ipv6Option2_1 = (pcpp::SomeIpSdIPv6Option*)option2_1; PTF_ASSERT_EQUAL(ipv6Option2_1->getIpAddress(), pcpp::IPv6Address("fd53:7cb8:383:4::1:1e5")); PTF_ASSERT_EQUAL(ipv6Option2_1->getProtocol(), pcpp::SomeIpSdProtocolType::SD_TCP); PTF_ASSERT_EQUAL(ipv6Option2_1->getPort(), 29769); - pcpp::SomeIpSdOption* option2_2 = *(options2.begin()+1); + pcpp::SomeIpSdOption* option2_2 = *(options2.begin() + 1); PTF_ASSERT_EQUAL(option2_2->getLength(), 93); PTF_ASSERT_EQUAL((uint8_t)option2_2->getType(), (uint8_t)pcpp::SomeIpSdOption::OptionType::ConfigurationString); PTF_ASSERT_EQUAL(option2_2->getDataPtr()[5], 0x63); - pcpp::SomeIpSdConfigurationOption* configurationOption = (pcpp::SomeIpSdConfigurationOption*) option2_2; - for(int i = 0; i < 89; i++){ - PTF_ASSERT_EQUAL(configurationOption->getConfigurationString()[i], someIpSdPacket2.getRawPacket()->getRawData()[138+i]); + pcpp::SomeIpSdConfigurationOption* configurationOption = (pcpp::SomeIpSdConfigurationOption*)option2_2; + for (int i = 0; i < 89; i++) + { + PTF_ASSERT_EQUAL(configurationOption->getConfigurationString()[i], + someIpSdPacket2.getRawPacket()->getRawData()[138 + i]); } pcpp::SomeIpSdLayer::OptionsVec options2Entry0 = someIpSdLayer2->getOptionsFromEntry(0); @@ -133,9 +135,10 @@ PTF_TEST_CASE(SomeIpSdParsingTest) PTF_ASSERT_EQUAL((uint8_t)options2Entry0_1->getType(), (uint8_t)pcpp::SomeIpSdOption::OptionType::IPv6Endpoint); PTF_ASSERT_EQUAL(options2Entry0_1->getDataPtr()[1], 0x15); - pcpp::SomeIpSdOption* options2Entry0_2 = *(options2Entry0.begin()+1); + pcpp::SomeIpSdOption* options2Entry0_2 = *(options2Entry0.begin() + 1); PTF_ASSERT_EQUAL(options2Entry0_2->getLength(), 93); - PTF_ASSERT_EQUAL((uint8_t)options2Entry0_2->getType(), (uint8_t)pcpp::SomeIpSdOption::OptionType::ConfigurationString); + PTF_ASSERT_EQUAL((uint8_t)options2Entry0_2->getType(), + (uint8_t)pcpp::SomeIpSdOption::OptionType::ConfigurationString); PTF_ASSERT_EQUAL(options2Entry0_2->getDataPtr()[5], 0x63); pcpp::SomeIpSdLayer::OptionsVec options2Entry1 = someIpSdLayer2->getOptionsFromEntry(1); @@ -177,7 +180,7 @@ PTF_TEST_CASE(SomeIpSdParsingTest) PTF_ASSERT_EQUAL(entry3_1->getEventgroupId(), 1); PTF_ASSERT_EQUAL(entry3_1->getDataPtr()[0], 0x06); - pcpp::SomeIpSdEntry* entry3_2 = *(entries3.begin()+1); + pcpp::SomeIpSdEntry* entry3_2 = *(entries3.begin() + 1); PTF_ASSERT_EQUAL(entry3_2->getLength(), 16); PTF_ASSERT_EQUAL(entry3_2->getNumOptions(), 1); PTF_ASSERT_EQUAL((uint8_t)entry3_2->getType(), (uint8_t)pcpp::SomeIpSdEntry::EntryType::SubscribeEventgroup); @@ -228,8 +231,11 @@ PTF_TEST_CASE(SomeIpSdCreationTest) // OfferService (Entry: OfferService, Option: IPv4Endpoint) pcpp::SomeIpSdLayer someIpSdLayer(0xffff, 0x8100, 0, 0x2, 0x1, pcpp::SomeIpLayer::MsgType::NOTIFICATION, 0, 0xc0); - auto pEntry = std::unique_ptr(new pcpp::SomeIpSdEntry(pcpp::SomeIpSdEntry::EntryType::OfferService, 0xd05f, 2, 1, 3, 0)); - auto pOption = std::unique_ptr(new pcpp::SomeIpSdIPv4Option(pcpp::SomeIpSdIPv4Option::IPv4OptionType::IPv4Endpoint, pcpp::IPv4Address("160.48.199.28"), 30502, pcpp::SomeIpSdProtocolType::SD_UDP)); + auto pEntry = std::unique_ptr( + new pcpp::SomeIpSdEntry(pcpp::SomeIpSdEntry::EntryType::OfferService, 0xd05f, 2, 1, 3, 0)); + auto pOption = std::unique_ptr( + new pcpp::SomeIpSdIPv4Option(pcpp::SomeIpSdIPv4Option::IPv4OptionType::IPv4Endpoint, + pcpp::IPv4Address("160.48.199.28"), 30502, pcpp::SomeIpSdProtocolType::SD_UDP)); auto offsetEntry = someIpSdLayer.addEntry(*pEntry); someIpSdLayer.addOptionTo(offsetEntry, *pOption); @@ -237,14 +243,18 @@ PTF_TEST_CASE(SomeIpSdCreationTest) PTF_ASSERT_TRUE(someIpSdPacket.addLayer(&someIpSdLayer)); someIpSdPacket.computeCalculateFields(); - PTF_ASSERT_EQUAL(someIpSdPacket.getRawPacket()->getRawDataLen(), bufferLength1-46); - PTF_ASSERT_BUF_COMPARE(someIpSdPacket.getRawPacket()->getRawData(), buffer1+46, bufferLength1-46); + PTF_ASSERT_EQUAL(someIpSdPacket.getRawPacket()->getRawDataLen(), bufferLength1 - 46); + PTF_ASSERT_BUF_COMPARE(someIpSdPacket.getRawPacket()->getRawData(), buffer1 + 46, bufferLength1 - 46); // Subscribe (Entry: 2xSubscribeEventgroup, Option: IPv4Endpoint) pcpp::SomeIpSdLayer someIpSdLayer2(0xffff, 0x8100, 0, 0x3, 0x1, pcpp::SomeIpLayer::MsgType::NOTIFICATION, 0, 0xc0); - auto pEntry2_1 = std::unique_ptr(new pcpp::SomeIpSdEntry(pcpp::SomeIpSdEntry::EntryType::SubscribeEventgroup, 0xd063, 1, 1, 3, 0, 1)); - auto pEntry2_2 = std::unique_ptr(new pcpp::SomeIpSdEntry(pcpp::SomeIpSdEntry::EntryType::SubscribeEventgroup, 0xd066, 1, 1, 3, 0, 1)); - auto pOption2 = std::unique_ptr(new pcpp::SomeIpSdIPv4Option(pcpp::SomeIpSdIPv4Option::IPv4OptionType::IPv4Endpoint, pcpp::IPv4Address("160.48.199.101"), 58358, pcpp::SomeIpSdProtocolType::SD_UDP)); + auto pEntry2_1 = std::unique_ptr( + new pcpp::SomeIpSdEntry(pcpp::SomeIpSdEntry::EntryType::SubscribeEventgroup, 0xd063, 1, 1, 3, 0, 1)); + auto pEntry2_2 = std::unique_ptr( + new pcpp::SomeIpSdEntry(pcpp::SomeIpSdEntry::EntryType::SubscribeEventgroup, 0xd066, 1, 1, 3, 0, 1)); + auto pOption2 = std::unique_ptr( + new pcpp::SomeIpSdIPv4Option(pcpp::SomeIpSdIPv4Option::IPv4OptionType::IPv4Endpoint, + pcpp::IPv4Address("160.48.199.101"), 58358, pcpp::SomeIpSdProtocolType::SD_UDP)); auto offsetEntry2_1 = someIpSdLayer2.addEntry(*pEntry2_1); someIpSdLayer2.addOptionTo(offsetEntry2_1, *pOption2); auto offsetEntry2_2 = someIpSdLayer2.addEntry(*pEntry2_2); @@ -254,9 +264,9 @@ PTF_TEST_CASE(SomeIpSdCreationTest) PTF_ASSERT_TRUE(someIpSdPacket2.addLayer(&someIpSdLayer2)); someIpSdPacket2.computeCalculateFields(); - PTF_ASSERT_EQUAL(someIpSdPacket2.getRawPacket()->getRawDataLen(), bufferLength2-46); - PTF_ASSERT_BUF_COMPARE(someIpSdPacket2.getRawPacket()->getRawData(), buffer2+46, bufferLength2-46); + PTF_ASSERT_EQUAL(someIpSdPacket2.getRawPacket()->getRawDataLen(), bufferLength2 - 46); + PTF_ASSERT_BUF_COMPARE(someIpSdPacket2.getRawPacket()->getRawData(), buffer2 + 46, bufferLength2 - 46); - delete [] buffer1; - delete [] buffer2; + delete[] buffer1; + delete[] buffer2; } diff --git a/Tests/Packet++Test/Tests/SomeIpTests.cpp b/Tests/Packet++Test/Tests/SomeIpTests.cpp index 53433ab158..216b9b34b0 100644 --- a/Tests/Packet++Test/Tests/SomeIpTests.cpp +++ b/Tests/Packet++Test/Tests/SomeIpTests.cpp @@ -14,8 +14,12 @@ class SomeIpTeardown { public: - SomeIpTeardown() {} - ~SomeIpTeardown() { pcpp::SomeIpLayer::removeAllSomeIpPorts(); } + SomeIpTeardown() + {} + ~SomeIpTeardown() + { + pcpp::SomeIpLayer::removeAllSomeIpPorts(); + } }; PTF_TEST_CASE(SomeIpPortTest) @@ -55,7 +59,7 @@ PTF_TEST_CASE(SomeIpParsingTest) // Test with one SOME/IP layer PTF_ASSERT_TRUE(someIpPacket.isPacketOfType(pcpp::SomeIP)); - pcpp::SomeIpLayer *someIpLayer = someIpPacket.getLayerOfType(); + pcpp::SomeIpLayer* someIpLayer = someIpPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(someIpLayer); PTF_ASSERT_EQUAL(someIpLayer->getHeaderLen(), 38); PTF_ASSERT_EQUAL(someIpLayer->getMessageID(), 0x6059410c); @@ -77,7 +81,7 @@ PTF_TEST_CASE(SomeIpParsingTest) PTF_ASSERT_NULL(someIpLayer->getNextLayer()); // Test with two SOME/IP layers - pcpp::SomeIpLayer *someIpLayer2_1 = someIpPacket2.getLayerOfType(); + pcpp::SomeIpLayer* someIpLayer2_1 = someIpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(someIpLayer2_1); PTF_ASSERT_EQUAL(someIpLayer2_1->getHeaderLen(), 38); PTF_ASSERT_EQUAL(someIpLayer2_1->getMessageID(), 0x6059410c); @@ -98,7 +102,7 @@ PTF_TEST_CASE(SomeIpParsingTest) PTF_ASSERT_EQUAL(someIpLayer2_1->toString(), "SOME/IP Layer, Service ID: 0x6059, Method ID: 0x410c, Length: 30"); PTF_ASSERT_NOT_NULL(someIpLayer2_1->getNextLayer()); - pcpp::SomeIpLayer *someIpLayer2_2 = someIpPacket2.getNextLayerOfType(someIpLayer2_1); + pcpp::SomeIpLayer* someIpLayer2_2 = someIpPacket2.getNextLayerOfType(someIpLayer2_1); PTF_ASSERT_NOT_NULL(someIpLayer2_2); PTF_ASSERT_EQUAL(someIpLayer2_2->getHeaderLen(), 36); PTF_ASSERT_EQUAL(someIpLayer2_2->getMessageID(), 0x6060410d); @@ -128,28 +132,33 @@ PTF_TEST_CASE(SomeIpCreationTest) READ_FILE_INTO_BUFFER(1, "PacketExamples/someip.dat"); READ_FILE_INTO_BUFFER(2, "PacketExamples/someip2.dat"); - std::array data1{0x40, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x85, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00}; + std::array data1{ 0x40, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x85, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00 }; - std::array data2{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14}; + std::array data2{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14 }; // Test with one SOME/IP layer - pcpp::SomeIpLayer someipLayer1(0x6059, 0x410c, 0x3, 0xa, 0x5, pcpp::SomeIpLayer::MsgType::REQUEST, 0, data1.data(), data1.size()); + pcpp::SomeIpLayer someipLayer1(0x6059, 0x410c, 0x3, 0xa, 0x5, pcpp::SomeIpLayer::MsgType::REQUEST, 0, data1.data(), + data1.size()); pcpp::Packet someIpPacket(100); PTF_ASSERT_TRUE(someIpPacket.addLayer(&someipLayer1)); someIpPacket.computeCalculateFields(); - PTF_ASSERT_EQUAL(someIpPacket.getRawPacket()->getRawDataLen(), bufferLength1-78); - PTF_ASSERT_BUF_COMPARE(someIpPacket.getRawPacket()->getRawData(), buffer1+78, bufferLength1-78); + PTF_ASSERT_EQUAL(someIpPacket.getRawPacket()->getRawDataLen(), bufferLength1 - 78); + PTF_ASSERT_BUF_COMPARE(someIpPacket.getRawPacket()->getRawData(), buffer1 + 78, bufferLength1 - 78); // Test with two SOME/IP layers - pcpp::EthLayer ethLayer2(pcpp::MacAddress("02:7d:fa:01:17:40"), pcpp::MacAddress("02:7d:fa:00:10:01"), PCPP_ETHERTYPE_VLAN); + pcpp::EthLayer ethLayer2(pcpp::MacAddress("02:7d:fa:01:17:40"), pcpp::MacAddress("02:7d:fa:00:10:01"), + PCPP_ETHERTYPE_VLAN); pcpp::VlanLayer vlanLayer2(2, false, 0, PCPP_ETHERTYPE_IP); - pcpp::IPv6Layer ip6Layer2(pcpp::IPv6Address("fd53:7cb8:0383:0002::0001:0117"), pcpp::IPv6Address("fd53:7cb8:0383:000e::0014")); + pcpp::IPv6Layer ip6Layer2(pcpp::IPv6Address("fd53:7cb8:0383:0002::0001:0117"), + pcpp::IPv6Address("fd53:7cb8:0383:000e::0014")); pcpp::UdpLayer udpLayer2(29300, 29180); - pcpp::SomeIpLayer someipLayer2_1(0x6059, 0x410c, 0x3, 0xa, 0x5, pcpp::SomeIpLayer::MsgType::REQUEST, 0, data1.data(), data1.size()); - pcpp::SomeIpLayer someipLayer2_2(0x6060, 0x410d, 0x4, 0xb, 0x6, pcpp::SomeIpLayer::MsgType::REQUEST, 0, data2.data(), data2.size()); + pcpp::SomeIpLayer someipLayer2_1(0x6059, 0x410c, 0x3, 0xa, 0x5, pcpp::SomeIpLayer::MsgType::REQUEST, 0, + data1.data(), data1.size()); + pcpp::SomeIpLayer someipLayer2_2(0x6060, 0x410d, 0x4, 0xb, 0x6, pcpp::SomeIpLayer::MsgType::REQUEST, 0, + data2.data(), data2.size()); pcpp::Packet someIpPacket2(100); PTF_ASSERT_TRUE(someIpPacket2.addLayer(ðLayer2)); @@ -163,8 +172,8 @@ PTF_TEST_CASE(SomeIpCreationTest) PTF_ASSERT_EQUAL(someIpPacket2.getRawPacket()->getRawDataLen(), bufferLength2); PTF_ASSERT_BUF_COMPARE(someIpPacket2.getRawPacket()->getRawData(), buffer2, bufferLength2); - delete [] buffer1; - delete [] buffer2; + delete[] buffer1; + delete[] buffer2; } PTF_TEST_CASE(SomeIpTpParsingTest) @@ -184,7 +193,7 @@ PTF_TEST_CASE(SomeIpTpParsingTest) // Test SOME/IP-TP start packet PTF_ASSERT_TRUE(someIpTpPacket1.isPacketOfType(pcpp::SomeIP)); - pcpp::SomeIpTpLayer *someIpTpLayer1 = someIpTpPacket1.getLayerOfType(); + pcpp::SomeIpTpLayer* someIpTpLayer1 = someIpTpPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(someIpTpLayer1); PTF_ASSERT_EQUAL(someIpTpLayer1->getHeaderLen(), 1412); PTF_ASSERT_EQUAL(someIpTpLayer1->getMessageID(), 0xd05f8001); @@ -204,11 +213,12 @@ PTF_TEST_CASE(SomeIpTpParsingTest) PTF_ASSERT_EQUAL(someIpTpLayer1->getPduPayloadSize(), 1392); PTF_ASSERT_EQUAL(someIpTpLayer1->getPduPayload()[0], 0x12); PTF_ASSERT_EQUAL(someIpTpLayer1->getPduPayload()[1391], 0x34); - PTF_ASSERT_EQUAL(someIpTpLayer1->toString(), "SOME/IP-TP Layer, Service ID: 0xd05f, Method ID: 0x8001, Length: 1404"); + PTF_ASSERT_EQUAL(someIpTpLayer1->toString(), + "SOME/IP-TP Layer, Service ID: 0xd05f, Method ID: 0x8001, Length: 1404"); // Test SOME/IP-TP end packet PTF_ASSERT_TRUE(someIpTpPacket2.isPacketOfType(pcpp::SomeIP)); - pcpp::SomeIpTpLayer *someIpTpLayer2 = someIpTpPacket2.getLayerOfType(); + pcpp::SomeIpTpLayer* someIpTpLayer2 = someIpTpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(someIpTpLayer2); PTF_ASSERT_EQUAL(someIpTpLayer2->getHeaderLen(), 245); PTF_ASSERT_EQUAL(someIpTpLayer2->getMessageID(), 0xd05f8001); @@ -228,7 +238,8 @@ PTF_TEST_CASE(SomeIpTpParsingTest) PTF_ASSERT_EQUAL(someIpTpLayer2->getPduPayloadSize(), 225); PTF_ASSERT_EQUAL(someIpTpLayer2->getPduPayload()[0], 0xab); PTF_ASSERT_EQUAL(someIpTpLayer2->getPduPayload()[224], 0xcd); - PTF_ASSERT_EQUAL(someIpTpLayer2->toString(), "SOME/IP-TP Layer, Service ID: 0xd05f, Method ID: 0x8001, Length: 237"); + PTF_ASSERT_EQUAL(someIpTpLayer2->toString(), + "SOME/IP-TP Layer, Service ID: 0xd05f, Method ID: 0x8001, Length: 237"); } PTF_TEST_CASE(SomeIpTpCreationTest) @@ -240,23 +251,24 @@ PTF_TEST_CASE(SomeIpTpCreationTest) READ_FILE_INTO_BUFFER(2, "PacketExamples/SomeIpTp2.dat"); const size_t dataLen1 = 1392; - uint8_t data1[dataLen1] = {0}; + uint8_t data1[dataLen1] = { 0 }; data1[0] = 0x12; - data1[dataLen1-1] = 0x34; + data1[dataLen1 - 1] = 0x34; const size_t dataLen2 = 225; - uint8_t data2[dataLen2] = {0}; + uint8_t data2[dataLen2] = { 0 }; data2[0] = 0xab; - data2[dataLen2-1] = 0xcd; + data2[dataLen2 - 1] = 0xcd; - pcpp::EthLayer ethLayer1(pcpp::MacAddress("02:7d:fa:01:17:40"), pcpp::MacAddress("02:7d:fa:00:10:01"), PCPP_ETHERTYPE_IP); + pcpp::EthLayer ethLayer1(pcpp::MacAddress("02:7d:fa:01:17:40"), pcpp::MacAddress("02:7d:fa:00:10:01"), + PCPP_ETHERTYPE_IP); pcpp::IPv4Layer ipLayer1(pcpp::IPv4Address("192.168.0.1"), pcpp::IPv4Address("192.168.0.2")); ipLayer1.getIPv4Header()->timeToLive = 20; pcpp::UdpLayer udpLayer1(30502, 16832); // Test SOME/IP-TP start packet pcpp::SomeIpTpLayer someIpTpLayer1(0xd05f, 0x8001, 0, 0, 1, pcpp::SomeIpLayer::MsgType::REQUEST_NO_RETURN, 0, 0, - true, data1, dataLen1); + true, data1, dataLen1); pcpp::Packet someIpTpPacket1(500); PTF_ASSERT_TRUE(someIpTpPacket1.addLayer(ðLayer1)); @@ -273,7 +285,7 @@ PTF_TEST_CASE(SomeIpTpCreationTest) pcpp::IPv4Layer ipLayer2(ipLayer1); pcpp::UdpLayer udpLayer2(udpLayer1); pcpp::SomeIpTpLayer someIpTpLayer2(0xd05f, 0x8001, 0, 0, 1, pcpp::SomeIpLayer::MsgType::REQUEST_NO_RETURN, 0, - 91872 / 16, false, data2, dataLen2); + 91872 / 16, false, data2, dataLen2); pcpp::Packet someIpTpPacket2(500); PTF_ASSERT_TRUE(someIpTpPacket2.addLayer(ðLayer2)); @@ -285,17 +297,17 @@ PTF_TEST_CASE(SomeIpTpCreationTest) PTF_ASSERT_EQUAL(someIpTpPacket2.getRawPacket()->getRawDataLen(), bufferLength2); PTF_ASSERT_BUF_COMPARE(someIpTpPacket2.getRawPacket()->getRawData(), buffer2, bufferLength2); - delete [] buffer1; - delete [] buffer2; + delete[] buffer1; + delete[] buffer2; } PTF_TEST_CASE(SomeIpTpEditTest) { const size_t dataLen2 = 225; - uint8_t data2[dataLen2] = {0}; + uint8_t data2[dataLen2] = { 0 }; pcpp::SomeIpTpLayer someIpTpLayer(0x6059, 0x410c, 0x3, 0xa, 0x5, pcpp::SomeIpLayer::MsgType::REQUEST, 0, 91872 / 16, - true, data2, dataLen2); + true, data2, dataLen2); someIpTpLayer.setOffset(123); PTF_ASSERT_EQUAL(someIpTpLayer.getOffset(), 123); diff --git a/Tests/Packet++Test/Tests/StpTests.cpp b/Tests/Packet++Test/Tests/StpTests.cpp index aa281c3efd..5ab3d5126e 100644 --- a/Tests/Packet++Test/Tests/StpTests.cpp +++ b/Tests/Packet++Test/Tests/StpTests.cpp @@ -16,7 +16,7 @@ PTF_TEST_CASE(StpConfigurationParsingTests) pcpp::Packet stpPacket(&rawPacket1); PTF_ASSERT_TRUE(stpPacket.isPacketOfType(pcpp::STP)); - pcpp::StpConfigurationBPDULayer *stpConfLayer = stpPacket.getLayerOfType(); + pcpp::StpConfigurationBPDULayer* stpConfLayer = stpPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpConfLayer); PTF_ASSERT_NOT_NULL(stpConfLayer->getNextLayer()); @@ -41,8 +41,7 @@ PTF_TEST_CASE(StpConfigurationParsingTests) PTF_ASSERT_EQUAL(stpConfLayer->getForwardDelay(), 15); PTF_ASSERT_EQUAL(stpConfLayer->toString(), "Spanning Tree Configuration"); -} // StpConfigurationParsingTests - +} // StpConfigurationParsingTests PTF_TEST_CASE(StpConfigurationCreationTests) { @@ -54,7 +53,7 @@ PTF_TEST_CASE(StpConfigurationCreationTests) pcpp::Packet stpPacket(&rawPacket1); PTF_ASSERT_TRUE(stpPacket.isPacketOfType(pcpp::STP)); - pcpp::StpConfigurationBPDULayer *stpConfLayerTgt = stpPacket.getLayerOfType(); + pcpp::StpConfigurationBPDULayer* stpConfLayerTgt = stpPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpConfLayerTgt); pcpp::StpConfigurationBPDULayer stpConfLayer; @@ -73,8 +72,7 @@ PTF_TEST_CASE(StpConfigurationCreationTests) stpConfLayer.setForwardDelay(15); PTF_ASSERT_BUF_COMPARE(stpConfLayer.getData(), stpConfLayerTgt->getData(), stpConfLayer.getHeaderLen()); -} // StpConfigurationCreationTests - +} // StpConfigurationCreationTests PTF_TEST_CASE(StpConfigurationEditTests) { @@ -86,7 +84,7 @@ PTF_TEST_CASE(StpConfigurationEditTests) pcpp::Packet stpPacket1(&rawPacket1); PTF_ASSERT_TRUE(stpPacket1.isPacketOfType(pcpp::STP)); - pcpp::StpConfigurationBPDULayer *stpConfLayerOrig = stpPacket1.getLayerOfType(); + pcpp::StpConfigurationBPDULayer* stpConfLayerOrig = stpPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpConfLayerOrig); // Read target packet @@ -94,7 +92,7 @@ PTF_TEST_CASE(StpConfigurationEditTests) pcpp::Packet stpPacket2(&rawPacket2); PTF_ASSERT_TRUE(stpPacket2.isPacketOfType(pcpp::STP)); - pcpp::StpConfigurationBPDULayer *stpConfLayerTgt1 = stpPacket2.getLayerOfType(); + pcpp::StpConfigurationBPDULayer* stpConfLayerTgt1 = stpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpConfLayerTgt1); // Set fields @@ -114,7 +112,7 @@ PTF_TEST_CASE(StpConfigurationEditTests) pcpp::Packet stpPacket3(&rawPacket3); PTF_ASSERT_TRUE(stpPacket3.isPacketOfType(pcpp::STP)); - pcpp::StpConfigurationBPDULayer *stpConfLayerTgt2 = stpPacket3.getLayerOfType(); + pcpp::StpConfigurationBPDULayer* stpConfLayerTgt2 = stpPacket3.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpConfLayerTgt2); // Set fields @@ -127,8 +125,7 @@ PTF_TEST_CASE(StpConfigurationEditTests) stpConfLayerOrig->setBridgeSystemID("FF:EE:DD:CC:BB:AA"); PTF_ASSERT_BUF_COMPARE(stpConfLayerOrig->getData(), stpConfLayerTgt2->getData(), stpConfLayerOrig->getHeaderLen()); -} // StpConfigurationEditTests - +} // StpConfigurationEditTests PTF_TEST_CASE(StpTopologyChangeParsingTests) { @@ -140,7 +137,7 @@ PTF_TEST_CASE(StpTopologyChangeParsingTests) pcpp::Packet stpPacket(&rawPacket1); PTF_ASSERT_TRUE(stpPacket.isPacketOfType(pcpp::STP)); - pcpp::StpTopologyChangeBPDULayer *stpTopologyLayer = stpPacket.getLayerOfType(); + pcpp::StpTopologyChangeBPDULayer* stpTopologyLayer = stpPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpTopologyLayer); PTF_ASSERT_NOT_NULL(stpTopologyLayer->getNextLayer()); @@ -150,8 +147,7 @@ PTF_TEST_CASE(StpTopologyChangeParsingTests) PTF_ASSERT_EQUAL(stpTopologyLayer->getType(), 0x80); PTF_ASSERT_EQUAL(stpTopologyLayer->toString(), "Spanning Tree Topology Change Notification"); -} // StpTopologyChangeParsingTests - +} // StpTopologyChangeParsingTests PTF_TEST_CASE(StpTopologyChangeCreationTests) { @@ -163,14 +159,14 @@ PTF_TEST_CASE(StpTopologyChangeCreationTests) pcpp::Packet stpPacket(&rawPacket1); PTF_ASSERT_TRUE(stpPacket.isPacketOfType(pcpp::STP)); - pcpp::StpTopologyChangeBPDULayer *stpTopologyLayerTgt = stpPacket.getLayerOfType(); + pcpp::StpTopologyChangeBPDULayer* stpTopologyLayerTgt = + stpPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpTopologyLayerTgt); pcpp::StpTopologyChangeBPDULayer stpTopologyLayer; PTF_ASSERT_BUF_COMPARE(stpTopologyLayer.getData(), stpTopologyLayerTgt->getData(), stpTopologyLayer.getHeaderLen()); -} // StpTopologyChangeCreationTests - +} // StpTopologyChangeCreationTests PTF_TEST_CASE(StpTopologyChangeEditTests) { @@ -182,7 +178,8 @@ PTF_TEST_CASE(StpTopologyChangeEditTests) pcpp::Packet stpPacket1(&rawPacket1); PTF_ASSERT_TRUE(stpPacket1.isPacketOfType(pcpp::STP)); - pcpp::StpTopologyChangeBPDULayer *stpTopologyLayerOrig = stpPacket1.getLayerOfType(); + pcpp::StpTopologyChangeBPDULayer* stpTopologyLayerOrig = + stpPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpTopologyLayerOrig); // Read target packet @@ -190,16 +187,17 @@ PTF_TEST_CASE(StpTopologyChangeEditTests) pcpp::Packet stpPacket2(&rawPacket2); PTF_ASSERT_TRUE(stpPacket2.isPacketOfType(pcpp::STP)); - pcpp::StpTopologyChangeBPDULayer *stpTopologyLayerTgt = stpPacket2.getLayerOfType(); + pcpp::StpTopologyChangeBPDULayer* stpTopologyLayerTgt = + stpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpTopologyLayerTgt); // Set fields stpTopologyLayerOrig->setProtoId(0xaa); stpTopologyLayerOrig->setVersion(0x13); - PTF_ASSERT_BUF_COMPARE(stpTopologyLayerOrig->getData(), stpTopologyLayerTgt->getData(), stpTopologyLayerOrig->getHeaderLen()); -} // StpTopologyChangeEditTests - + PTF_ASSERT_BUF_COMPARE(stpTopologyLayerOrig->getData(), stpTopologyLayerTgt->getData(), + stpTopologyLayerOrig->getHeaderLen()); +} // StpTopologyChangeEditTests PTF_TEST_CASE(RapidStpParsingTests) { @@ -211,7 +209,7 @@ PTF_TEST_CASE(RapidStpParsingTests) pcpp::Packet stpPacket(&rawPacket1); PTF_ASSERT_TRUE(stpPacket.isPacketOfType(pcpp::STP)); - pcpp::RapidStpLayer *stpRapidLayer = stpPacket.getLayerOfType(); + pcpp::RapidStpLayer* stpRapidLayer = stpPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpRapidLayer); PTF_ASSERT_NULL(stpRapidLayer->getNextLayer()); @@ -237,8 +235,7 @@ PTF_TEST_CASE(RapidStpParsingTests) PTF_ASSERT_EQUAL(stpRapidLayer->getVersion1Len(), 0); PTF_ASSERT_EQUAL(stpRapidLayer->toString(), "Rapid Spanning Tree"); -} // RapidStpParsingTests - +} // RapidStpParsingTests PTF_TEST_CASE(RapidStpCreationTests) { @@ -250,7 +247,7 @@ PTF_TEST_CASE(RapidStpCreationTests) pcpp::Packet stpPacket(&rawPacket1); PTF_ASSERT_TRUE(stpPacket.isPacketOfType(pcpp::STP)); - pcpp::RapidStpLayer *stpRapidLayerTgt = stpPacket.getLayerOfType(); + pcpp::RapidStpLayer* stpRapidLayerTgt = stpPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpRapidLayerTgt); pcpp::RapidStpLayer stpRapidLayer; @@ -270,8 +267,7 @@ PTF_TEST_CASE(RapidStpCreationTests) stpRapidLayer.setVersion1Len(0); PTF_ASSERT_BUF_COMPARE(stpRapidLayer.getData(), stpRapidLayerTgt->getData(), stpRapidLayer.getHeaderLen()); -} // RapidStpCreationTests - +} // RapidStpCreationTests PTF_TEST_CASE(RapidStpEditTests) { @@ -282,7 +278,7 @@ PTF_TEST_CASE(RapidStpEditTests) pcpp::Packet stpPacket1(&rawPacket1); PTF_ASSERT_TRUE(stpPacket1.isPacketOfType(pcpp::STP)); - pcpp::RapidStpLayer *stpRapidLayerOrig = stpPacket1.getLayerOfType(); + pcpp::RapidStpLayer* stpRapidLayerOrig = stpPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpRapidLayerOrig); // Read target packet @@ -290,7 +286,7 @@ PTF_TEST_CASE(RapidStpEditTests) pcpp::Packet stpPacket2(&rawPacket2); PTF_ASSERT_TRUE(stpPacket2.isPacketOfType(pcpp::STP)); - pcpp::RapidStpLayer *stpRapidLayerTgt = stpPacket2.getLayerOfType(); + pcpp::RapidStpLayer* stpRapidLayerTgt = stpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpRapidLayerTgt); // Set fields @@ -302,8 +298,7 @@ PTF_TEST_CASE(RapidStpEditTests) stpRapidLayerOrig->setVersion1Len(2); PTF_ASSERT_BUF_COMPARE(stpRapidLayerOrig->getData(), stpRapidLayerTgt->getData(), stpRapidLayerTgt->getHeaderLen()); -} // RapidStpEditTests - +} // RapidStpEditTests PTF_TEST_CASE(MultipleStpParsingTests) { @@ -315,7 +310,7 @@ PTF_TEST_CASE(MultipleStpParsingTests) pcpp::Packet stpPacket(&rawPacket1); PTF_ASSERT_TRUE(stpPacket.isPacketOfType(pcpp::STP)); - pcpp::MultipleStpLayer *stpMultipleLayer = stpPacket.getLayerOfType(); + pcpp::MultipleStpLayer* stpMultipleLayer = stpPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpMultipleLayer); PTF_ASSERT_NULL(stpMultipleLayer->getNextLayer()); @@ -353,7 +348,7 @@ PTF_TEST_CASE(MultipleStpParsingTests) PTF_ASSERT_EQUAL(stpMultipleLayer->getNumberOfMSTIConfMessages(), 1); - pcpp::msti_conf_msg *ptrExtension = stpMultipleLayer->getMstiConfMessages(); + pcpp::msti_conf_msg* ptrExtension = stpMultipleLayer->getMstiConfMessages(); PTF_ASSERT_NOT_NULL(ptrExtension); PTF_ASSERT_EQUAL(ptrExtension->flags, 0x7c); @@ -364,8 +359,7 @@ PTF_TEST_CASE(MultipleStpParsingTests) PTF_ASSERT_EQUAL(ptrExtension->remainingHops, 19); PTF_ASSERT_EQUAL(stpMultipleLayer->toString(), "Multiple Spanning Tree"); -} // MultipleStpParsingTests - +} // MultipleStpParsingTests PTF_TEST_CASE(MultipleStpCreationTests) { @@ -377,7 +371,7 @@ PTF_TEST_CASE(MultipleStpCreationTests) pcpp::Packet stpPacket(&rawPacket1); PTF_ASSERT_TRUE(stpPacket.isPacketOfType(pcpp::STP)); - pcpp::MultipleStpLayer *stpMultipleLayerTgt = stpPacket.getLayerOfType(); + pcpp::MultipleStpLayer* stpMultipleLayerTgt = stpPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpMultipleLayerTgt); pcpp::MultipleStpLayer stpMultipleLayer; @@ -406,8 +400,7 @@ PTF_TEST_CASE(MultipleStpCreationTests) PTF_ASSERT_EQUAL(stpMultipleLayer.getDataLen(), stpMultipleLayerTgt->getDataLen()); PTF_ASSERT_BUF_COMPARE(stpMultipleLayer.getData(), stpMultipleLayerTgt->getData(), stpMultipleLayer.getDataLen()); -} // MultipleStpParsingTests - +} // MultipleStpParsingTests PTF_TEST_CASE(MultipleStpEditTests) { @@ -423,10 +416,10 @@ PTF_TEST_CASE(MultipleStpEditTests) pcpp::Packet stpPacket2(&rawPacket2); PTF_ASSERT_TRUE(stpPacket2.isPacketOfType(pcpp::STP)); - pcpp::RapidStpLayer *stpMultipleLayerTgt = stpPacket2.getLayerOfType(); + pcpp::RapidStpLayer* stpMultipleLayerTgt = stpPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpMultipleLayerTgt); - pcpp::MultipleStpLayer *stpMultipleLayerOrig = stpPacket1.getLayerOfType(); + pcpp::MultipleStpLayer* stpMultipleLayerOrig = stpPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpMultipleLayerOrig); // Set fields @@ -440,13 +433,15 @@ PTF_TEST_CASE(MultipleStpEditTests) stpMultipleLayerOrig->setRemainingHopCount(17); PTF_ASSERT_EQUAL(stpMultipleLayerOrig->getDataLen(), stpMultipleLayerTgt->getDataLen()); - PTF_ASSERT_BUF_COMPARE(stpMultipleLayerOrig->getData(), stpMultipleLayerTgt->getData(), stpMultipleLayerTgt->getDataLen()); + PTF_ASSERT_BUF_COMPARE(stpMultipleLayerOrig->getData(), stpMultipleLayerTgt->getData(), + stpMultipleLayerTgt->getDataLen()); READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/StpMultipleEdit2.dat"); pcpp::Packet stpPacket3(&rawPacket3); PTF_ASSERT_TRUE(stpPacket3.isPacketOfType(pcpp::STP)); - pcpp::StpConfigurationBPDULayer *stpMultipleLayerTgt2 = stpPacket3.getLayerOfType(); + pcpp::StpConfigurationBPDULayer* stpMultipleLayerTgt2 = + stpPacket3.getLayerOfType(); PTF_ASSERT_NOT_NULL(stpMultipleLayerTgt2); stpMultipleLayerOrig->setCISTBridgePriority(24576); @@ -454,5 +449,6 @@ PTF_TEST_CASE(MultipleStpEditTests) stpMultipleLayerOrig->setCISTBridgeSystemID("FF:EE:DD:CC:BB:AA"); PTF_ASSERT_EQUAL(stpMultipleLayerOrig->getDataLen(), stpMultipleLayerTgt2->getDataLen()); - PTF_ASSERT_BUF_COMPARE(stpMultipleLayerOrig->getData(), stpMultipleLayerTgt2->getData(), stpMultipleLayerTgt2->getDataLen()); -} // MultipleStpEditTests + PTF_ASSERT_BUF_COMPARE(stpMultipleLayerOrig->getData(), stpMultipleLayerTgt2->getData(), + stpMultipleLayerTgt2->getDataLen()); +} // MultipleStpEditTests diff --git a/Tests/Packet++Test/Tests/TcpTests.cpp b/Tests/Packet++Test/Tests/TcpTests.cpp index f50e28cd12..bafea1907a 100644 --- a/Tests/Packet++Test/Tests/TcpTests.cpp +++ b/Tests/Packet++Test/Tests/TcpTests.cpp @@ -14,7 +14,6 @@ DISABLE_WARNING_PUSH DISABLE_WARNING_DEPRECATED - PTF_TEST_CASE(TcpPacketNoOptionsParsing) { timeval time; @@ -51,10 +50,10 @@ PTF_TEST_CASE(TcpPacketNoOptionsParsing) // TCP options PTF_ASSERT_EQUAL(tcpLayer->getTcpOptionCount(), 0); - //TODO: remove deprecated + // TODO: remove deprecated PTF_ASSERT_TRUE(tcpLayer->getTcpOption(pcpp::PCPP_TCPOPT_NOP).isNull()); PTF_ASSERT_TRUE(tcpLayer->getTcpOption(pcpp::PCPP_TCPOPT_TIMESTAMP).isNull()); - //end deprecated + // end deprecated PTF_ASSERT_TRUE(tcpLayer->getTcpOption(pcpp::TcpOptionEnumType::Nop).isNull()); PTF_ASSERT_TRUE(tcpLayer->getTcpOption(pcpp::TcpOptionEnumType::Timestamp).isNull()); @@ -62,9 +61,7 @@ PTF_TEST_CASE(TcpPacketNoOptionsParsing) pcpp::Layer* afterTcpLayer = tcpLayer->getNextLayer(); PTF_ASSERT_NOT_NULL(afterTcpLayer); PTF_ASSERT_EQUAL(afterTcpLayer->getProtocol(), pcpp::HTTPResponse, enum); -} // TcpPacketNoOptionsParsing - - +} // TcpPacketNoOptionsParsing PTF_TEST_CASE(TcpPacketWithOptionsParsing) { @@ -90,7 +87,7 @@ PTF_TEST_CASE(TcpPacketWithOptionsParsing) // TCP options PTF_ASSERT_EQUAL(tcpLayer->getTcpOptionCount(), 3); - //TODO: remove deprecated + // TODO: remove deprecated PTF_ASSERT_TRUE(!tcpLayer->getTcpOption(pcpp::PCPP_TCPOPT_NOP).isNull()); pcpp::TcpOption timestampOptionData = tcpLayer->getTcpOption(pcpp::PCPP_TCPOPT_TIMESTAMP); PTF_ASSERT_TRUE(!timestampOptionData.isNull()); @@ -99,7 +96,7 @@ PTF_TEST_CASE(TcpPacketWithOptionsParsing) uint32_t tsEchoReply = timestampOptionData.getValueAs(4); PTF_ASSERT_EQUAL(tsValue, htobe32(195102)); PTF_ASSERT_EQUAL(tsEchoReply, htobe32(3555729271UL)); - //end deprecated + // end deprecated PTF_ASSERT_TRUE(!tcpLayer->getTcpOption(pcpp::TcpOptionEnumType::Nop).isNull()); pcpp::TcpOption timestampOptionData2 = tcpLayer->getTcpOption(pcpp::TcpOptionEnumType::Timestamp); @@ -109,7 +106,7 @@ PTF_TEST_CASE(TcpPacketWithOptionsParsing) uint32_t tsEchoReply2 = timestampOptionData2.getValueAs(4); PTF_ASSERT_EQUAL(tsValue2, htobe32(195102)); PTF_ASSERT_EQUAL(tsEchoReply2, htobe32(3555729271UL)); -} // TcpPacketWithOptionsParsing +} // TcpPacketWithOptionsParsing PTF_TEST_CASE(TcpPacketWithOptionsParsing2) { @@ -125,7 +122,7 @@ PTF_TEST_CASE(TcpPacketWithOptionsParsing2) PTF_ASSERT_EQUAL(tcpLayer->getTcpOptionCount(), 5); - //TODO: remove deprecated + // TODO: remove deprecated pcpp::TcpOption mssOption = tcpLayer->getTcpOption(pcpp::TCPOPT_MSS); pcpp::TcpOption sackPermOption = tcpLayer->getTcpOption(pcpp::TCPOPT_SACK_PERM); pcpp::TcpOption windowScaleOption = tcpLayer->getTcpOption(pcpp::PCPP_TCPOPT_WINDOW); @@ -146,7 +143,7 @@ PTF_TEST_CASE(TcpPacketWithOptionsParsing2) PTF_ASSERT_EQUAL(sackPermOption.getValueAs(), 0); PTF_ASSERT_EQUAL(mssOption.getValueAs(), 0); PTF_ASSERT_EQUAL(mssOption.getValueAs(1), 0); - //end deprecated + // end deprecated pcpp::TcpOption mssOption2 = tcpLayer->getTcpOption(pcpp::TcpOptionEnumType::Mss); pcpp::TcpOption sackPermOption2 = tcpLayer->getTcpOption(pcpp::TcpOptionEnumType::SackPerm); @@ -169,7 +166,7 @@ PTF_TEST_CASE(TcpPacketWithOptionsParsing2) PTF_ASSERT_EQUAL(mssOption2.getValueAs(), 0); PTF_ASSERT_EQUAL(mssOption2.getValueAs(1), 0); - //TODO: remove deprecated + // TODO: remove deprecated pcpp::TcpOption curOpt = tcpLayer->getFirstTcpOption(); PTF_ASSERT_TRUE(curOpt.isNotNull() && curOpt.getTcpOptionType() == pcpp::TCPOPT_MSS); curOpt = tcpLayer->getNextTcpOption(curOpt); @@ -180,7 +177,7 @@ PTF_TEST_CASE(TcpPacketWithOptionsParsing2) PTF_ASSERT_TRUE(curOpt.isNotNull() && curOpt.getTcpOptionType() == pcpp::PCPP_TCPOPT_NOP); curOpt = tcpLayer->getNextTcpOption(curOpt); PTF_ASSERT_TRUE(curOpt.isNotNull() && curOpt.getTcpOptionType() == pcpp::PCPP_TCPOPT_WINDOW); - //end deprecated + // end deprecated curOpt = tcpLayer->getFirstTcpOption(); PTF_ASSERT_TRUE(curOpt.isNotNull() && curOpt.getTcpOptionEnumType() == pcpp::TcpOptionEnumType::Mss); @@ -194,9 +191,7 @@ PTF_TEST_CASE(TcpPacketWithOptionsParsing2) PTF_ASSERT_TRUE(curOpt.isNotNull() && curOpt.getTcpOptionEnumType() == pcpp::TcpOptionEnumType::Window); curOpt = tcpLayer->getNextTcpOption(curOpt); PTF_ASSERT_TRUE(curOpt.isNull()); -} // TcpPacketWithOptionsParsing2 - - +} // TcpPacketWithOptionsParsing2 PTF_TEST_CASE(TcpMalformedPacketParsing) { @@ -209,7 +204,7 @@ PTF_TEST_CASE(TcpMalformedPacketParsing) PTF_ASSERT_NOT_NULL(badTcpPacket.getLayerOfType()); PTF_ASSERT_NULL(badTcpPacket.getLayerOfType()); -} // TcpMalformedPacketParsing +} // TcpMalformedPacketParsing PTF_TEST_CASE(TcpPacketCreation) { @@ -232,11 +227,16 @@ PTF_TEST_CASE(TcpPacketCreation) PTF_ASSERT_EQUAL(tcpLayer.getHeaderLen(), 24); PTF_ASSERT_TRUE(tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NOP)).isNotNull()); PTF_ASSERT_EQUAL(tcpLayer.getHeaderLen(), 24); - PTF_ASSERT_TRUE(tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::PCPP_TCPOPT_TIMESTAMP, nullptr, PCPP_TCPOLEN_TIMESTAMP-2)).isNotNull()); + PTF_ASSERT_TRUE( + tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::PCPP_TCPOPT_TIMESTAMP, nullptr, PCPP_TCPOLEN_TIMESTAMP - 2)) + .isNotNull()); PTF_ASSERT_EQUAL(tcpLayer.getHeaderLen(), 32); - PTF_ASSERT_TRUE(tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NopEolOptionEnumType::Nop)).isNotNull()); - PTF_ASSERT_TRUE(tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionEnumType::Window, nullptr, PCPP_TCPOLEN_WINDOW-2)).isNotNull()); + PTF_ASSERT_TRUE( + tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NopEolOptionEnumType::Nop)).isNotNull()); + PTF_ASSERT_TRUE( + tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionEnumType::Window, nullptr, PCPP_TCPOLEN_WINDOW - 2)) + .isNotNull()); PTF_ASSERT_EQUAL(tcpLayer.getHeaderLen(), 36); PTF_ASSERT_EQUAL(tcpLayer.getTcpOptionCount(), 5); @@ -269,10 +269,8 @@ PTF_TEST_CASE(TcpPacketCreation) PTF_ASSERT_BUF_COMPARE(tcpPacket.getRawPacket()->getRawData(), buffer1, bufferLength1); - delete [] buffer1; -} // TcpPacketCreation - - + delete[] buffer1; +} // TcpPacketCreation PTF_TEST_CASE(TcpPacketCreation2) { @@ -297,17 +295,21 @@ PTF_TEST_CASE(TcpPacketCreation2) PTF_ASSERT_TRUE(tcpLayer.addTcpOptionAfter(pcpp::TcpOptionBuilder(pcpp::TCPOPT_MSS, (uint16_t)1460)).isNotNull()); PTF_ASSERT_EQUAL(tcpLayer.getHeaderLen(), 28); - pcpp::TcpOption tsOption = tcpLayer.addTcpOptionAfter(pcpp::TcpOptionBuilder(pcpp::PCPP_TCPOPT_TIMESTAMP, nullptr, PCPP_TCPOLEN_TIMESTAMP-2), pcpp::TCPOPT_MSS); + pcpp::TcpOption tsOption = tcpLayer.addTcpOptionAfter( + pcpp::TcpOptionBuilder(pcpp::PCPP_TCPOPT_TIMESTAMP, nullptr, PCPP_TCPOLEN_TIMESTAMP - 2), pcpp::TCPOPT_MSS); PTF_ASSERT_TRUE(tsOption.isNotNull()); tsOption.setValue(htobe32(197364)); tsOption.setValue(0, 4); PTF_ASSERT_EQUAL(tcpLayer.getHeaderLen(), 36); - pcpp::TcpOption winScaleOption = tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::PCPP_TCPOPT_WINDOW, (uint8_t)4)); + pcpp::TcpOption winScaleOption = + tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::PCPP_TCPOPT_WINDOW, (uint8_t)4)); PTF_ASSERT_TRUE(winScaleOption.isNotNull()); PTF_ASSERT_EQUAL(tcpLayer.getHeaderLen(), 40); - PTF_ASSERT_TRUE(tcpLayer.addTcpOptionAfter(pcpp::TcpOptionBuilder(pcpp::TCPOPT_SACK_PERM, nullptr, 0), pcpp::TCPOPT_MSS).isNotNull()); + PTF_ASSERT_TRUE( + tcpLayer.addTcpOptionAfter(pcpp::TcpOptionBuilder(pcpp::TCPOPT_SACK_PERM, nullptr, 0), pcpp::TCPOPT_MSS) + .isNotNull()); PTF_ASSERT_EQUAL(tcpLayer.getHeaderLen(), 40); PTF_ASSERT_EQUAL(tcpLayer.getTcpOptionCount(), 5); @@ -325,11 +327,18 @@ PTF_TEST_CASE(TcpPacketCreation2) PTF_ASSERT_BUF_COMPARE(tcpPacket.getRawPacket()->getRawData(), buffer1, bufferLength1); - pcpp::TcpOption qsOption = tcpLayer.addTcpOptionAfter(pcpp::TcpOptionBuilder(pcpp::TCPOPT_QS, nullptr, PCPP_TCPOLEN_QS), pcpp::TCPOPT_MSS); + pcpp::TcpOption qsOption = + tcpLayer.addTcpOptionAfter(pcpp::TcpOptionBuilder(pcpp::TCPOPT_QS, nullptr, PCPP_TCPOLEN_QS), pcpp::TCPOPT_MSS); PTF_ASSERT_TRUE(qsOption.isNotNull()); PTF_ASSERT_TRUE(qsOption.setValue(htobe32(9999))); - PTF_ASSERT_TRUE(tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionEnumType::Snack, static_cast(htobe32(1000)))).isNotNull()); - PTF_ASSERT_TRUE(tcpLayer.insertTcpOptionAfter(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NopEolOptionEnumType::Nop), pcpp::TcpOptionEnumType::Timestamp).isNotNull()); + PTF_ASSERT_TRUE( + tcpLayer + .addTcpOption(pcpp::TcpOptionBuilder(pcpp::TcpOptionEnumType::Snack, static_cast(htobe32(1000)))) + .isNotNull()); + PTF_ASSERT_TRUE(tcpLayer + .insertTcpOptionAfter(pcpp::TcpOptionBuilder(pcpp::TcpOptionBuilder::NopEolOptionEnumType::Nop), + pcpp::TcpOptionEnumType::Timestamp) + .isNotNull()); PTF_ASSERT_EQUAL(tcpLayer.getTcpOptionCount(), 8); @@ -341,7 +350,7 @@ PTF_TEST_CASE(TcpPacketCreation2) PTF_ASSERT_BUF_COMPARE(tcpPacket.getRawPacket()->getRawData(), buffer1, bufferLength1); - delete [] buffer1; + delete[] buffer1; PTF_ASSERT_TRUE(tcpLayer.removeAllTcpOptions()); PTF_ASSERT_EQUAL(tcpLayer.getTcpOptionCount(), 0); @@ -349,14 +358,15 @@ PTF_TEST_CASE(TcpPacketCreation2) PTF_ASSERT_EQUAL(tcpLayer.getHeaderLen(), 20); PTF_ASSERT_TRUE(tcpLayer.getTcpOption(pcpp::PCPP_TCPOPT_TIMESTAMP).isNull()); - pcpp::TcpOption tcpSnackOption = tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TCPOPT_SNACK, nullptr, PCPP_TCPOLEN_SNACK)); + pcpp::TcpOption tcpSnackOption = + tcpLayer.addTcpOption(pcpp::TcpOptionBuilder(pcpp::TCPOPT_SNACK, nullptr, PCPP_TCPOLEN_SNACK)); PTF_ASSERT_TRUE(tcpSnackOption.isNotNull()); PTF_ASSERT_TRUE(tcpSnackOption.setValue(htobe32(1000))); -} // TcpPacketCreation2 +} // TcpPacketCreation2 PTF_TEST_CASE(TcpChecksumInvalidRead) { - uint8_t *m = new uint8_t[3]; + uint8_t* m = new uint8_t[3]; m[0] = 0x01; m[1] = 0x12; m[2] = 0xF3; @@ -368,15 +378,15 @@ PTF_TEST_CASE(TcpChecksumInvalidRead) uint16_t c = pcpp::computeChecksum(vec, 1); PTF_ASSERT_EQUAL(c, 0xbedU); - delete [] m; -} // TcpChecksumInvalidRead + delete[] m; +} // TcpChecksumInvalidRead PTF_TEST_CASE(TcpChecksumMultiBuffer) { // Taken from https://en.wikipedia.org/wiki/IPv4_header_checksum#Calculating_the_IPv4_header_checksum - uint16_t m[4] = {0x4500, 0x0073, 0x0000, 0x4000}; - uint16_t n[3] = {0x4011, 0xc0a8, 0x0001}; - uint16_t o[2] = {0xc0a8, 0x00c7}; + uint16_t m[4] = { 0x4500, 0x0073, 0x0000, 0x4000 }; + uint16_t n[3] = { 0x4011, 0xc0a8, 0x0001 }; + uint16_t o[2] = { 0xc0a8, 0x00c7 }; uint16_t checksum_expected = 0xb861; pcpp::ScalarBuffer vec[4]; @@ -396,5 +406,5 @@ PTF_TEST_CASE(TcpChecksumMultiBuffer) // Adding the checksum should be equal to 0x0 c = pcpp::computeChecksum(vec, 4); PTF_ASSERT_EQUAL(c, 0); -} // TcpChecksumInvalidRead +} // TcpChecksumInvalidRead DISABLE_WARNING_POP diff --git a/Tests/Packet++Test/Tests/TelnetTests.cpp b/Tests/Packet++Test/Tests/TelnetTests.cpp index 58b95fe24e..5ddb8f3520 100644 --- a/Tests/Packet++Test/Tests/TelnetTests.cpp +++ b/Tests/Packet++Test/Tests/TelnetTests.cpp @@ -17,7 +17,7 @@ PTF_TEST_CASE(TelnetCommandParsingTests) READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/telnetCommand.dat"); pcpp::Packet telnetPacket(&rawPacket1); - pcpp::TelnetLayer *telnetLayer = telnetPacket.getLayerOfType(); + pcpp::TelnetLayer* telnetLayer = telnetPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(telnetLayer); @@ -31,38 +31,35 @@ PTF_TEST_CASE(TelnetCommandParsingTests) PTF_ASSERT_EQUAL(telnetLayer->getFirstCommand(), pcpp::TelnetLayer::TelnetCommand::WillPerform, enumclass); PTF_ASSERT_EQUAL(telnetLayer->getOption(pcpp::TelnetLayer::TelnetCommand::WillPerform), - pcpp::TelnetLayer::TelnetOption::SuppressGoAhead, enumclass); + pcpp::TelnetLayer::TelnetOption::SuppressGoAhead, enumclass); PTF_ASSERT_EQUAL(telnetLayer->getOption(pcpp::TelnetLayer::TelnetCommand::DoPerform), - pcpp::TelnetLayer::TelnetOption::TerminalType, enumclass); + pcpp::TelnetLayer::TelnetOption::TerminalType, enumclass); PTF_ASSERT_EQUAL(telnetLayer->getOption(pcpp::TelnetLayer::TelnetCommand::AreYouThere), - pcpp::TelnetLayer::TelnetOption::TelnetOptionNoOption, enumclass); + pcpp::TelnetLayer::TelnetOption::TelnetOptionNoOption, enumclass); // Check iteration std::vector vCommand = { - pcpp::TelnetLayer::TelnetCommand::WillPerform, - pcpp::TelnetLayer::TelnetCommand::DoPerform, - pcpp::TelnetLayer::TelnetCommand::DoPerform, - pcpp::TelnetLayer::TelnetCommand::DoPerform, - pcpp::TelnetLayer::TelnetCommand::DoPerform, - pcpp::TelnetLayer::TelnetCommand::DoPerform, - pcpp::TelnetLayer::TelnetCommand::Subnegotiation, - pcpp::TelnetLayer::TelnetCommand::SubnegotiationEnd}; - - std::vector vOptions = { - pcpp::TelnetLayer::TelnetOption::SuppressGoAhead, - pcpp::TelnetLayer::TelnetOption::TerminalType, - pcpp::TelnetLayer::TelnetOption::NegotiateAboutWindowSize, - pcpp::TelnetLayer::TelnetOption::TerminalSpeed, - pcpp::TelnetLayer::TelnetOption::RemoteFlowControl, - pcpp::TelnetLayer::TelnetOption::Linemode, - pcpp::TelnetLayer::TelnetOption::Linemode, - pcpp::TelnetLayer::TelnetOption::TelnetOptionNoOption}; - - std::vector vCommandString = {"Will Perform", "Do Perform", "Do Perform", "Do Perform", - "Do Perform", "Do Perform", "Subnegotiation", "Subnegotiation End"}; + pcpp::TelnetLayer::TelnetCommand::WillPerform, pcpp::TelnetLayer::TelnetCommand::DoPerform, + pcpp::TelnetLayer::TelnetCommand::DoPerform, pcpp::TelnetLayer::TelnetCommand::DoPerform, + pcpp::TelnetLayer::TelnetCommand::DoPerform, pcpp::TelnetLayer::TelnetCommand::DoPerform, + pcpp::TelnetLayer::TelnetCommand::Subnegotiation, pcpp::TelnetLayer::TelnetCommand::SubnegotiationEnd + }; + + std::vector vOptions = { pcpp::TelnetLayer::TelnetOption::SuppressGoAhead, + pcpp::TelnetLayer::TelnetOption::TerminalType, + pcpp::TelnetLayer::TelnetOption::NegotiateAboutWindowSize, + pcpp::TelnetLayer::TelnetOption::TerminalSpeed, + pcpp::TelnetLayer::TelnetOption::RemoteFlowControl, + pcpp::TelnetLayer::TelnetOption::Linemode, + pcpp::TelnetLayer::TelnetOption::Linemode, + pcpp::TelnetLayer::TelnetOption::TelnetOptionNoOption }; + + std::vector vCommandString = { "Will Perform", "Do Perform", "Do Perform", "Do Perform", + "Do Perform", "Do Perform", "Subnegotiation", "Subnegotiation End" }; std::vector vOptionString = { "Suppress Go Ahead", "Terminal Type", "Negotiate About Window Size", "Terminal Speed", "Remote Flow Control", - "Line mode", "Line mode", "No option for this command"}; + "Line mode", "Line mode", "No option for this command" + }; size_t ctr = 0; size_t length = 0; @@ -100,7 +97,7 @@ PTF_TEST_CASE(TelnetCommandParsingTests) READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/telnetTN3270.dat"); pcpp::Packet telnetPacket2(&rawPacket2); - pcpp::TelnetLayer *telnetLayer2 = telnetPacket2.getLayerOfType(); + pcpp::TelnetLayer* telnetLayer2 = telnetPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(telnetLayer2); @@ -108,15 +105,13 @@ PTF_TEST_CASE(TelnetCommandParsingTests) PTF_ASSERT_EQUAL(telnetLayer2->getDataAsString(), "@"); PTF_ASSERT_EQUAL(telnetLayer2->getTotalNumberOfCommands(), 3); - std::vector vCommand2 = { - pcpp::TelnetLayer::TelnetCommand::DoPerform, - pcpp::TelnetLayer::TelnetCommand::WillPerform, - pcpp::TelnetLayer::TelnetCommand::EndOfRecordCommand}; + std::vector vCommand2 = { pcpp::TelnetLayer::TelnetCommand::DoPerform, + pcpp::TelnetLayer::TelnetCommand::WillPerform, + pcpp::TelnetLayer::TelnetCommand::EndOfRecordCommand }; - std::vector vOptions2 = { - pcpp::TelnetLayer::TelnetOption::TransmitBinary, - pcpp::TelnetLayer::TelnetOption::TransmitBinary, - pcpp::TelnetLayer::TelnetOption::TelnetOptionNoOption}; + std::vector vOptions2 = { pcpp::TelnetLayer::TelnetOption::TransmitBinary, + pcpp::TelnetLayer::TelnetOption::TransmitBinary, + pcpp::TelnetLayer::TelnetOption::TelnetOptionNoOption }; size_t ctr2 = 0; size_t length2 = 0; @@ -140,117 +135,119 @@ PTF_TEST_CASE(TelnetCommandParsingTests) READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/telnetCommandWithData.dat"); pcpp::Packet telnetPacket3(&rawPacket3); - pcpp::TelnetLayer *telnetLayer3 = telnetPacket3.getLayerOfType(); + pcpp::TelnetLayer* telnetLayer3 = telnetPacket3.getLayerOfType(); PTF_ASSERT_NOT_NULL(telnetLayer3); PTF_ASSERT_EQUAL(telnetLayer3->getDataAsString(), - "Telnet server could not log you in using NTLM authentication.Your password may have " - "expired.Login using username and passwordWelcome to Microsoft Telnet Service login: "); + "Telnet server could not log you in using NTLM authentication.Your password may have " + "expired.Login using username and passwordWelcome to Microsoft Telnet Service login: "); PTF_ASSERT_EQUAL(telnetLayer3->getTotalNumberOfCommands(), 2); PTF_ASSERT_EQUAL(telnetLayer3->getNumberOfCommands(pcpp::TelnetLayer::TelnetCommand::Subnegotiation), 1); PTF_ASSERT_EQUAL(telnetLayer3->getNumberOfCommands(pcpp::TelnetLayer::TelnetCommand::SubnegotiationEnd), 1); PTF_ASSERT_EQUAL(telnetLayer3->getOption(pcpp::TelnetLayer::TelnetCommand::Subnegotiation), - pcpp::TelnetLayer::TelnetOption::AuthenticationOption, enumclass); + pcpp::TelnetLayer::TelnetOption::AuthenticationOption, enumclass); PTF_ASSERT_EQUAL(telnetLayer3->getOption(pcpp::TelnetLayer::TelnetCommand::SubnegotiationEnd), - pcpp::TelnetLayer::TelnetOption::TelnetOptionNoOption, enumclass); + pcpp::TelnetLayer::TelnetOption::TelnetOptionNoOption, enumclass); PTF_ASSERT_EQUAL(telnetLayer3->toString(), "Telnet Control"); // Commands std::vector> possibleCommands = { - {static_cast(0), "Unknown Command"}, - {pcpp::TelnetLayer::TelnetCommand::TelnetCommandEndOfPacket, "Reached end of packet while parsing"}, - {pcpp::TelnetLayer::TelnetCommand::EndOfFile, "End of File"}, - {pcpp::TelnetLayer::TelnetCommand::Suspend, "Suspend current process"}, - {pcpp::TelnetLayer::TelnetCommand::Abort, "Abort Process"}, - {pcpp::TelnetLayer::TelnetCommand::EndOfRecordCommand, "End of Record"}, - {pcpp::TelnetLayer::TelnetCommand::SubnegotiationEnd, "Subnegotiation End"}, - {pcpp::TelnetLayer::TelnetCommand::NoOperation, "No Operation"}, - {pcpp::TelnetLayer::TelnetCommand::DataMark, "Data Mark"}, - {pcpp::TelnetLayer::TelnetCommand::Break, "Break"}, - {pcpp::TelnetLayer::TelnetCommand::InterruptProcess, "Interrupt Process"}, - {pcpp::TelnetLayer::TelnetCommand::AbortOutput, "Abort Output"}, - {pcpp::TelnetLayer::TelnetCommand::AreYouThere, "Are You There"}, - {pcpp::TelnetLayer::TelnetCommand::EraseCharacter, "Erase Character"}, - {pcpp::TelnetLayer::TelnetCommand::EraseLine, "Erase Line"}, - {pcpp::TelnetLayer::TelnetCommand::GoAhead, "Go Ahead"}, - {pcpp::TelnetLayer::TelnetCommand::Subnegotiation, "Subnegotiation"}, - {pcpp::TelnetLayer::TelnetCommand::WillPerform, "Will Perform"}, - {pcpp::TelnetLayer::TelnetCommand::WontPerform, "Wont Perform"}, - {pcpp::TelnetLayer::TelnetCommand::DoPerform, "Do Perform"}, - {pcpp::TelnetLayer::TelnetCommand::DontPerform, "Dont Perform"}, - {pcpp::TelnetLayer::TelnetCommand::InterpretAsCommand, "Interpret As Command"}}; - - for (const auto &entry : possibleCommands) + { static_cast(0), "Unknown Command" }, + { pcpp::TelnetLayer::TelnetCommand::TelnetCommandEndOfPacket, "Reached end of packet while parsing" }, + { pcpp::TelnetLayer::TelnetCommand::EndOfFile, "End of File" }, + { pcpp::TelnetLayer::TelnetCommand::Suspend, "Suspend current process" }, + { pcpp::TelnetLayer::TelnetCommand::Abort, "Abort Process" }, + { pcpp::TelnetLayer::TelnetCommand::EndOfRecordCommand, "End of Record" }, + { pcpp::TelnetLayer::TelnetCommand::SubnegotiationEnd, "Subnegotiation End" }, + { pcpp::TelnetLayer::TelnetCommand::NoOperation, "No Operation" }, + { pcpp::TelnetLayer::TelnetCommand::DataMark, "Data Mark" }, + { pcpp::TelnetLayer::TelnetCommand::Break, "Break" }, + { pcpp::TelnetLayer::TelnetCommand::InterruptProcess, "Interrupt Process" }, + { pcpp::TelnetLayer::TelnetCommand::AbortOutput, "Abort Output" }, + { pcpp::TelnetLayer::TelnetCommand::AreYouThere, "Are You There" }, + { pcpp::TelnetLayer::TelnetCommand::EraseCharacter, "Erase Character" }, + { pcpp::TelnetLayer::TelnetCommand::EraseLine, "Erase Line" }, + { pcpp::TelnetLayer::TelnetCommand::GoAhead, "Go Ahead" }, + { pcpp::TelnetLayer::TelnetCommand::Subnegotiation, "Subnegotiation" }, + { pcpp::TelnetLayer::TelnetCommand::WillPerform, "Will Perform" }, + { pcpp::TelnetLayer::TelnetCommand::WontPerform, "Wont Perform" }, + { pcpp::TelnetLayer::TelnetCommand::DoPerform, "Do Perform" }, + { pcpp::TelnetLayer::TelnetCommand::DontPerform, "Dont Perform" }, + { pcpp::TelnetLayer::TelnetCommand::InterpretAsCommand, "Interpret As Command" } + }; + + for (const auto& entry : possibleCommands) { PTF_ASSERT_EQUAL(pcpp::TelnetLayer::getTelnetCommandAsString(entry.first), entry.second); } // Options std::vector> possibleOptions = { - {static_cast(-10), "Unknown Option"}, - {pcpp::TelnetLayer::TelnetOption::TelnetOptionNoOption, "No option for this command"}, - {pcpp::TelnetLayer::TelnetOption::TransmitBinary, "Binary Transmission"}, - {pcpp::TelnetLayer::TelnetOption::Echo, "Echo"}, - {pcpp::TelnetLayer::TelnetOption::Reconnection, "Reconnection"}, - {pcpp::TelnetLayer::TelnetOption::SuppressGoAhead, "Suppress Go Ahead"}, - {pcpp::TelnetLayer::TelnetOption::ApproxMsgSizeNegotiation, "Negotiate approximate message size"}, - {pcpp::TelnetLayer::TelnetOption::Status, "Status"}, - {pcpp::TelnetLayer::TelnetOption::TimingMark, "Timing Mark"}, - {pcpp::TelnetLayer::TelnetOption::RemoteControlledTransAndEcho, "Remote Controlled Transmission and Echo"}, - {pcpp::TelnetLayer::TelnetOption::OutputLineWidth, "Output Line Width"}, - {pcpp::TelnetLayer::TelnetOption::OutputPageSize, "Output Page Size"}, - {pcpp::TelnetLayer::TelnetOption::OutputCarriageReturnDisposition, - "Negotiate About Output Carriage-Return Disposition"}, - {pcpp::TelnetLayer::TelnetOption::OutputHorizontalTabStops, "Negotiate About Output Horizontal Tabstops"}, - {pcpp::TelnetLayer::TelnetOption::OutputHorizontalTabDisposition, - "Negotiate About Output Horizontal Tab Disposition"}, - {pcpp::TelnetLayer::TelnetOption::OutputFormfeedDisposition, "Negotiate About Output Formfeed Disposition"}, - {pcpp::TelnetLayer::TelnetOption::OutputVerticalTabStops, "Negotiate About Vertical Tabstops"}, - {pcpp::TelnetLayer::TelnetOption::OutputVerticalTabDisposition, - "Negotiate About Output Vertcial Tab Disposition"}, - {pcpp::TelnetLayer::TelnetOption::OutputLinefeedDisposition, "Negotiate About Output Linefeed Disposition"}, - {pcpp::TelnetLayer::TelnetOption::ExtendedASCII, "Extended ASCII"}, - {pcpp::TelnetLayer::TelnetOption::Logout, "Logout"}, - {pcpp::TelnetLayer::TelnetOption::ByteMacro, "Byte Macro"}, - {pcpp::TelnetLayer::TelnetOption::DataEntryTerminal, "Data Entry Terminal"}, - {pcpp::TelnetLayer::TelnetOption::SUPDUP, "SUPDUP"}, - {pcpp::TelnetLayer::TelnetOption::SUPDUPOutput, "SUPDUP Output"}, - {pcpp::TelnetLayer::TelnetOption::SendLocation, "Send Location"}, - {pcpp::TelnetLayer::TelnetOption::TerminalType, "Terminal Type"}, - {pcpp::TelnetLayer::TelnetOption::EndOfRecordOption, "End Of Record"}, - {pcpp::TelnetLayer::TelnetOption::TACACSUserIdentification, "TACACS User Identification"}, - {pcpp::TelnetLayer::TelnetOption::OutputMarking, "Output Marking"}, - {pcpp::TelnetLayer::TelnetOption::TerminalLocationNumber, "Terminal Location Number"}, - {pcpp::TelnetLayer::TelnetOption::Telnet3270Regime, "Telnet 3270 Regime"}, - {pcpp::TelnetLayer::TelnetOption::X3Pad, "X3 Pad"}, - {pcpp::TelnetLayer::TelnetOption::NegotiateAboutWindowSize, "Negotiate About Window Size"}, - {pcpp::TelnetLayer::TelnetOption::TerminalSpeed, "Terminal Speed"}, - {pcpp::TelnetLayer::TelnetOption::RemoteFlowControl, "Remote Flow Control"}, - {pcpp::TelnetLayer::TelnetOption::Linemode, "Line mode"}, - {pcpp::TelnetLayer::TelnetOption::XDisplayLocation, "X Display Location"}, - {pcpp::TelnetLayer::TelnetOption::EnvironmentOption, "Environment Option"}, - {pcpp::TelnetLayer::TelnetOption::AuthenticationOption, "Authentication Option"}, - {pcpp::TelnetLayer::TelnetOption::EncryptionOption, "Encryption Option"}, - {pcpp::TelnetLayer::TelnetOption::NewEnvironmentOption, "New Environment Option"}, - {pcpp::TelnetLayer::TelnetOption::TN3270E, "TN3270E"}, - {pcpp::TelnetLayer::TelnetOption::XAuth, "X Server Authentication"}, - {pcpp::TelnetLayer::TelnetOption::Charset, "Charset"}, - {pcpp::TelnetLayer::TelnetOption::TelnetRemoteSerialPort, "Telnet Remote Serial Port"}, - {pcpp::TelnetLayer::TelnetOption::ComPortControlOption, "Com Port Control Option"}, - {pcpp::TelnetLayer::TelnetOption::TelnetSuppressLocalEcho, "Telnet Suppress Local Echo"}, - {pcpp::TelnetLayer::TelnetOption::TelnetStartTLS, "Telnet Start TLS"}, - {pcpp::TelnetLayer::TelnetOption::Kermit, "Kermit"}, - {pcpp::TelnetLayer::TelnetOption::SendURL, "Send URL"}, - {pcpp::TelnetLayer::TelnetOption::ForwardX, "Forward X Server"}, - {pcpp::TelnetLayer::TelnetOption::TelOptPragmaLogon, "Telnet Option Pragma Logon"}, - {pcpp::TelnetLayer::TelnetOption::TelOptSSPILogon, "Telnet Option SSPI Logon"}, - {pcpp::TelnetLayer::TelnetOption::TelOptPragmaHeartbeat, "Telnet Option Pragma Heartbeat"}, - {pcpp::TelnetLayer::TelnetOption::ExtendedOptions, "Extended option list"}}; - - for (const auto &entry : possibleOptions) + { static_cast(-10), "Unknown Option" }, + { pcpp::TelnetLayer::TelnetOption::TelnetOptionNoOption, "No option for this command" }, + { pcpp::TelnetLayer::TelnetOption::TransmitBinary, "Binary Transmission" }, + { pcpp::TelnetLayer::TelnetOption::Echo, "Echo" }, + { pcpp::TelnetLayer::TelnetOption::Reconnection, "Reconnection" }, + { pcpp::TelnetLayer::TelnetOption::SuppressGoAhead, "Suppress Go Ahead" }, + { pcpp::TelnetLayer::TelnetOption::ApproxMsgSizeNegotiation, "Negotiate approximate message size" }, + { pcpp::TelnetLayer::TelnetOption::Status, "Status" }, + { pcpp::TelnetLayer::TelnetOption::TimingMark, "Timing Mark" }, + { pcpp::TelnetLayer::TelnetOption::RemoteControlledTransAndEcho, "Remote Controlled Transmission and Echo" }, + { pcpp::TelnetLayer::TelnetOption::OutputLineWidth, "Output Line Width" }, + { pcpp::TelnetLayer::TelnetOption::OutputPageSize, "Output Page Size" }, + { pcpp::TelnetLayer::TelnetOption::OutputCarriageReturnDisposition, + "Negotiate About Output Carriage-Return Disposition" }, + { pcpp::TelnetLayer::TelnetOption::OutputHorizontalTabStops, "Negotiate About Output Horizontal Tabstops" }, + { pcpp::TelnetLayer::TelnetOption::OutputHorizontalTabDisposition, + "Negotiate About Output Horizontal Tab Disposition" }, + { pcpp::TelnetLayer::TelnetOption::OutputFormfeedDisposition, "Negotiate About Output Formfeed Disposition" }, + { pcpp::TelnetLayer::TelnetOption::OutputVerticalTabStops, "Negotiate About Vertical Tabstops" }, + { pcpp::TelnetLayer::TelnetOption::OutputVerticalTabDisposition, + "Negotiate About Output Vertcial Tab Disposition" }, + { pcpp::TelnetLayer::TelnetOption::OutputLinefeedDisposition, "Negotiate About Output Linefeed Disposition" }, + { pcpp::TelnetLayer::TelnetOption::ExtendedASCII, "Extended ASCII" }, + { pcpp::TelnetLayer::TelnetOption::Logout, "Logout" }, + { pcpp::TelnetLayer::TelnetOption::ByteMacro, "Byte Macro" }, + { pcpp::TelnetLayer::TelnetOption::DataEntryTerminal, "Data Entry Terminal" }, + { pcpp::TelnetLayer::TelnetOption::SUPDUP, "SUPDUP" }, + { pcpp::TelnetLayer::TelnetOption::SUPDUPOutput, "SUPDUP Output" }, + { pcpp::TelnetLayer::TelnetOption::SendLocation, "Send Location" }, + { pcpp::TelnetLayer::TelnetOption::TerminalType, "Terminal Type" }, + { pcpp::TelnetLayer::TelnetOption::EndOfRecordOption, "End Of Record" }, + { pcpp::TelnetLayer::TelnetOption::TACACSUserIdentification, "TACACS User Identification" }, + { pcpp::TelnetLayer::TelnetOption::OutputMarking, "Output Marking" }, + { pcpp::TelnetLayer::TelnetOption::TerminalLocationNumber, "Terminal Location Number" }, + { pcpp::TelnetLayer::TelnetOption::Telnet3270Regime, "Telnet 3270 Regime" }, + { pcpp::TelnetLayer::TelnetOption::X3Pad, "X3 Pad" }, + { pcpp::TelnetLayer::TelnetOption::NegotiateAboutWindowSize, "Negotiate About Window Size" }, + { pcpp::TelnetLayer::TelnetOption::TerminalSpeed, "Terminal Speed" }, + { pcpp::TelnetLayer::TelnetOption::RemoteFlowControl, "Remote Flow Control" }, + { pcpp::TelnetLayer::TelnetOption::Linemode, "Line mode" }, + { pcpp::TelnetLayer::TelnetOption::XDisplayLocation, "X Display Location" }, + { pcpp::TelnetLayer::TelnetOption::EnvironmentOption, "Environment Option" }, + { pcpp::TelnetLayer::TelnetOption::AuthenticationOption, "Authentication Option" }, + { pcpp::TelnetLayer::TelnetOption::EncryptionOption, "Encryption Option" }, + { pcpp::TelnetLayer::TelnetOption::NewEnvironmentOption, "New Environment Option" }, + { pcpp::TelnetLayer::TelnetOption::TN3270E, "TN3270E" }, + { pcpp::TelnetLayer::TelnetOption::XAuth, "X Server Authentication" }, + { pcpp::TelnetLayer::TelnetOption::Charset, "Charset" }, + { pcpp::TelnetLayer::TelnetOption::TelnetRemoteSerialPort, "Telnet Remote Serial Port" }, + { pcpp::TelnetLayer::TelnetOption::ComPortControlOption, "Com Port Control Option" }, + { pcpp::TelnetLayer::TelnetOption::TelnetSuppressLocalEcho, "Telnet Suppress Local Echo" }, + { pcpp::TelnetLayer::TelnetOption::TelnetStartTLS, "Telnet Start TLS" }, + { pcpp::TelnetLayer::TelnetOption::Kermit, "Kermit" }, + { pcpp::TelnetLayer::TelnetOption::SendURL, "Send URL" }, + { pcpp::TelnetLayer::TelnetOption::ForwardX, "Forward X Server" }, + { pcpp::TelnetLayer::TelnetOption::TelOptPragmaLogon, "Telnet Option Pragma Logon" }, + { pcpp::TelnetLayer::TelnetOption::TelOptSSPILogon, "Telnet Option SSPI Logon" }, + { pcpp::TelnetLayer::TelnetOption::TelOptPragmaHeartbeat, "Telnet Option Pragma Heartbeat" }, + { pcpp::TelnetLayer::TelnetOption::ExtendedOptions, "Extended option list" } + }; + + for (const auto& entry : possibleOptions) { PTF_ASSERT_EQUAL(pcpp::TelnetLayer::getTelnetOptionAsString(entry.first), entry.second); } @@ -265,7 +262,7 @@ PTF_TEST_CASE(TelnetDataParsingTests) READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/telnetData.dat"); pcpp::Packet telnetPacket(&rawPacket1); - pcpp::TelnetLayer *telnetLayer = telnetPacket.getLayerOfType(); + pcpp::TelnetLayer* telnetLayer = telnetPacket.getLayerOfType(); PTF_ASSERT_NOT_NULL(telnetLayer); diff --git a/Tests/Packet++Test/Tests/TpktTests.cpp b/Tests/Packet++Test/Tests/TpktTests.cpp index 45777ed6a5..ad80dbdeb0 100644 --- a/Tests/Packet++Test/Tests/TpktTests.cpp +++ b/Tests/Packet++Test/Tests/TpktTests.cpp @@ -35,4 +35,4 @@ PTF_TEST_CASE(TpktLayerTest) PTF_ASSERT_EQUAL(tpktLayerTest.getLength(), 602); PTF_ASSERT_EQUAL(tpktLayerTest.toString(), "TPKT Layer, version: 10, length: 602"); -} // TpktLayerTest +} // TpktLayerTest diff --git a/Tests/Packet++Test/Tests/VlanMplsTests.cpp b/Tests/Packet++Test/Tests/VlanMplsTests.cpp index 5a9b412bec..44ab437489 100644 --- a/Tests/Packet++Test/Tests/VlanMplsTests.cpp +++ b/Tests/Packet++Test/Tests/VlanMplsTests.cpp @@ -11,14 +11,13 @@ #include "UdpLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(VlanParseAndCreation) { - for(int vid = 0; vid < 4096 * 2; vid++) + for (int vid = 0; vid < 4096 * 2; vid++) { - for(int prio = 0; prio < 8 * 2; prio ++) + for (int prio = 0; prio < 8 * 2; prio++) { - for(int cfi = 0; cfi < 2 * 2; cfi++) //true or false + for (int cfi = 0; cfi < 2 * 2; cfi++) // true or false { pcpp::VlanLayer testVlanLayer(vid, cfi, prio, PCPP_ETHERTYPE_VLAN); PTF_ASSERT_EQUAL(testVlanLayer.getVlanID(), (vid & 0xFFF)); @@ -53,8 +52,9 @@ PTF_TEST_CASE(VlanParseAndCreation) pcpp::EthLayer ethLayer(macSrc, macDest); pcpp::VlanLayer firstVlanLayer(666, 1, 5); pcpp::VlanLayer secondVlanLayer(200, 0, 2, PCPP_ETHERTYPE_ARP); - pcpp::ArpLayer arpLayer(pcpp::ARP_REQUEST, macSrc, pcpp::MacAddress("00:00:00:00:00:00"), pcpp::IPv4Address("192.168.2.200"), pcpp::IPv4Address("192.168.2.254")); - pcpp::Packet arpWithVlanNew(1); + pcpp::ArpLayer arpLayer(pcpp::ARP_REQUEST, macSrc, pcpp::MacAddress("00:00:00:00:00:00"), + pcpp::IPv4Address("192.168.2.200"), pcpp::IPv4Address("192.168.2.254")); + pcpp::Packet arpWithVlanNew(1); PTF_ASSERT_TRUE(arpWithVlanNew.addLayer(ðLayer)); PTF_ASSERT_TRUE(arpWithVlanNew.addLayer(&firstVlanLayer)); PTF_ASSERT_TRUE(arpWithVlanNew.addLayer(&secondVlanLayer)); @@ -64,9 +64,7 @@ PTF_TEST_CASE(VlanParseAndCreation) PTF_ASSERT_EQUAL(arpWithVlanNew.getRawPacket()->getRawDataLen(), bufferLength1); PTF_ASSERT_BUF_COMPARE(arpWithVlanNew.getRawPacket()->getRawData(), buffer1, bufferLength1); -} // VlanParseAndCreation - - +} // VlanParseAndCreation PTF_TEST_CASE(QinQ802_1adParse) { @@ -88,9 +86,7 @@ PTF_TEST_CASE(QinQ802_1adParse) PTF_ASSERT_EQUAL(secondVlanLayerPtr->getPriority(), 0); PTF_ASSERT_NOT_NULL(secondVlanLayerPtr->getNextLayer()); PTF_ASSERT_EQUAL(secondVlanLayerPtr->getNextLayer()->getProtocol(), pcpp::IPv4, enum); -} // QinQ802_1adParse - - +} // QinQ802_1adParse PTF_TEST_CASE(MplsLayerTest) { @@ -138,7 +134,7 @@ PTF_TEST_CASE(MplsLayerTest) mplsLayer->setTTL(111); PTF_ASSERT_TRUE(mplsLayer->setMplsLabel(100000)); uint8_t expectedResult[4] = { 0x18, 0x6A, 0x0d, 0x6f }; - PTF_ASSERT_BUF_COMPARE(mplsLayer->getData(), expectedResult , 4); + PTF_ASSERT_BUF_COMPARE(mplsLayer->getData(), expectedResult, 4); PTF_ASSERT_EQUAL(mplsLayer->getTTL(), 111); PTF_ASSERT_EQUAL(mplsLayer->getMplsLabel(), 100000); PTF_ASSERT_EQUAL(mplsLayer->getExperimentalUseValue(), 6); @@ -146,7 +142,7 @@ PTF_TEST_CASE(MplsLayerTest) pcpp::MplsLayer mplsLayer2(0xdff0f, 20, 7, false); uint8_t expectedResult2[4] = { 0xdf, 0xf0, 0xfe, 0x14 }; - PTF_ASSERT_BUF_COMPARE(mplsLayer2.getData(), expectedResult2 , 4); + PTF_ASSERT_BUF_COMPARE(mplsLayer2.getData(), expectedResult2, 4); pcpp::Logger::getInstance().suppressLogs(); PTF_ASSERT_FALSE(mplsLayer->setMplsLabel(0xFFFFFF)); @@ -173,9 +169,7 @@ PTF_TEST_CASE(MplsLayerTest) PTF_ASSERT_EQUAL(mplsLayer->getMplsLabel(), 18); PTF_ASSERT_EQUAL(mplsLayer->getExperimentalUseValue(), 0); PTF_ASSERT_TRUE(mplsLayer->isBottomOfStack()); -} // MplsLayerTest - - +} // MplsLayerTest PTF_TEST_CASE(VxlanParsingAndCreationTest) { @@ -209,7 +203,8 @@ PTF_TEST_CASE(VxlanParsingAndCreationTest) // verify edited fields PTF_ASSERT_EQUAL(vxlanPacket.getRawPacket()->getRawDataLen(), bufferLength2); - PTF_ASSERT_BUF_COMPARE(vxlanPacket.getRawPacket()->getRawData(), buffer2, vxlanPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(vxlanPacket.getRawPacket()->getRawData(), buffer2, + vxlanPacket.getRawPacket()->getRawDataLen()); // remove vxlan layer PTF_ASSERT_TRUE(vxlanPacket.removeLayer(pcpp::VXLAN)); @@ -221,7 +216,8 @@ PTF_TEST_CASE(VxlanParsingAndCreationTest) // verify new vxlan layer PTF_ASSERT_EQUAL(vxlanPacket.getRawPacket()->getRawDataLen(), bufferLength1); - PTF_ASSERT_BUF_COMPARE(vxlanPacket.getRawPacket()->getRawData(), buffer1, vxlanPacket.getRawPacket()->getRawDataLen()); + PTF_ASSERT_BUF_COMPARE(vxlanPacket.getRawPacket()->getRawData(), buffer1, + vxlanPacket.getRawPacket()->getRawDataLen()); - delete [] buffer2; -} // VxlanParsingAndCreationTest + delete[] buffer2; +} // VxlanParsingAndCreationTest diff --git a/Tests/Packet++Test/Tests/VrrpTest.cpp b/Tests/Packet++Test/Tests/VrrpTest.cpp old mode 100755 new mode 100644 index a30e39cafb..c38fadbd39 --- a/Tests/Packet++Test/Tests/VrrpTest.cpp +++ b/Tests/Packet++Test/Tests/VrrpTest.cpp @@ -11,14 +11,13 @@ #include "PayloadLayer.h" #include "SystemUtils.h" - PTF_TEST_CASE(VrrpParsingTest) { timeval time = {}; gettimeofday(&time, nullptr); PTF_ASSERT_EQUAL(pcpp::VrrpLayer::getVersionFromData(nullptr, 0), pcpp::UnknownProtocol); - uint8_t fakeBuffer[10] = {0xb4,0xaf,0x98,0x1a, 0xb4,0xaf,0x98,0x1a, 0x98,0x1a}; + uint8_t fakeBuffer[10] = { 0xb4, 0xaf, 0x98, 0x1a, 0xb4, 0xaf, 0x98, 0x1a, 0x98, 0x1a }; PTF_ASSERT_EQUAL(pcpp::VrrpLayer::getVersionFromData(fakeBuffer, 10), pcpp::UnknownProtocol); READ_FILE_AND_CREATE_PACKET(1, "PacketExamples/VRRP-V2.dat"); @@ -47,14 +46,11 @@ PTF_TEST_CASE(VrrpParsingTest) PTF_ASSERT_EQUAL(vrrpV2Layer->toString(), "VRRP v2 Layer, virtual router ID: 1, IP address count: 3") PTF_ASSERT_EQUAL(vrrpV2Layer->getIPAddressesCount(), 3) auto ipAddressVec = vrrpV2Layer->getIPAddresses(); - std::vector expectedIpAddressVec = { - pcpp::IPAddress("192.168.0.1"), - pcpp::IPAddress("192.168.0.2"), - pcpp::IPAddress("192.168.0.3") - }; + std::vector expectedIpAddressVec = { pcpp::IPAddress("192.168.0.1"), + pcpp::IPAddress("192.168.0.2"), + pcpp::IPAddress("192.168.0.3") }; PTF_ASSERT_TRUE(ipAddressVec == expectedIpAddressVec) - PTF_ASSERT_TRUE(vrrpv3IPv4Packet.isPacketOfType(pcpp::VRRP)) PTF_ASSERT_FALSE(vrrpv3IPv4Packet.isPacketOfType(pcpp::VRRPv2)) PTF_ASSERT_TRUE(vrrpv3IPv4Packet.isPacketOfType(pcpp::VRRPv3)) @@ -71,10 +67,7 @@ PTF_TEST_CASE(VrrpParsingTest) PTF_ASSERT_EQUAL(vrrpV3IPv4Layer->toString(), "VRRP v3 Layer, virtual router ID: 1, IP address count: 2") PTF_ASSERT_EQUAL(vrrpV3IPv4Layer->getIPAddressesCount(), 2) ipAddressVec = vrrpV3IPv4Layer->getIPAddresses(); - expectedIpAddressVec = { - pcpp::IPAddress("192.168.0.1"), - pcpp::IPAddress("192.168.0.2") - }; + expectedIpAddressVec = { pcpp::IPAddress("192.168.0.1"), pcpp::IPAddress("192.168.0.2") }; PTF_ASSERT_TRUE(ipAddressVec == expectedIpAddressVec) PTF_ASSERT_TRUE(vrrpv3IPv6Packet.isPacketOfType(pcpp::VRRP)) @@ -93,15 +86,10 @@ PTF_TEST_CASE(VrrpParsingTest) PTF_ASSERT_TRUE(vrrpV3IPv6Layer->isChecksumCorrect()) PTF_ASSERT_EQUAL(vrrpV3IPv6Layer->toString(), "VRRP v3 Layer, virtual router ID: 1, IP address count: 3") ipAddressVec = vrrpV3IPv6Layer->getIPAddresses(); - expectedIpAddressVec = { - pcpp::IPAddress("fe80::254"), - pcpp::IPAddress("2001:db8::1"), - pcpp::IPAddress("2001:db8::2") - }; + expectedIpAddressVec = { pcpp::IPAddress("fe80::254"), pcpp::IPAddress("2001:db8::1"), + pcpp::IPAddress("2001:db8::2") }; PTF_ASSERT_TRUE(ipAddressVec == expectedIpAddressVec) -} // VrrpParsingTest - - +} // VrrpParsingTest PTF_TEST_CASE(VrrpCreateAndEditTest) { @@ -188,14 +176,13 @@ PTF_TEST_CASE(VrrpCreateAndEditTest) vrrpv2Layer.setAuthType(10); PTF_ASSERT_EQUAL(vrrpv2Layer.getAuthTypeAsEnum(), pcpp::VrrpV2Layer::VrrpAuthType::Other, enumclass) - - //VRRPv3 IPv4 Packet + // VRRPv3 IPv4 Packet pcpp::EthLayer ethLayer2(pcpp::MacAddress("00:00:5e:00:01:01"), pcpp::MacAddress("01:00:5e:00:00:12")); pcpp::IPv4Layer ipv4Layer(pcpp::IPv4Address("192.168.0.30"), pcpp::IPv4Address("224.0.0.18")); ipv4Layer.getIPv4Header()->timeToLive = 255; pcpp::Packet vrrpv3IPv4Packet(1); - pcpp::VrrpV3Layer vrrpv3IPv4Layer(pcpp::IPAddress::IPv4AddressType, 1 ,100, 1); + pcpp::VrrpV3Layer vrrpv3IPv4Layer(pcpp::IPAddress::IPv4AddressType, 1, 100, 1); vrrpv3IPv4Layer.addIPAddress(ipv4Address1); vrrpv3IPv4Layer.addIPAddress(ipv4Address2); @@ -221,10 +208,10 @@ PTF_TEST_CASE(VrrpCreateAndEditTest) vrrpv3IPv4Layer.getData()[0] = 0x55; PTF_ASSERT_EQUAL(vrrpv3IPv4Layer.getType(), pcpp::VrrpLayer::VrrpType::VrrpType_Unknown) - PTF_ASSERT_RAISES(vrrpv3IPv4Layer.setMaxAdvInt(0x1234), std::invalid_argument, "maxAdvInt must not exceed 12 bits length") - + PTF_ASSERT_RAISES(vrrpv3IPv4Layer.setMaxAdvInt(0x1234), std::invalid_argument, + "maxAdvInt must not exceed 12 bits length") - //VRRPv3 IPv6 Packet + // VRRPv3 IPv6 Packet pcpp::EthLayer ethLayer3(pcpp::MacAddress("00:00:5e:00:01:01"), pcpp::MacAddress("01:00:5e:00:00:12")); pcpp::IPv6Layer ipv6Layer(pcpp::IPv6Address("fe80::1"), pcpp::IPv6Address("ff02::12")); ipv6Layer.getIPv6Header()->hopLimit = 255; @@ -249,4 +236,4 @@ PTF_TEST_CASE(VrrpCreateAndEditTest) FREE_FILE_INTO_BUFFER(2) FREE_FILE_INTO_BUFFER(3) -} // VrrpCreateAndEditTest +} // VrrpCreateAndEditTest diff --git a/Tests/Packet++Test/Tests/WakeOnLanTests.cpp b/Tests/Packet++Test/Tests/WakeOnLanTests.cpp index 26a935ad1d..aaf233346a 100644 --- a/Tests/Packet++Test/Tests/WakeOnLanTests.cpp +++ b/Tests/Packet++Test/Tests/WakeOnLanTests.cpp @@ -15,7 +15,7 @@ PTF_TEST_CASE(WakeOnLanParsingTests) pcpp::Packet wolPacket1(&rawPacket1); PTF_ASSERT_TRUE(wolPacket1.isPacketOfType(pcpp::WakeOnLan)); - pcpp::WakeOnLanLayer *wolLayer1 = wolPacket1.getLayerOfType(); + pcpp::WakeOnLanLayer* wolLayer1 = wolPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(wolLayer1); PTF_ASSERT_NOT_NULL(wolLayer1->getWakeOnLanHeader()); @@ -27,7 +27,7 @@ PTF_TEST_CASE(WakeOnLanParsingTests) pcpp::Packet wolPacket2(&rawPacket2); PTF_ASSERT_TRUE(wolPacket2.isPacketOfType(pcpp::WakeOnLan)); - pcpp::WakeOnLanLayer *wolLayer2 = wolPacket2.getLayerOfType(); + pcpp::WakeOnLanLayer* wolLayer2 = wolPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(wolLayer2); PTF_ASSERT_NOT_NULL(wolLayer2->getWakeOnLanHeader()); @@ -45,7 +45,7 @@ PTF_TEST_CASE(WakeOnLanCreationTests) pcpp::Packet wolPacket1(&rawPacket1); PTF_ASSERT_TRUE(wolPacket1.isPacketOfType(pcpp::WakeOnLan)); - pcpp::WakeOnLanLayer *wolLayer1 = wolPacket1.getLayerOfType(); + pcpp::WakeOnLanLayer* wolLayer1 = wolPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(wolLayer1); pcpp::WakeOnLanLayer wolcraftedLayer1(pcpp::MacAddress("00:0d:56:dc:9e:35")); @@ -62,7 +62,7 @@ PTF_TEST_CASE(WakeOnLanCreationTests) pcpp::Packet wolPacket2(&rawPacket2); PTF_ASSERT_TRUE(wolPacket2.isPacketOfType(pcpp::WakeOnLan)); - pcpp::WakeOnLanLayer *wolLayer2 = wolPacket2.getLayerOfType(); + pcpp::WakeOnLanLayer* wolLayer2 = wolPacket2.getLayerOfType(); PTF_ASSERT_NOT_NULL(wolLayer2); pcpp::WakeOnLanLayer wolcraftedLayer2(pcpp::MacAddress("00:90:27:85:cf:01")); @@ -79,14 +79,14 @@ PTF_TEST_CASE(WakeOnLanEditTests) pcpp::Packet wolPacket1(&rawPacket1); PTF_ASSERT_TRUE(wolPacket1.isPacketOfType(pcpp::WakeOnLan)); - pcpp::WakeOnLanLayer *wolLayer1 = wolPacket1.getLayerOfType(); + pcpp::WakeOnLanLayer* wolLayer1 = wolPacket1.getLayerOfType(); PTF_ASSERT_NOT_NULL(wolLayer1); // Edit password READ_FILE_AND_CREATE_PACKET(2, "PacketExamples/WoL_ether_edited1.dat"); pcpp::Packet wolPacketEdited1(&rawPacket2); PTF_ASSERT_TRUE(wolPacketEdited1.isPacketOfType(pcpp::WakeOnLan)); - pcpp::WakeOnLanLayer *wolLayer2 = wolPacketEdited1.getLayerOfType(); + pcpp::WakeOnLanLayer* wolLayer2 = wolPacketEdited1.getLayerOfType(); PTF_ASSERT_NOT_NULL(wolLayer2); wolLayer1->setPassword(pcpp::IPv4Address("172.0.0.2")); @@ -97,7 +97,7 @@ PTF_TEST_CASE(WakeOnLanEditTests) READ_FILE_AND_CREATE_PACKET(3, "PacketExamples/WoL_ether_edited2.dat"); pcpp::Packet wolPacketEdited2(&rawPacket3); PTF_ASSERT_TRUE(wolPacketEdited2.isPacketOfType(pcpp::WakeOnLan)); - pcpp::WakeOnLanLayer *wolLayer3 = wolPacketEdited2.getLayerOfType(); + pcpp::WakeOnLanLayer* wolLayer3 = wolPacketEdited2.getLayerOfType(); PTF_ASSERT_NOT_NULL(wolLayer3); wolLayer1->setTargetAddr("00:90:27:85:cf:01"); diff --git a/Tests/Packet++Test/Utils/TestUtils.cpp b/Tests/Packet++Test/Utils/TestUtils.cpp index 03b98b21aa..40613b42b9 100644 --- a/Tests/Packet++Test/Utils/TestUtils.cpp +++ b/Tests/Packet++Test/Utils/TestUtils.cpp @@ -9,106 +9,106 @@ namespace pcpp_tests { -int getFileLength(const char* filename) -{ - std::ifstream infile(filename, std::ifstream::binary); - if (!infile) - return -1; - infile.seekg(0, infile.end); - int length = infile.tellg(); - infile.close(); - return length; -} - -uint8_t* readFileIntoBuffer(const char* filename, int& bufferLength) -{ - int fileLength = getFileLength(filename); - if (fileLength == -1) - return nullptr; - - std::ifstream infile(filename); - if (!infile) - return nullptr; - - bufferLength = fileLength/2 + 2; - uint8_t* result = new uint8_t[bufferLength]; - int i = 0; - while (!infile.eof()) + int getFileLength(const char* filename) { - char byte[3]; - memset(byte, 0, 3); - infile.read(byte, 2); - result[i] = (uint8_t)strtol(byte, nullptr, 16); - i++; + std::ifstream infile(filename, std::ifstream::binary); + if (!infile) + return -1; + infile.seekg(0, infile.end); + int length = infile.tellg(); + infile.close(); + return length; } - infile.close(); - bufferLength -= 2; - return result; -} -void printBufferDifferences(const uint8_t* buffer1, size_t buffer1Len, const uint8_t* buffer2, size_t buffer2Len) -{ - std::cout << "First buffer (" << std::dec << buffer1Len << " bytes):\n\n"; - for(int i = 0; i<(int)buffer1Len; i++) + uint8_t* readFileIntoBuffer(const char* filename, int& bufferLength) { - std::cout << " 0x" << std::setfill('0') << std::setw(2) << std::hex << (int)buffer1[i] << " "; - if ((i+1) % 16 == 0) + int fileLength = getFileLength(filename); + if (fileLength == -1) + return nullptr; + + std::ifstream infile(filename); + if (!infile) + return nullptr; + + bufferLength = fileLength / 2 + 2; + uint8_t* result = new uint8_t[bufferLength]; + int i = 0; + while (!infile.eof()) { - std::cout << std::endl; + char byte[3]; + memset(byte, 0, 3); + infile.read(byte, 2); + result[i] = (uint8_t)strtol(byte, nullptr, 16); + i++; } + infile.close(); + bufferLength -= 2; + return result; } - std::cout << "\n\n" - << "Second buffer (" << std::dec << buffer2Len << " bytes):\n\n"; - int differenceCount = 0; - for(int i = 0; i<(int)buffer2Len; i++) + void printBufferDifferences(const uint8_t* buffer1, size_t buffer1Len, const uint8_t* buffer2, size_t buffer2Len) { - std::string starOrSpace = (buffer2[i] != buffer1[i] ? "*" : " "); - differenceCount += (buffer2[i] != buffer1[i] ? 1 : 0); - std::cout << starOrSpace << "0x" << std::setfill('0') << std::setw(2) << std::hex << (int)buffer2[i] << " "; - if ((i+1) % 16 == 0) + std::cout << "First buffer (" << std::dec << buffer1Len << " bytes):\n\n"; + for (int i = 0; i < (int)buffer1Len; i++) + { + std::cout << " 0x" << std::setfill('0') << std::setw(2) << std::hex << (int)buffer1[i] << " "; + if ((i + 1) % 16 == 0) + { + std::cout << std::endl; + } + } + std::cout << "\n\n" + << "Second buffer (" << std::dec << buffer2Len << " bytes):\n\n"; + + int differenceCount = 0; + for (int i = 0; i < (int)buffer2Len; i++) { - std::cout << std::endl; + std::string starOrSpace = (buffer2[i] != buffer1[i] ? "*" : " "); + differenceCount += (buffer2[i] != buffer1[i] ? 1 : 0); + std::cout << starOrSpace << "0x" << std::setfill('0') << std::setw(2) << std::hex << (int)buffer2[i] << " "; + if ((i + 1) % 16 == 0) + { + std::cout << std::endl; + } } + std::cout << "\n\n" << std::dec << differenceCount << " bytes differ\n\n"; } - std::cout << "\n\n" << std::dec << differenceCount << " bytes differ\n\n"; -} -void testSetUp() -{ - pcpp::SomeIpLayer::addSomeIpPort(1); - pcpp::SomeIpLayer::removeSomeIpPort(1); -} + void testSetUp() + { + pcpp::SomeIpLayer::addSomeIpPort(1); + pcpp::SomeIpLayer::removeSomeIpPort(1); + } #ifdef PCPP_TESTS_DEBUG -#include "pcap.h" - -void savePacketToPcap(pcpp::Packet& packet, const std::string &fileName) -{ - pcap_t* pcap; - pcap = pcap_open_dead(1, 65565); +# include "pcap.h" - pcap_dumper_t* d; - /* open output file */ - d = pcap_dump_open(pcap, fileName.c_str()); - if (d == NULL) + void savePacketToPcap(pcpp::Packet& packet, const std::string& fileName) { - pcap_perror(pcap, "pcap_dump_fopen"); - return; - } + pcap_t* pcap; + pcap = pcap_open_dead(1, 65565); - /* prepare for writing */ - struct pcap_pkthdr hdr; - hdr.ts.tv_sec = 0; /* sec */ - hdr.ts.tv_usec = 0; /* ms */ - hdr.caplen = hdr.len = packet.getRawPacket()->getRawDataLen(); - /* write single IP packet */ - pcap_dump(static_cast(d), &hdr, packet.getRawPacketReadOnly()->getRawData()); + pcap_dumper_t* d; + /* open output file */ + d = pcap_dump_open(pcap, fileName.c_str()); + if (d == NULL) + { + pcap_perror(pcap, "pcap_dump_fopen"); + return; + } + + /* prepare for writing */ + struct pcap_pkthdr hdr; + hdr.ts.tv_sec = 0; /* sec */ + hdr.ts.tv_usec = 0; /* ms */ + hdr.caplen = hdr.len = packet.getRawPacket()->getRawDataLen(); + /* write single IP packet */ + pcap_dump(static_cast(d), &hdr, packet.getRawPacketReadOnly()->getRawData()); - /* finish up */ - pcap_dump_close(d); - return; -} + /* finish up */ + pcap_dump_close(d); + return; + } #endif -} +} // namespace pcpp_tests diff --git a/Tests/Packet++Test/Utils/TestUtils.h b/Tests/Packet++Test/Utils/TestUtils.h index a763ca6163..81e1fb8e9d 100644 --- a/Tests/Packet++Test/Utils/TestUtils.h +++ b/Tests/Packet++Test/Utils/TestUtils.h @@ -1,7 +1,7 @@ #pragma once #ifdef PCPP_TESTS_DEBUG -#include "Packet.h" +# include "Packet.h" #endif #include #include @@ -9,38 +9,35 @@ namespace pcpp_tests { -int getFileLength(const char* filename); + int getFileLength(const char* filename); -uint8_t* readFileIntoBuffer(const char* filename, int& bufferLength); + uint8_t* readFileIntoBuffer(const char* filename, int& bufferLength); -void printBufferDifferences(const uint8_t* buffer1, size_t buffer1Len, const uint8_t* buffer2, size_t buffer2Len); + void printBufferDifferences(const uint8_t* buffer1, size_t buffer1Len, const uint8_t* buffer2, size_t buffer2Len); -void testSetUp(); + void testSetUp(); -#define READ_FILE_INTO_BUFFER(num, filename) \ - int bufferLength##num = 0; \ - uint8_t* buffer##num = pcpp_tests::readFileIntoBuffer(filename, bufferLength##num); \ - PTF_ASSERT_NOT_NULL(buffer##num) \ +#define READ_FILE_INTO_BUFFER(num, filename) \ + int bufferLength##num = 0; \ + uint8_t* buffer##num = pcpp_tests::readFileIntoBuffer(filename, bufferLength##num); \ + PTF_ASSERT_NOT_NULL(buffer##num) -#define FREE_FILE_INTO_BUFFER(num) \ - delete[] buffer##num; +#define FREE_FILE_INTO_BUFFER(num) delete[] buffer##num; -#define FILE_INTO_BUFFER_LENGTH(num) \ - bufferLength##num +#define FILE_INTO_BUFFER_LENGTH(num) bufferLength##num -#define FILE_INTO_BUFFER(num) \ - buffer##num +#define FILE_INTO_BUFFER(num) buffer##num -#define READ_FILE_AND_CREATE_PACKET(num, filename) \ - READ_FILE_INTO_BUFFER(num, filename); \ +#define READ_FILE_AND_CREATE_PACKET(num, filename) \ + READ_FILE_INTO_BUFFER(num, filename); \ pcpp::RawPacket rawPacket##num(static_cast(buffer##num), bufferLength##num, time, true) -#define READ_FILE_AND_CREATE_PACKET_LINKTYPE(num, filename, linktype) \ - READ_FILE_INTO_BUFFER(num, filename); \ +#define READ_FILE_AND_CREATE_PACKET_LINKTYPE(num, filename, linktype) \ + READ_FILE_INTO_BUFFER(num, filename); \ pcpp::RawPacket rawPacket##num(static_cast(buffer##num), bufferLength##num, time, true, linktype) #ifdef PCPP_TESTS_DEBUG -void savePacketToPcap(pcpp::Packet& packet, const std::string &fileName); + void savePacketToPcap(pcpp::Packet& packet, const std::string& fileName); #endif -} +} // namespace pcpp_tests diff --git a/Tests/Packet++Test/main.cpp b/Tests/Packet++Test/main.cpp index 937bf62707..dcaa4d7f70 100644 --- a/Tests/Packet++Test/main.cpp +++ b/Tests/Packet++Test/main.cpp @@ -7,32 +7,30 @@ #include "Logger.h" #include "../../Tests/Packet++Test/Utils/TestUtils.h" -static struct option PacketTestOptions[] = -{ - {"include-tags", required_argument, nullptr, 't'}, - {"exclude-tags", required_argument, nullptr, 'x'}, - {"show-skipped-tests", no_argument, nullptr, 'w' }, - {"mem-verbose", no_argument, nullptr, 'm' }, - {"verbose", no_argument, nullptr, 'v' }, - {"skip-mem-leak-check", no_argument, nullptr, 's' }, - {"help", no_argument, nullptr, 'h' }, - {nullptr, 0, nullptr, 0} +static struct option PacketTestOptions[] = { + { "include-tags", required_argument, nullptr, 't' }, + { "exclude-tags", required_argument, nullptr, 'x' }, + { "show-skipped-tests", no_argument, nullptr, 'w' }, + { "mem-verbose", no_argument, nullptr, 'm' }, + { "verbose", no_argument, nullptr, 'v' }, + { "skip-mem-leak-check", no_argument, nullptr, 's' }, + { "help", no_argument, nullptr, 'h' }, + { nullptr, 0, nullptr, 0 } }; void printUsage() { std::cout << "Usage: Packet++Test [-t tags] [-m] [-s] [-v] [-h]\n\n" - << "Flags:\n" - << "-t --include-tags A list of semicolon separated tags for tests to run\n" - << "-x --exclude-tags A list of semicolon separated tags for tests to exclude\n" - << "-w --show-skipped-tests Show tests that are skipped. Default is to hide them in tests results\n" - << "-v --verbose Run in verbose mode (emits more output in several tests)\n" - << "-m --mem-verbose Output information about each memory allocation and deallocation\n" - << "-s --skip-mem-leak-check Skip memory leak check\n" - << "-h --help Display this help message and exit\n"; + << "Flags:\n" + << "-t --include-tags A list of semicolon separated tags for tests to run\n" + << "-x --exclude-tags A list of semicolon separated tags for tests to exclude\n" + << "-w --show-skipped-tests Show tests that are skipped. Default is to hide them in tests results\n" + << "-v --verbose Run in verbose mode (emits more output in several tests)\n" + << "-m --mem-verbose Output information about each memory allocation and deallocation\n" + << "-s --skip-mem-leak-check Skip memory leak check\n" + << "-h --help Display this help message and exit\n"; } - int main(int argc, char* argv[]) { int optionIndex = 0; @@ -41,48 +39,50 @@ int main(int argc, char* argv[]) bool memVerbose = false; bool skipMemLeakCheck = false; - while((opt = getopt_long(argc, argv, "msvwht:x:", PacketTestOptions, &optionIndex)) != -1) + while ((opt = getopt_long(argc, argv, "msvwht:x:", PacketTestOptions, &optionIndex)) != -1) { switch (opt) { - case 0: - break; - case 't': - userTagsInclude = optarg; - break; - case 'x': - userTagsExclude = optarg; - break; - case 's': - skipMemLeakCheck = true; - break; - case 'm': - memVerbose = true; - break; - case 'w': - PTF_SHOW_SKIPPED_TESTS(true); - break; - case 'v': - PTF_SET_VERBOSE_MODE(true); - break; - case 'h': - printUsage(); - exit(0); - default: - printUsage(); - exit(-1); + case 0: + break; + case 't': + userTagsInclude = optarg; + break; + case 'x': + userTagsExclude = optarg; + break; + case 's': + skipMemLeakCheck = true; + break; + case 'm': + memVerbose = true; + break; + case 'w': + PTF_SHOW_SKIPPED_TESTS(true); + break; + case 'v': + PTF_SET_VERBOSE_MODE(true); + break; + case 'h': + printUsage(); + exit(0); + default: + printUsage(); + exit(-1); } } std::cout << "PcapPlusPlus version: " << pcpp::getPcapPlusPlusVersionFull() << std::endl - << "Built: " << pcpp::getBuildDateTime() << std::endl - << "Built from: " << pcpp::getGitInfo() << std::endl; + << "Built: " << pcpp::getBuildDateTime() << std::endl + << "Built from: " << pcpp::getGitInfo() << std::endl; - #ifdef NDEBUG +#ifdef NDEBUG skipMemLeakCheck = true; - std::cout << "Disabling memory leak check in MSVC Release builds due to caching logic in stream objects that looks like a memory leak:" << std::endl - << " https://github.com/cpputest/cpputest/issues/786#issuecomment-148921958" << std::endl; - #endif + std::cout << "Disabling memory leak check in MSVC Release builds due to caching logic in stream objects that looks " + "like a memory leak:" + << std::endl + << " https://github.com/cpputest/cpputest/issues/786#issuecomment-148921958" << std::endl; +#endif // The logger singleton looks like a memory leak. Invoke it before starting the memory check pcpp::Logger::getInstance(); diff --git a/Tests/Pcap++Test/Common/TestUtils.cpp b/Tests/Pcap++Test/Common/TestUtils.cpp index 131b24d757..b60ced1d2f 100644 --- a/Tests/Pcap++Test/Common/TestUtils.cpp +++ b/Tests/Pcap++Test/Common/TestUtils.cpp @@ -5,15 +5,15 @@ #include "PcapFileDevice.h" #include "PcapLiveDeviceList.h" #ifdef USE_PF_RING -#include "PfRingDeviceList.h" +# include "PfRingDeviceList.h" #endif #ifdef USE_DPDK -#include "DpdkDeviceList.h" +# include "DpdkDeviceList.h" #endif extern PcapTestArgs PcapTestGlobalArgs; -bool sendURLRequest(const std::string &url) +bool sendURLRequest(const std::string& url) { #if defined(_WIN32) std::string cmd = "cUrl\\curl_win32.exe -s -o cUrl\\curl_output.txt"; @@ -29,8 +29,8 @@ bool sendURLRequest(const std::string &url) return true; } - -bool readPcapIntoPacketVec(const std::string& pcapFileName, std::vector& packetStream, std::string& errMsg) +bool readPcapIntoPacketVec(const std::string& pcapFileName, std::vector& packetStream, + std::string& errMsg) { errMsg = ""; packetStream.clear(); @@ -51,8 +51,7 @@ bool readPcapIntoPacketVec(const std::string& pcapFileName, std::vector -1) { pcpp::CoreMask coreMask = 0; @@ -109,5 +106,5 @@ void testSetUp() } pcpp::DpdkDeviceList::initDpdk(coreMask, 16383); } - #endif +#endif } diff --git a/Tests/Pcap++Test/Common/TestUtils.h b/Tests/Pcap++Test/Common/TestUtils.h index 94625923ba..1b67358012 100644 --- a/Tests/Pcap++Test/Common/TestUtils.h +++ b/Tests/Pcap++Test/Common/TestUtils.h @@ -9,14 +9,14 @@ class DeviceTeardown { private: - pcpp::IDevice* m_Device; bool m_CancelTeardown; bool m_DeleteDevice; public: - - explicit DeviceTeardown(pcpp::IDevice* device, bool deleteDevice = false) : m_Device(device), m_CancelTeardown(false), m_DeleteDevice(deleteDevice) {} + explicit DeviceTeardown(pcpp::IDevice* device, bool deleteDevice = false) + : m_Device(device), m_CancelTeardown(false), m_DeleteDevice(deleteDevice) + {} ~DeviceTeardown() { @@ -36,34 +36,34 @@ class DeviceTeardown } }; -bool sendURLRequest(const std::string &url); +bool sendURLRequest(const std::string& url); -bool readPcapIntoPacketVec(const std::string& pcapFileName, std::vector& packetStream, std::string& errMsg); +bool readPcapIntoPacketVec(const std::string& pcapFileName, std::vector& packetStream, + std::string& errMsg); -int getFileLength(const std::string &filename); +int getFileLength(const std::string& filename); -uint8_t* readFileIntoBuffer(const std::string &filename, int& bufferLength); +uint8_t* readFileIntoBuffer(const std::string& filename, int& bufferLength); -template -void intersectMaps( - const std::unordered_map & left, - const std::unordered_map & right, - std::unordered_map >& result) +template +void intersectMaps(const std::unordered_map& left, + const std::unordered_map& right, + std::unordered_map>& result) { typename std::unordered_map::const_iterator il = left.begin(); typename std::unordered_map::const_iterator ir = right.begin(); while (il != left.end() && ir != right.end()) { - if (il->first < ir->first) - ++il; - else if (ir->first < il->first) - ++ir; - else - { - result.insert(std::make_pair(il->first, std::make_pair(il->second, ir->second))); - ++il; - ++ir; - } + if (il->first < ir->first) + ++il; + else if (ir->first < il->first) + ++ir; + else + { + result.insert(std::make_pair(il->first, std::make_pair(il->second, ir->second))); + ++il; + ++ir; + } } } diff --git a/Tests/Pcap++Test/Tests/DpdkTests.cpp b/Tests/Pcap++Test/Tests/DpdkTests.cpp index 50afd7b03e..3bf3bcc024 100644 --- a/Tests/Pcap++Test/Tests/DpdkTests.cpp +++ b/Tests/Pcap++Test/Tests/DpdkTests.cpp @@ -7,15 +7,15 @@ #include #ifdef USE_DPDK -#include -#include "Logger.h" -#include "PacketUtils.h" -#include "IPv4Layer.h" -#include "TcpLayer.h" -#include "UdpLayer.h" -#include "DnsLayer.h" -#include "DpdkDeviceList.h" -#include "PcapFileDevice.h" +# include +# include "Logger.h" +# include "PacketUtils.h" +# include "IPv4Layer.h" +# include "TcpLayer.h" +# include "UdpLayer.h" +# include "DnsLayer.h" +# include "DpdkDeviceList.h" +# include "PcapFileDevice.h" #endif extern PcapTestArgs PcapTestGlobalArgs; @@ -35,8 +35,23 @@ struct DpdkPacketData std::unordered_map FlowKeys; - DpdkPacketData() : ThreadId(-1), PacketCount(0), EthCount(0), ArpCount(0), Ip4Count(0), Ip6Count(0), TcpCount(0), UdpCount(0), HttpCount(0) {} - void clear() { ThreadId = -1; PacketCount = 0; EthCount = 0; ArpCount = 0; Ip4Count = 0; Ip6Count = 0; TcpCount = 0; UdpCount = 0; HttpCount = 0; FlowKeys.clear(); } + DpdkPacketData() + : ThreadId(-1), PacketCount(0), EthCount(0), ArpCount(0), Ip4Count(0), Ip6Count(0), TcpCount(0), UdpCount(0), + HttpCount(0) + {} + void clear() + { + ThreadId = -1; + PacketCount = 0; + EthCount = 0; + ArpCount = 0; + Ip4Count = 0; + Ip6Count = 0; + TcpCount = 0; + UdpCount = 0; + HttpCount = 0; + FlowKeys.clear(); + } }; int incSleep(int maxSleepTime, int minPacketCount, const DpdkPacketData& packetData) @@ -53,7 +68,8 @@ int incSleep(int maxSleepTime, int minPacketCount, const DpdkPacketData& packetD return totalSleepTime; } -int incSleepMultiThread(int maxSleepTime, DpdkPacketData packetData[], int totalNumOfCores, int numOfCoresInUse, pcpp::CoreMask coreMask) +int incSleepMultiThread(int maxSleepTime, DpdkPacketData packetData[], int totalNumOfCores, int numOfCoresInUse, + pcpp::CoreMask coreMask) { int totalSleepTime = 0; while (totalSleepTime < maxSleepTime) @@ -78,7 +94,8 @@ int incSleepMultiThread(int maxSleepTime, DpdkPacketData packetData[], int total return totalSleepTime; } -void dpdkPacketsArrive(pcpp::MBufRawPacket* packets, uint32_t numOfPackets, uint8_t threadId, pcpp::DpdkDevice* device, void* userCookie) +void dpdkPacketsArrive(pcpp::MBufRawPacket* packets, uint32_t numOfPackets, uint8_t threadId, pcpp::DpdkDevice* device, + void* userCookie) { DpdkPacketData* data = (DpdkPacketData*)userCookie; @@ -102,11 +119,11 @@ void dpdkPacketsArrive(pcpp::MBufRawPacket* packets, uint32_t numOfPackets, uint data->UdpCount++; if (packet.isPacketOfType(pcpp::HTTP)) data->HttpCount++; - } } -void dpdkPacketsArriveMultiThread(pcpp::MBufRawPacket* packets, uint32_t numOfPackets, uint8_t threadId, pcpp::DpdkDevice* device, void* userCookie) +void dpdkPacketsArriveMultiThread(pcpp::MBufRawPacket* packets, uint32_t numOfPackets, uint8_t threadId, + pcpp::DpdkDevice* device, void* userCookie) { DpdkPacketData* data = (DpdkPacketData*)userCookie; @@ -144,8 +161,6 @@ void dpdkPacketsArriveMultiThread(pcpp::MBufRawPacket* packets, uint32_t numOfPa } if (packet.isPacketOfType(pcpp::HTTP)) data[threadId].HttpCount++; - - } } @@ -160,6 +175,7 @@ class DpdkTestWorkerThread : public pcpp::DpdkWorkerThread int m_PacketCount; bool m_Initialized; bool m_RanAndStopped; + public: DpdkTestWorkerThread() { @@ -225,20 +241,28 @@ class DpdkTestWorkerThread : public pcpp::DpdkWorkerThread return true; } - void stop() { m_Stop = true; } + void stop() + { + m_Stop = true; + } - uint32_t getCoreId() const { return m_CoreId; } + uint32_t getCoreId() const + { + return m_CoreId; + } - int getPacketCount() const { return m_PacketCount; } + int getPacketCount() const + { + return m_PacketCount; + } - bool threadRanAndStopped() { return m_RanAndStopped; } + bool threadRanAndStopped() + { + return m_RanAndStopped; + } }; -#endif // USE_DPDK - - - - +#endif // USE_DPDK PTF_TEST_CASE(TestDpdkInitDevice) { @@ -253,10 +277,7 @@ PTF_TEST_CASE(TestDpdkInitDevice) #else PTF_SKIP_TEST("DPDK not configured"); #endif -} // TestDpdkInitDevice - - - +} // TestDpdkInitDevice PTF_TEST_CASE(TestDpdkDevice) { @@ -287,10 +308,8 @@ PTF_TEST_CASE(TestDpdkDevice) } else if (dev->getPMDName() == "net_vmxnet3") { - uint64_t rssHF = pcpp::DpdkDevice::RSS_IPV4 | \ - pcpp::DpdkDevice::RSS_NONFRAG_IPV4_TCP | \ - pcpp::DpdkDevice::RSS_IPV6 | \ - pcpp::DpdkDevice::RSS_NONFRAG_IPV6_TCP; + uint64_t rssHF = pcpp::DpdkDevice::RSS_IPV4 | pcpp::DpdkDevice::RSS_NONFRAG_IPV4_TCP | + pcpp::DpdkDevice::RSS_IPV6 | pcpp::DpdkDevice::RSS_NONFRAG_IPV6_TCP; PTF_ASSERT_TRUE(dev->isDeviceSupportRssHashFunction(rssHF)); PTF_ASSERT_EQUAL(dev->getSupportedRssHashFunctions(), rssHF); @@ -299,14 +318,10 @@ PTF_TEST_CASE(TestDpdkDevice) uint64_t configuredRssHF = pcpp::DpdkDevice::RSS_IPV4 | pcpp::DpdkDevice::RSS_IPV6; if (dev->getPMDType() == pcpp::PMD_I40E || dev->getPMDType() == pcpp::PMD_I40EVF) { - configuredRssHF = pcpp::DpdkDevice::RSS_NONFRAG_IPV4_TCP | \ - pcpp::DpdkDevice::RSS_NONFRAG_IPV4_UDP | \ - pcpp::DpdkDevice::RSS_NONFRAG_IPV4_OTHER | \ - pcpp::DpdkDevice::RSS_FRAG_IPV4 | \ - pcpp::DpdkDevice::RSS_NONFRAG_IPV6_TCP | \ - pcpp::DpdkDevice::RSS_NONFRAG_IPV6_UDP | \ - pcpp::DpdkDevice::RSS_NONFRAG_IPV6_OTHER | \ - pcpp::DpdkDevice::RSS_FRAG_IPV6; + configuredRssHF = pcpp::DpdkDevice::RSS_NONFRAG_IPV4_TCP | pcpp::DpdkDevice::RSS_NONFRAG_IPV4_UDP | + pcpp::DpdkDevice::RSS_NONFRAG_IPV4_OTHER | pcpp::DpdkDevice::RSS_FRAG_IPV4 | + pcpp::DpdkDevice::RSS_NONFRAG_IPV6_TCP | pcpp::DpdkDevice::RSS_NONFRAG_IPV6_UDP | + pcpp::DpdkDevice::RSS_NONFRAG_IPV6_OTHER | pcpp::DpdkDevice::RSS_FRAG_IPV6; } PTF_ASSERT_EQUAL(dev->getConfiguredRssHashFunction(), configuredRssHF); @@ -353,7 +368,9 @@ PTF_TEST_CASE(TestDpdkDevice) PTF_ASSERT_GREATER_THAN(packetData.PacketCount, 0); PTF_ASSERT_NOT_EQUAL(packetData.ThreadId, -1); - int statsVsPacketCount = stats.aggregatedRxStats.packets > (uint64_t)packetData.PacketCount ? stats.aggregatedRxStats.packets-(uint64_t)packetData.PacketCount : (uint64_t)packetData.PacketCount-stats.aggregatedRxStats.packets; + int statsVsPacketCount = stats.aggregatedRxStats.packets > (uint64_t)packetData.PacketCount + ? stats.aggregatedRxStats.packets - (uint64_t)packetData.PacketCount + : (uint64_t)packetData.PacketCount - stats.aggregatedRxStats.packets; PTF_ASSERT_LOWER_OR_EQUAL_THAN(statsVsPacketCount, 20); dev->close(); @@ -361,10 +378,7 @@ PTF_TEST_CASE(TestDpdkDevice) #else PTF_SKIP_TEST("DPDK not configured"); #endif -} // TestDpdkDevice - - - +} // TestDpdkDevice PTF_TEST_CASE(TestDpdkMultiThread) { @@ -376,7 +390,8 @@ PTF_TEST_CASE(TestDpdkMultiThread) DeviceTeardown devTeardown(dev); // take min value between number of cores and number of available RX queues - int numOfRxQueuesToOpen = pcpp::getNumOfCores()-1; //using num of cores minus one since 1 core is the master core and cannot be used + int numOfRxQueuesToOpen = + pcpp::getNumOfCores() - 1; // using num of cores minus one since 1 core is the master core and cannot be used if (dev->getTotalNumOfRxQueues() < numOfRxQueuesToOpen) numOfRxQueuesToOpen = dev->getTotalNumOfRxQueues(); @@ -391,7 +406,7 @@ PTF_TEST_CASE(TestDpdkMultiThread) if (dev->getTotalNumOfRxQueues() > 1) { pcpp::Logger::getInstance().suppressLogs(); - PTF_ASSERT_FALSE(dev->openMultiQueues(numOfRxQueuesToOpen+1, 1)); + PTF_ASSERT_FALSE(dev->openMultiQueues(numOfRxQueuesToOpen + 1, 1)); pcpp::Logger::getInstance().enableLogs(); } @@ -430,7 +445,8 @@ PTF_TEST_CASE(TestDpdkMultiThread) } PTF_ASSERT_TRUE(dev->startCaptureMultiThreads(dpdkPacketsArriveMultiThread, packetDataMultiThread, coreMask)); - int totalSleepTime = incSleepMultiThread(20, packetDataMultiThread, pcpp::getNumOfCores(), numOfCoresInUse, coreMask); + int totalSleepTime = + incSleepMultiThread(20, packetDataMultiThread, pcpp::getNumOfCores(), numOfCoresInUse, coreMask); dev->stopCapture(); PTF_PRINT_VERBOSE("Total sleep time: " << totalSleepTime); uint64_t packetCount = 0; @@ -463,7 +479,6 @@ PTF_TEST_CASE(TestDpdkMultiThread) { PTF_PRINT_VERBOSE("Packets captured on RX queue #" << i << " according to stats: " << stats.rxStats[i].packets); PTF_PRINT_VERBOSE("Bytes captured on RX queue #" << i << " according to stats: " << stats.rxStats[i].bytes); - } PTF_ASSERT_GREATER_OR_EQUAL_THAN(stats.aggregatedRxStats.packets, packetCount); PTF_ASSERT_EQUAL(stats.rxPacketsDroppedByHW, 0); @@ -473,19 +488,21 @@ PTF_TEST_CASE(TestDpdkMultiThread) if ((pcpp::SystemCores::IdToSystemCore[firstCoreId].Mask & coreMask) == 0) continue; - for (int secondCoreId = firstCoreId+1; secondCoreId < pcpp::getNumOfCores(); secondCoreId++) + for (int secondCoreId = firstCoreId + 1; secondCoreId < pcpp::getNumOfCores(); secondCoreId++) { if ((pcpp::SystemCores::IdToSystemCore[secondCoreId].Mask & coreMask) == 0) continue; - std::unordered_map > res; - intersectMaps(packetDataMultiThread[firstCoreId].FlowKeys, packetDataMultiThread[secondCoreId].FlowKeys, res); + std::unordered_map> res; + intersectMaps( + packetDataMultiThread[firstCoreId].FlowKeys, packetDataMultiThread[secondCoreId].FlowKeys, res); PTF_ASSERT_EQUAL(res.size(), 0); if (PTF_IS_VERBOSE_MODE) { - for (auto &iter : res) + for (auto& iter : res) { - PTF_PRINT_VERBOSE("Same flow exists in core " << firstCoreId << " and core " << secondCoreId << ". Flow key = " << iter.first); + PTF_PRINT_VERBOSE("Same flow exists in core " << firstCoreId << " and core " << secondCoreId + << ". Flow key = " << iter.first); std::ostringstream stream; stream << "Core" << firstCoreId << "_Flow_" << std::hex << iter.first << ".pcap"; pcpp::PcapFileWriterDevice writerDev(stream.str()); @@ -502,16 +519,15 @@ PTF_TEST_CASE(TestDpdkMultiThread) iter.second.first.clear(); iter.second.second.clear(); - } } } - PTF_PRINT_VERBOSE("____Core " << firstCoreId << "____"); + PTF_PRINT_VERBOSE("____Core " << firstCoreId << "____"); PTF_PRINT_VERBOSE("Total flows: " << packetDataMultiThread[firstCoreId].FlowKeys.size()); if (PTF_IS_VERBOSE_MODE) { - for(auto &iter : packetDataMultiThread[firstCoreId].FlowKeys) + for (auto& iter : packetDataMultiThread[firstCoreId].FlowKeys) { PTF_PRINT_VERBOSE("Key=0x" << std::hex << iter.first << "; Value=" << std::dec << iter.second.size()); iter.second.clear(); @@ -526,10 +542,7 @@ PTF_TEST_CASE(TestDpdkMultiThread) #else PTF_SKIP_TEST("DPDK not configured"); #endif -} // TestDpdkMultiThread - - - +} // TestDpdkMultiThread PTF_TEST_CASE(TestDpdkDeviceSendPackets) { @@ -557,7 +570,7 @@ PTF_TEST_CASE(TestDpdkDeviceSendPackets) pcpp::Packet* packetArr[10000]; uint16_t packetsRead = 0; pcpp::RawPacket rawPacket; - while(fileReaderDev.getNextPacket(rawPacket)) + while (fileReaderDev.getNextPacket(rawPacket)) { if (packetsRead == 100) break; @@ -571,28 +584,28 @@ PTF_TEST_CASE(TestDpdkDeviceSendPackets) packetsRead++; } - //send packets as parsed EthPacekt array + // send packets as parsed EthPacekt array uint16_t packetsSentAsParsed = dev->sendPackets(packetArr, packetsRead, 0, false); PTF_ASSERT_EQUAL(packetsSentAsParsed, packetsRead); - //send packets are RawPacketVector + // send packets are RawPacketVector uint16_t packetsSentAsRawVector = dev->sendPackets(rawPacketVec); PTF_ASSERT_EQUAL(packetsSentAsRawVector, packetsRead); if (txQueues > 1) { - packetsSentAsParsed = dev->sendPackets(packetArr, packetsRead, txQueues-1); - packetsSentAsRawVector = dev->sendPackets(rawPacketVec, txQueues-1); + packetsSentAsParsed = dev->sendPackets(packetArr, packetsRead, txQueues - 1); + packetsSentAsRawVector = dev->sendPackets(rawPacketVec, txQueues - 1); PTF_ASSERT_EQUAL(packetsSentAsParsed, packetsRead); PTF_ASSERT_EQUAL(packetsSentAsRawVector, packetsRead); } pcpp::Logger::getInstance().suppressLogs(); - PTF_ASSERT_EQUAL(dev->sendPackets(rawPacketVec, txQueues+1), 0); + PTF_ASSERT_EQUAL(dev->sendPackets(rawPacketVec, txQueues + 1), 0); pcpp::Logger::getInstance().enableLogs(); - PTF_ASSERT_TRUE(dev->sendPacket(*(rawPacketVec.at(packetsRead/3)), 0)); - PTF_ASSERT_TRUE(dev->sendPacket(*(packetArr[packetsRead/2]), 0)); + PTF_ASSERT_TRUE(dev->sendPacket(*(rawPacketVec.at(packetsRead / 3)), 0)); + PTF_ASSERT_TRUE(dev->sendPacket(*(packetArr[packetsRead / 2]), 0)); dev->close(); fileReaderDev.close(); @@ -600,10 +613,7 @@ PTF_TEST_CASE(TestDpdkDeviceSendPackets) #else PTF_SKIP_TEST("DPDK not configured"); #endif -} // TestDpdkDeviceSendPackets - - - +} // TestDpdkDeviceSendPackets PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) { @@ -628,9 +638,9 @@ PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) PTF_ASSERT_EQUAL(dev->receivePackets(mBufRawPacketArr, mBufRawPacketArrLen, 0), 0); PTF_ASSERT_TRUE(dev->open()); - PTF_ASSERT_EQUAL(dev->receivePackets(rawPacketVec, dev->getTotalNumOfRxQueues()+1), 0); - PTF_ASSERT_EQUAL(dev->receivePackets(packetArr, packetArrLen, dev->getTotalNumOfRxQueues()+1), 0); - PTF_ASSERT_EQUAL(dev->receivePackets(mBufRawPacketArr, mBufRawPacketArrLen, dev->getTotalNumOfRxQueues()+1), 0); + PTF_ASSERT_EQUAL(dev->receivePackets(rawPacketVec, dev->getTotalNumOfRxQueues() + 1), 0); + PTF_ASSERT_EQUAL(dev->receivePackets(packetArr, packetArrLen, dev->getTotalNumOfRxQueues() + 1), 0); + PTF_ASSERT_EQUAL(dev->receivePackets(mBufRawPacketArr, mBufRawPacketArrLen, dev->getTotalNumOfRxQueues() + 1), 0); DpdkPacketData packetData; mBufRawPacketArrLen = 32; @@ -672,7 +682,8 @@ PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) } PTF_ASSERT_LOWER_THAN(numOfAttempts, 20); - PTF_PRINT_VERBOSE("Captured " << rawPacketVec.size() << " packets in " << numOfAttempts << " attempts using RawPacketVector"); + PTF_PRINT_VERBOSE("Captured " << rawPacketVec.size() << " packets in " << numOfAttempts + << " attempts using RawPacketVector"); // receive packets to mbuf array // ----------------------------- @@ -698,7 +709,8 @@ PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) } PTF_ASSERT_LOWER_THAN(numOfAttempts, 20); - PTF_PRINT_VERBOSE("Captured " << mBufRawPacketArrLen << " packets in " << numOfAttempts << " attempts using mBuf raw packet arr"); + PTF_PRINT_VERBOSE("Captured " << mBufRawPacketArrLen << " packets in " << numOfAttempts + << " attempts using mBuf raw packet arr"); for (int i = 0; i < 32; i++) { @@ -776,15 +788,15 @@ PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) dev->getStatistics(stats); PTF_PRINT_VERBOSE("Packets captured : " << stats.aggregatedRxStats.packets); PTF_PRINT_VERBOSE("Bytes captured : " << stats.aggregatedRxStats.bytes); - PTF_PRINT_VERBOSE("Bits per second : " << stats.aggregatedRxStats.bytesPerSec*8); + PTF_PRINT_VERBOSE("Bits per second : " << stats.aggregatedRxStats.bytesPerSec * 8); PTF_PRINT_VERBOSE("Packets per second : " << stats.aggregatedRxStats.packetsPerSec); PTF_PRINT_VERBOSE("Packets dropped : " << stats.rxPacketsDroppedByHW); PTF_PRINT_VERBOSE("Erroneous packets : " << stats.rxErroneousPackets); for (int i = 0; i < DPDK_MAX_RX_QUEUES; i++) { - PTF_PRINT_VERBOSE("Packets captured on RX queue #" << i << " according to stats: " << stats.rxStats[i].packets); + PTF_PRINT_VERBOSE("Packets captured on RX queue #" << i + << " according to stats: " << stats.rxStats[i].packets); PTF_PRINT_VERBOSE("Bytes captured on RX queue #" << i << " according to stats: " << stats.rxStats[i].bytes); - } pcpp::multiPlatformSleep(1); @@ -798,16 +810,17 @@ PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) pcpp::DpdkDeviceList::getInstance().stopDpdkWorkerThreads(); PTF_PRINT_VERBOSE("Worker threads stopped"); - // we can't guarantee all threads receive packets, it depends on the NIC load balancing and the traffic. So we check that all threads were run and - // that total amount of packets received by all threads is greater than zero + // we can't guarantee all threads receive packets, it depends on the NIC load balancing and the traffic. So we check + // that all threads were run and that total amount of packets received by all threads is greater than zero int packetCount = 0; - for (auto &iter : workerThreadVec) + for (auto& iter : workerThreadVec) { DpdkTestWorkerThread* thread = (DpdkTestWorkerThread*)iter; PTF_ASSERT_TRUE(thread->threadRanAndStopped()); packetCount += thread->getPacketCount(); - PTF_PRINT_VERBOSE("Worker thread on core " << thread->getCoreId() << " captured " << thread->getPacketCount() << " packets"); + PTF_PRINT_VERBOSE("Worker thread on core " << thread->getCoreId() << " captured " << thread->getPacketCount() + << " packets"); delete thread; } @@ -820,10 +833,7 @@ PTF_TEST_CASE(TestDpdkDeviceWorkerThreads) #else PTF_SKIP_TEST("DPDK not configured"); #endif -} // TestDpdkDeviceWorkerThreads - - - +} // TestDpdkDeviceWorkerThreads PTF_TEST_CASE(TestDpdkMbufRawPacket) { @@ -839,7 +849,6 @@ PTF_TEST_CASE(TestDpdkMbufRawPacket) PTF_ASSERT_TRUE(dev->openMultiQueues(numOfRxQueues, numOfTxQueues)); DeviceTeardown devTeardown(dev); - // Test load from PCAP to MBufRawPacket // ------------------------------------ pcpp::PcapFileReaderDevice reader(EXAMPLE2_PCAP_PATH); @@ -894,10 +903,12 @@ PTF_TEST_CASE(TestDpdkMbufRawPacket) { dev->receivePackets(rawPacketVec, i); pcpp::multiPlatformSleep(1); - for (pcpp::MBufRawPacketVector::VectorIterator iter = rawPacketVec.begin(); iter != rawPacketVec.end(); iter++) + for (pcpp::MBufRawPacketVector::VectorIterator iter = rawPacketVec.begin(); iter != rawPacketVec.end(); + iter++) { pcpp::Packet packet(*iter); - if ((packet.isPacketOfType(pcpp::TCP) || packet.isPacketOfType(pcpp::UDP)) && packet.isPacketOfType(pcpp::IPv4)) + if ((packet.isPacketOfType(pcpp::TCP) || packet.isPacketOfType(pcpp::UDP)) && + packet.isPacketOfType(pcpp::IPv4)) { foundTcpOrUdpPacket = true; break; @@ -987,25 +998,25 @@ PTF_TEST_CASE(TestDpdkMbufRawPacket) for (int i = 0; i < 10; i++) { // generate random string with random length < 40 - int nameLength = rand()%60; - char name[nameLength+1]; + int nameLength = rand() % 60; + char name[nameLength + 1]; for (int j = 0; j < nameLength; ++j) { - int randomChar = rand()%(26+26+10); + int randomChar = rand() % (26 + 26 + 10); if (randomChar < 26) name[j] = 'a' + randomChar; - else if (randomChar < 26+26) + else if (randomChar < 26 + 26) name[j] = 'A' + randomChar - 26; else name[j] = '0' + randomChar - 26 - 26; } name[nameLength] = 0; - //set name for query + // set name for query newQuery->setName(std::string(name)); packetToManipulate.computeCalculateFields(); - //transmit packet + // transmit packet PTF_ASSERT_TRUE(dev->sendPacket(packetToManipulate, 0)); } @@ -1014,4 +1025,4 @@ PTF_TEST_CASE(TestDpdkMbufRawPacket) #else PTF_SKIP_TEST("DPDK not configured"); #endif -} // TestDpdkMbufRawPacket +} // TestDpdkMbufRawPacket diff --git a/Tests/Pcap++Test/Tests/FileTests.cpp b/Tests/Pcap++Test/Tests/FileTests.cpp index 0647c714f8..4b8b567e1f 100644 --- a/Tests/Pcap++Test/Tests/FileTests.cpp +++ b/Tests/Pcap++Test/Tests/FileTests.cpp @@ -6,7 +6,6 @@ #include #include - class FileReaderTeardown { private: @@ -27,9 +26,6 @@ class FileReaderTeardown } }; - - - PTF_TEST_CASE(TestPcapFileReadWrite) { pcpp::PcapFileReaderDevice readerDev(EXAMPLE_PCAP_PATH); @@ -66,7 +62,6 @@ PTF_TEST_CASE(TestPcapFileReadWrite) PTF_ASSERT_TRUE(writerDev.writePacket(rawPacket)); } - pcpp::IPcapDevice::PcapStats readerStatistics; pcpp::IPcapDevice::PcapStats writerStatistics; @@ -102,26 +97,32 @@ PTF_TEST_CASE(TestPcapFileReadWrite) readerDev2.close(); PTF_ASSERT_FALSE(readerDev2.isOpened()); -} // TestPcapFileReadWrite +} // TestPcapFileReadWrite PTF_TEST_CASE(TestPcapFilePrecision) { - std::array testPayload = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; - pcpp::RawPacket rawPacketNano(testPayload.data(), testPayload.size(), timespec({1, 1234}), false); // 1.000001234 - pcpp::RawPacket rawPacketMicro(testPayload.data(), testPayload.size(), timeval({1, 2}), false); // 1.000002000 + std::array testPayload = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; + pcpp::RawPacket rawPacketNano(testPayload.data(), testPayload.size(), timespec({ 1, 1234 }), false); // 1.000001234 + pcpp::RawPacket rawPacketMicro(testPayload.data(), testPayload.size(), timeval({ 1, 2 }), false); // 1.000002000 // Writer precision support should equal to reader precision support - PTF_ASSERT_EQUAL(pcpp::PcapFileWriterDevice::isNanoSecondPrecisionSupported(), pcpp::PcapFileReaderDevice::isNanoSecondPrecisionSupported()); + PTF_ASSERT_EQUAL(pcpp::PcapFileWriterDevice::isNanoSecondPrecisionSupported(), + pcpp::PcapFileReaderDevice::isNanoSecondPrecisionSupported()); // Write nano precision file pcpp::PcapFileWriterDevice writerDevNano(EXAMPLE_PCAP_NANO_PATH, pcpp::LINKTYPE_ETHERNET, true); - PTF_ASSERT_EQUAL(writerDevNano.getTimestampPrecision(), pcpp::PcapFileWriterDevice::isNanoSecondPrecisionSupported() - ? pcpp::FileTimestampPrecision::Nanoseconds - : pcpp::FileTimestampPrecision::Microseconds, enumclass); + PTF_ASSERT_EQUAL(writerDevNano.getTimestampPrecision(), + pcpp::PcapFileWriterDevice::isNanoSecondPrecisionSupported() + ? pcpp::FileTimestampPrecision::Nanoseconds + : pcpp::FileTimestampPrecision::Microseconds, + enumclass); PTF_ASSERT_TRUE(writerDevNano.open()); - PTF_ASSERT_EQUAL(writerDevNano.getTimestampPrecision(), pcpp::PcapFileWriterDevice::isNanoSecondPrecisionSupported() - ? pcpp::FileTimestampPrecision::Nanoseconds - : pcpp::FileTimestampPrecision::Microseconds, enumclass); + PTF_ASSERT_EQUAL(writerDevNano.getTimestampPrecision(), + pcpp::PcapFileWriterDevice::isNanoSecondPrecisionSupported() + ? pcpp::FileTimestampPrecision::Nanoseconds + : pcpp::FileTimestampPrecision::Microseconds, + enumclass); PTF_ASSERT_TRUE(writerDevNano.writePacket(rawPacketMicro)); PTF_ASSERT_TRUE(writerDevNano.writePacket(rawPacketNano)); writerDevNano.close(); @@ -140,10 +141,10 @@ PTF_TEST_CASE(TestPcapFilePrecision) PTF_ASSERT_EQUAL(readerDevNano.getTimestampPrecision(), pcpp::FileTimestampPrecision::Unknown, enumclass); PTF_ASSERT_TRUE(readerDevNano.open()); PTF_ASSERT_EQUAL(readerDevNano.getTimestampPrecision(), - pcpp::PcapFileReaderDevice::isNanoSecondPrecisionSupported() - ? pcpp::FileTimestampPrecision::Nanoseconds - : pcpp::FileTimestampPrecision::Microseconds, - enumclass); + pcpp::PcapFileReaderDevice::isNanoSecondPrecisionSupported() + ? pcpp::FileTimestampPrecision::Nanoseconds + : pcpp::FileTimestampPrecision::Microseconds, + enumclass); pcpp::RawPacket readPacketNano, readPacketMicro; PTF_ASSERT_TRUE(readerDevNano.getNextPacket(readPacketMicro)); @@ -152,7 +153,8 @@ PTF_TEST_CASE(TestPcapFilePrecision) PTF_ASSERT_TRUE(readerDevNano.getNextPacket(readPacketNano)); PTF_ASSERT_EQUAL(readPacketNano.getPacketTimeStamp().tv_sec, 1); - PTF_ASSERT_EQUAL(readPacketNano.getPacketTimeStamp().tv_nsec, pcpp::PcapFileReaderDevice::isNanoSecondPrecisionSupported() ? 1234 : 1000); + PTF_ASSERT_EQUAL(readPacketNano.getPacketTimeStamp().tv_nsec, + pcpp::PcapFileReaderDevice::isNanoSecondPrecisionSupported() ? 1234 : 1000); readerDevNano.close(); @@ -161,10 +163,10 @@ PTF_TEST_CASE(TestPcapFilePrecision) PTF_ASSERT_EQUAL(readerDevMicro.getTimestampPrecision(), pcpp::FileTimestampPrecision::Unknown, enumclass); PTF_ASSERT_TRUE(readerDevMicro.open()); PTF_ASSERT_EQUAL(readerDevMicro.getTimestampPrecision(), - pcpp::PcapFileReaderDevice::isNanoSecondPrecisionSupported() - ? pcpp::FileTimestampPrecision::Nanoseconds - : pcpp::FileTimestampPrecision::Microseconds, - enumclass); + pcpp::PcapFileReaderDevice::isNanoSecondPrecisionSupported() + ? pcpp::FileTimestampPrecision::Nanoseconds + : pcpp::FileTimestampPrecision::Microseconds, + enumclass); pcpp::RawPacket readPacketNano2, readPacketMicro2; PTF_ASSERT_TRUE(readerDevMicro.getNextPacket(readPacketMicro2)); @@ -176,8 +178,7 @@ PTF_TEST_CASE(TestPcapFilePrecision) PTF_ASSERT_EQUAL(readPacketNano2.getPacketTimeStamp().tv_nsec, 1000); readerDevMicro.close(); -} // TestPcapFilePrecision - +} // TestPcapFilePrecision PTF_TEST_CASE(TestPcapSllFileReadWrite) { @@ -230,9 +231,7 @@ PTF_TEST_CASE(TestPcapSllFileReadWrite) readerDev.close(); writerDev.close(); -} // TestPcapSllFileReadWrite - - +} // TestPcapSllFileReadWrite PTF_TEST_CASE(TestPcapSll2FileReadWrite) { @@ -281,9 +280,7 @@ PTF_TEST_CASE(TestPcapSll2FileReadWrite) PTF_ASSERT_EQUAL(ipCount, 3); readerDev.close(); -} // TestPcapSll2FileReadWrite - - +} // TestPcapSll2FileReadWrite PTF_TEST_CASE(TestPcapRawIPFileReadWrite) { @@ -349,9 +346,7 @@ PTF_TEST_CASE(TestPcapRawIPFileReadWrite) readerDev.close(); writerDev.close(); writerNgDev.close(); -} // TestPcapRawIPFileReadWrite - - +} // TestPcapRawIPFileReadWrite PTF_TEST_CASE(TestPcapFileAppend) { @@ -384,16 +379,14 @@ PTF_TEST_CASE(TestPcapFileAppend) while (readerDev.getNextPacket(rawPacket)) counter++; - PTF_ASSERT_EQUAL(counter, (4631*5)); + PTF_ASSERT_EQUAL(counter, (4631 * 5)); pcpp::Logger::getInstance().suppressLogs(); pcpp::PcapFileWriterDevice writerDev2(EXAMPLE_PCAP_WRITE_PATH, pcpp::LINKTYPE_LINUX_SLL); PTF_ASSERT_FALSE(writerDev2.open(true)); pcpp::Logger::getInstance().enableLogs(); -} // TestPcapFileAppend - - +} // TestPcapFileAppend PTF_TEST_CASE(TestPcapNgFileReadWrite) { @@ -478,9 +471,7 @@ PTF_TEST_CASE(TestPcapNgFileReadWrite) writerDev.close(); writerCompressDev.close(); -} // TestPcapNgFileReadWrite - - +} // TestPcapNgFileReadWrite PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) { @@ -496,10 +487,13 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) PTF_ASSERT_TRUE(readerDev.open()); PTF_ASSERT_EQUAL(readerDev.getOS(), "Linux 3.18.1-1-ARCH"); PTF_ASSERT_EQUAL(readerDev.getCaptureApplication(), "Dumpcap (Wireshark) 1.99.1 (Git Rev Unknown from unknown)"); - PTF_ASSERT_EQUAL(readerDev.getCaptureFileComment(), "CLIENT_RANDOM E39B5BF4903C68684E8512FB2F60213E9EE843A0810B4982B607914D8092D482 95A5D39B02693BC1FB39254B179E9293007F6D37C66172B1EE4EF0D5E25CE1DABE878B6143DC3B266883E51A75E99DF9 "); + PTF_ASSERT_EQUAL(readerDev.getCaptureFileComment(), + "CLIENT_RANDOM E39B5BF4903C68684E8512FB2F60213E9EE843A0810B4982B607914D8092D482 " + "95A5D39B02693BC1FB39254B179E9293007F6D37C66172B1EE4EF0D5E25CE1DABE878B6143DC3B266883E51A75E99DF9 " + " "); PTF_ASSERT_EQUAL(readerDev.getHardware(), ""); - pcpp::PcapNgFileWriterDevice writerDev(EXAMPLE2_PCAPNG_WRITE_PATH); + pcpp::PcapNgFileWriterDevice writerDev(EXAMPLE2_PCAPNG_WRITE_PATH); pcpp::PcapNgFileWriterDevice writerCompressDev(EXAMPLE2_PCAPNG_ZSTD_WRITE_PATH, 5); // negative tests @@ -507,8 +501,11 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) writerCompressDev.close(); // -------------- - PTF_ASSERT_TRUE(writerDev.open(readerDev.getOS().c_str(), "My Hardware", readerDev.getCaptureApplication().c_str(), "This is a comment in a pcap-ng file")); - PTF_ASSERT_TRUE(writerCompressDev.open(readerDev.getOS().c_str(), "My Hardware", readerDev.getCaptureApplication().c_str(), "This is a comment in a pcap-ng file")); + PTF_ASSERT_TRUE(writerDev.open(readerDev.getOS().c_str(), "My Hardware", readerDev.getCaptureApplication().c_str(), + "This is a comment in a pcap-ng file")); + PTF_ASSERT_TRUE(writerCompressDev.open(readerDev.getOS().c_str(), "My Hardware", + readerDev.getCaptureApplication().c_str(), + "This is a comment in a pcap-ng file")); pcpp::RawPacket rawPacket; int packetCount = 0; @@ -593,7 +590,8 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) PTF_ASSERT_TRUE(readerDev3.open()); PTF_ASSERT_EQUAL(readerDevCompress.getOS(), "Linux 3.18.1-1-ARCH\0"); - PTF_ASSERT_EQUAL(readerDevCompress.getCaptureApplication(), "Dumpcap (Wireshark) 1.99.1 (Git Rev Unknown from unknown)"); + PTF_ASSERT_EQUAL(readerDevCompress.getCaptureApplication(), + "Dumpcap (Wireshark) 1.99.1 (Git Rev Unknown from unknown)"); PTF_ASSERT_EQUAL(readerDevCompress.getCaptureFileComment(), "This is a comment in a pcap-ng file"); PTF_ASSERT_EQUAL(readerDevCompress.getHardware(), "My Hardware"); @@ -612,8 +610,7 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) httpCount = 0; commentCount = 0; - - pcpp::RawPacket rawPacket2,rawPacketCompress; + pcpp::RawPacket rawPacket2, rawPacketCompress; while (readerDev2.getNextPacket(rawPacket, pktComment)) { @@ -680,7 +677,7 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) if (packet1_timestamp.tv_sec < packetCompress_timestamp.tv_sec) { uint64_t timeDiff = (uint64_t)(packetCompress_timestamp.tv_sec - packet1_timestamp.tv_sec); - PTF_ASSERT_LOWER_THAN(timeDiff,2); + PTF_ASSERT_LOWER_THAN(timeDiff, 2); } else { @@ -714,7 +711,7 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) readerDev2.close(); readerDev3.close(); - //For now appends are not fully supported with compressed pcapng files + // For now appends are not fully supported with compressed pcapng files pcpp::PcapNgFileWriterDevice appendDev(EXAMPLE2_PCAPNG_WRITE_PATH); PTF_ASSERT_TRUE(appendDev.open(true)); @@ -723,7 +720,6 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) appendDev.close(); - pcpp::PcapNgFileReaderDevice readerDev4(EXAMPLE2_PCAPNG_WRITE_PATH); PTF_ASSERT_TRUE(readerDev4.open()); @@ -739,8 +735,8 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) // ------- // copy the .zstd file to a similar file with .zst extension - std::ifstream zstdFile(EXAMPLE2_PCAPNG_ZSTD_WRITE_PATH, std::ios::binary); - std::ofstream zstFile(EXAMPLE2_PCAPNG_ZST_WRITE_PATH, std::ios::binary); + std::ifstream zstdFile(EXAMPLE2_PCAPNG_ZSTD_WRITE_PATH, std::ios::binary); + std::ofstream zstFile(EXAMPLE2_PCAPNG_ZST_WRITE_PATH, std::ios::binary); zstFile << zstdFile.rdbuf(); zstdFile.close(); zstFile.close(); @@ -779,7 +775,7 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) PTF_ASSERT_TRUE(writerDev2.setFilter("dst port 35938")); pcpp::PcapNgFileWriterDevice writerCompressDev2(EXAMPLE2_PCAPNG_ZSTD_WRITE_PATH, 5); - PTF_ASSERT_TRUE(writerCompressDev2.open()); //Do not try append mode on compressed files!!! + PTF_ASSERT_TRUE(writerCompressDev2.open()); // Do not try append mode on compressed files!!! PTF_ASSERT_FALSE(writerCompressDev2.setFilter("bla bla bla")); PTF_ASSERT_TRUE(writerCompressDev2.setFilter("dst port 35938")); @@ -789,7 +785,7 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) while (readerDev5.getNextPacket(rawPacket, pktComment)) { filteredReadPacketCount++; - if(writerDev2.writePacket(rawPacket)) + if (writerDev2.writePacket(rawPacket)) filteredWritePacketCount++; if (writerCompressDev2.writePacket(rawPacket)) filteredCompressWritePacketCount++; @@ -802,9 +798,7 @@ PTF_TEST_CASE(TestPcapNgFileReadWriteAdv) writerCompressDev2.close(); readerDev5.close(); writerDev2.close(); -} // TestPcapNgFileReadWriteAdv - - +} // TestPcapNgFileReadWriteAdv PTF_TEST_CASE(TestPcapNgFileTooManyInterfaces) { @@ -824,9 +818,7 @@ PTF_TEST_CASE(TestPcapNgFileTooManyInterfaces) } PTF_ASSERT_EQUAL(packetCount, 1); readerDev.close(); -} // TestPcapNgFileTooManyInterfaces - - +} // TestPcapNgFileTooManyInterfaces PTF_TEST_CASE(TestPcapFileReadLinkTypeIPv6) { @@ -854,7 +846,6 @@ PTF_TEST_CASE(TestPcapFileReadLinkTypeIPv6) udpCount++; } - pcpp::IPcapDevice::PcapStats readerStatistics; readerDev.getStatistics(readerStatistics); @@ -870,7 +861,7 @@ PTF_TEST_CASE(TestPcapFileReadLinkTypeIPv6) readerDev.close(); PTF_ASSERT_FALSE(readerDev.isOpened()); -} // TestPcapFileReadLinkTypeIPv6 +} // TestPcapFileReadLinkTypeIPv6 PTF_TEST_CASE(TestPcapFileReadLinkTypeIPv4) { @@ -898,7 +889,6 @@ PTF_TEST_CASE(TestPcapFileReadLinkTypeIPv4) udpCount++; } - pcpp::IPcapDevice::PcapStats readerStatistics; readerDev.getStatistics(readerStatistics); @@ -914,7 +904,7 @@ PTF_TEST_CASE(TestPcapFileReadLinkTypeIPv4) readerDev.close(); PTF_ASSERT_FALSE(readerDev.isOpened()); -} // TestPcapFileReadLinkTypeIPv4 +} // TestPcapFileReadLinkTypeIPv4 PTF_TEST_CASE(TestSolarisSnoopFileRead) { @@ -963,4 +953,4 @@ PTF_TEST_CASE(TestSolarisSnoopFileRead) PTF_ASSERT_EQUAL(timeStamps[249].tv_nsec, 499893000); readerDev.close(); -} // TestSolarisSnoopFileRead +} // TestSolarisSnoopFileRead diff --git a/Tests/Pcap++Test/Tests/FilterTests.cpp b/Tests/Pcap++Test/Tests/FilterTests.cpp index ac22767762..b0f96803e1 100644 --- a/Tests/Pcap++Test/Tests/FilterTests.cpp +++ b/Tests/Pcap++Test/Tests/FilterTests.cpp @@ -15,7 +15,6 @@ extern PcapTestArgs PcapTestGlobalArgs; - static int incSleep(const pcpp::RawPacketVector& capturedPackets, size_t expectedPacketCount, int maxTimeToSleep) { int totalSleepTime = 0; @@ -33,8 +32,6 @@ static int incSleep(const pcpp::RawPacketVector& capturedPackets, size_t expecte return totalSleepTime; } - - PTF_TEST_CASE(TestPcapFiltersLive) { pcpp::PcapLiveDevice* liveDev = nullptr; @@ -48,7 +45,7 @@ PTF_TEST_CASE(TestPcapFiltersLive) pcpp::RawPacketVector capturedPackets; //----------- - //IP filter + // IP filter //----------- PTF_PRINT_VERBOSE("Testing IPFilter"); std::string filterAddrAsString(PcapTestGlobalArgs.ipToSendReceivePackets); @@ -57,13 +54,12 @@ PTF_TEST_CASE(TestPcapFiltersLive) PTF_ASSERT_TRUE(liveDev->setFilter(ipFilter)); PTF_ASSERT_TRUE(liveDev->startCapture(capturedPackets)); PTF_ASSERT_TRUE(sendURLRequest("www.google.com")); - //let the capture work for couple of seconds + // let the capture work for couple of seconds int totalSleepTime = incSleep(capturedPackets, 2, 7); PTF_PRINT_VERBOSE("Total sleep time: " << totalSleepTime); liveDev->stopCapture(); PTF_ASSERT_GREATER_OR_EQUAL_THAN(capturedPackets.size(), 2); - for (pcpp::RawPacketVector::VectorIterator iter = capturedPackets.begin(); iter != capturedPackets.end(); iter++) { pcpp::Packet packet(*iter); @@ -73,9 +69,8 @@ PTF_TEST_CASE(TestPcapFiltersLive) } capturedPackets.clear(); - //------------ - //Port filter + // Port filter //------------ PTF_PRINT_VERBOSE("Testing PortFilter"); uint16_t filterPort = 80; @@ -84,7 +79,7 @@ PTF_TEST_CASE(TestPcapFiltersLive) PTF_ASSERT_TRUE(liveDev->setFilter(portFilter)); PTF_ASSERT_TRUE(liveDev->startCapture(capturedPackets)); PTF_ASSERT_TRUE(sendURLRequest("www.yahoo.com")); - //let the capture work for couple of seconds + // let the capture work for couple of seconds totalSleepTime = incSleep(capturedPackets, 2, 7); PTF_PRINT_VERBOSE("Total sleep time: " << totalSleepTime); liveDev->stopCapture(); @@ -98,9 +93,8 @@ PTF_TEST_CASE(TestPcapFiltersLive) } capturedPackets.clear(); - //---------------- - //IP & Port filter + // IP & Port filter //---------------- PTF_PRINT_VERBOSE("Testing IP and Port Filter"); std::vector andFilterFilters; @@ -111,7 +105,7 @@ PTF_TEST_CASE(TestPcapFiltersLive) PTF_ASSERT_TRUE(liveDev->setFilter(andFilter)); PTF_ASSERT_TRUE(liveDev->startCapture(capturedPackets)); PTF_ASSERT_TRUE(sendURLRequest("www.walla.co.il")); - //let the capture work for couple of seconds + // let the capture work for couple of seconds totalSleepTime = incSleep(capturedPackets, 2, 7); PTF_PRINT_VERBOSE("Total sleep time: " << totalSleepTime); liveDev->stopCapture(); @@ -128,9 +122,8 @@ PTF_TEST_CASE(TestPcapFiltersLive) } capturedPackets.clear(); - //----------------- - //IP || Port filter + // IP || Port filter //----------------- PTF_PRINT_VERBOSE("Testing IP or Port Filter"); std::vector orFilterFilters; @@ -142,7 +135,7 @@ PTF_TEST_CASE(TestPcapFiltersLive) PTF_ASSERT_TRUE(liveDev->setFilter(orFilter)); PTF_ASSERT_TRUE(liveDev->startCapture(capturedPackets)); PTF_ASSERT_TRUE(sendURLRequest("www.youtube.com")); - //let the capture work for couple of seconds + // let the capture work for couple of seconds totalSleepTime = incSleep(capturedPackets, 2, 7); PTF_PRINT_VERBOSE("Total sleep time: " << totalSleepTime); liveDev->stopCapture(); @@ -171,9 +164,8 @@ PTF_TEST_CASE(TestPcapFiltersLive) } capturedPackets.clear(); - //---------- - //Not filter + // Not filter //---------- PTF_PRINT_VERBOSE("Testing Not IP Filter"); ipFilter.setDirection(pcpp::SRC); @@ -182,7 +174,7 @@ PTF_TEST_CASE(TestPcapFiltersLive) PTF_ASSERT_TRUE(liveDev->setFilter(notFilter)); PTF_ASSERT_TRUE(liveDev->startCapture(capturedPackets)); PTF_ASSERT_TRUE(sendURLRequest("www.ebay.com")); - //let the capture work for couple of seconds + // let the capture work for couple of seconds totalSleepTime = incSleep(capturedPackets, 2, 7); PTF_PRINT_VERBOSE("Total sleep time: " << totalSleepTime); liveDev->stopCapture(); @@ -198,13 +190,9 @@ PTF_TEST_CASE(TestPcapFiltersLive) } capturedPackets.clear(); - liveDev->close(); -} // TestPcapFiltersLive - - - +} // TestPcapFiltersLive PTF_TEST_CASE(TestPcapFilters_General_BPFStr) { @@ -214,14 +202,14 @@ PTF_TEST_CASE(TestPcapFilters_General_BPFStr) pcpp::PcapFileReaderDevice fileReaderDev(EXAMPLE_PCAP_VLAN); //------------------------------------ - //Test GeneralFilter + BPFStringFilter + // Test GeneralFilter + BPFStringFilter //------------------------------------ - //Try to make an invalid filter + // Try to make an invalid filter pcpp::BPFStringFilter badFilter("This is not a valid filter"); PTF_ASSERT_FALSE(badFilter.verifyFilter()); - //Test stolen from MacAddress test below + // Test stolen from MacAddress test below pcpp::MacAddress macAddr("00:13:c3:df:ae:18"); pcpp::BPFStringFilter bpfStringFilter("ether dst " + macAddr.toString()); PTF_ASSERT_TRUE(bpfStringFilter.verifyFilter()); @@ -247,10 +235,7 @@ PTF_TEST_CASE(TestPcapFilters_General_BPFStr) PTF_ASSERT_EQUAL(validCounter, 5); rawPacketVec.clear(); -} // TestPcapFilters_General_BPFStr - - - +} // TestPcapFilters_General_BPFStr PTF_TEST_CASE(TestPcapFilters_MatchStatic) { @@ -270,10 +255,7 @@ PTF_TEST_CASE(TestPcapFilters_MatchStatic) } rawPacketVec.clear(); -} // TestPcapFilters_MatchStatic - - - +} // TestPcapFilters_MatchStatic PTF_TEST_CASE(TestPcapFiltersOffline) { @@ -286,7 +268,7 @@ PTF_TEST_CASE(TestPcapFiltersOffline) pcpp::PcapFileReaderDevice fileReaderDev4(EXAMPLE_PCAP_IGMP); //----------------- - //VLAN filter + // VLAN filter //----------------- pcpp::VlanFilter vlanFilter(118); @@ -308,9 +290,8 @@ PTF_TEST_CASE(TestPcapFiltersOffline) rawPacketVec.clear(); - //-------------------- - //MacAddress filter + // MacAddress filter //-------------------- pcpp::MacAddress macAddrToFilter("00:13:c3:df:ae:18"); pcpp::MacAddressFilter macAddrFilter(macAddrToFilter, pcpp::DST); @@ -331,9 +312,8 @@ PTF_TEST_CASE(TestPcapFiltersOffline) rawPacketVec.clear(); - //-------------------- - //EtherType filter + // EtherType filter //-------------------- pcpp::EtherTypeFilter ethTypeFiler(PCPP_ETHERTYPE_VLAN); ethTypeFiler.parseToString(filterAsString); @@ -352,9 +332,8 @@ PTF_TEST_CASE(TestPcapFiltersOffline) rawPacketVec.clear(); - //-------------------- - //IPv4 ID filter + // IPv4 ID filter //-------------------- uint16_t ipID(0x9900); pcpp::IPv4IDFilter ipIDFiler(ipID, pcpp::GREATER_THAN); @@ -376,9 +355,8 @@ PTF_TEST_CASE(TestPcapFiltersOffline) rawPacketVec.clear(); - //------------------------- - //IPv4 Total Length filter + // IPv4 Total Length filter //------------------------- uint16_t totalLength(576); pcpp::IPv4TotalLengthFilter ipTotalLengthFiler(totalLength, pcpp::LESS_OR_EQUAL); @@ -400,9 +378,8 @@ PTF_TEST_CASE(TestPcapFiltersOffline) rawPacketVec.clear(); - //------------------------- - //TCP window size filter + // TCP window size filter //------------------------- uint16_t windowSize(8312); pcpp::TcpWindowSizeFilter tcpWindowSizeFilter(windowSize, pcpp::NOT_EQUALS); @@ -424,9 +401,8 @@ PTF_TEST_CASE(TestPcapFiltersOffline) rawPacketVec.clear(); - //------------------------- - //UDP length filter + // UDP length filter //------------------------- uint16_t udpLength(46); pcpp::UdpLengthFilter udpLengthFilter(udpLength, pcpp::EQUALS); @@ -448,15 +424,15 @@ PTF_TEST_CASE(TestPcapFiltersOffline) rawPacketVec.clear(); - //------------------------- - //IP filter with mask + // IP filter with mask //------------------------- pcpp::IPFilter ipFilterWithMask("212.199.202.9", pcpp::SRC, "255.255.255.0"); ipFilterWithMask.parseToString(filterAsString); PTF_ASSERT_EQUAL(filterAsString, "ip and src net 212.199.202.0/24"); - PTF_ASSERT_RAISES(ipFilterWithMask.setAddr("BogusIPAddressString"), std::invalid_argument, "Not a valid IP address: BogusIPAddressString"); + PTF_ASSERT_RAISES(ipFilterWithMask.setAddr("BogusIPAddressString"), std::invalid_argument, + "Not a valid IP address: BogusIPAddressString"); PTF_ASSERT_TRUE(fileReaderDev2.open()); PTF_ASSERT_TRUE(fileReaderDev2.setFilter(ipFilterWithMask)); @@ -518,7 +494,8 @@ PTF_TEST_CASE(TestPcapFiltersOffline) ipFilterWithMask.parseToString(filterAsString); PTF_ASSERT_EQUAL(filterAsString, "ip6 and src net 2001:db8:3333:4444:cccc:dddd:eeee:ffff/128"); - PTF_ASSERT_RAISES(ipFilterWithMask.setMask("255.255.255.255"), std::invalid_argument, "Netmask is not valid IPv6 format: 255.255.255.255"); + PTF_ASSERT_RAISES(ipFilterWithMask.setMask("255.255.255.255"), std::invalid_argument, + "Netmask is not valid IPv6 format: 255.255.255.255"); ipFilterWithMask.setMask("ffff:ffff:ffff::"); ipFilterWithMask.parseToString(filterAsString); PTF_ASSERT_EQUAL(filterAsString, "ip6 and src net 2001:db8:3333::/48"); @@ -546,7 +523,7 @@ PTF_TEST_CASE(TestPcapFiltersOffline) { pcpp::Packet packet(*iter); PTF_ASSERT_TRUE(packet.isPacketOfType(pcpp::IPv6)); - pcpp::IPv6Layer *ipLayer = packet.getLayerOfType(); + pcpp::IPv6Layer* ipLayer = packet.getLayerOfType(); // This is essentially matching the host address, but it will have to do for the current sample. PTF_ASSERT_TRUE(ipLayer->getSrcIPv6Address().matchNetwork("2001:db8:0:12::1/128")); } @@ -563,13 +540,13 @@ PTF_TEST_CASE(TestPcapFiltersOffline) { pcpp::Packet packet(*iter); PTF_ASSERT_TRUE(packet.isPacketOfType(pcpp::IPv6)); - pcpp::IPv6Layer *ipLayer = packet.getLayerOfType(); + pcpp::IPv6Layer* ipLayer = packet.getLayerOfType(); PTF_ASSERT_TRUE(ipLayer->getSrcIPv6Address().matchNetwork("2001:db8:0:12::/64")); } rawPacketVec.clear(); //------------- - //Port range + // Port range //------------- pcpp::PortRangeFilter portRangeFilter(40000, 50000, pcpp::SRC); portRangeFilter.parseToString(filterAsString); @@ -589,22 +566,21 @@ PTF_TEST_CASE(TestPcapFiltersOffline) { pcpp::TcpLayer* tcpLayer = packet.getLayerOfType(); uint16_t portSrc = tcpLayer->getSrcPort(); - PTF_ASSERT_TRUE(portSrc >= 40000 && portSrc <=50000); + PTF_ASSERT_TRUE(portSrc >= 40000 && portSrc <= 50000); } else if (packet.isPacketOfType(pcpp::UDP)) { pcpp::UdpLayer* udpLayer = packet.getLayerOfType(); uint16_t portSrc = udpLayer->getSrcPort(); - PTF_ASSERT_TRUE(portSrc >= 40000 && portSrc <=50000); + PTF_ASSERT_TRUE(portSrc >= 40000 && portSrc <= 50000); } } rawPacketVec.clear(); - //------------------------- - //TCP flags filter + // TCP flags filter //------------------------- - uint8_t tcpFlagsBitMask(pcpp::TcpFlagsFilter::tcpSyn|pcpp::TcpFlagsFilter::tcpAck); + uint8_t tcpFlagsBitMask(pcpp::TcpFlagsFilter::tcpSyn | pcpp::TcpFlagsFilter::tcpAck); pcpp::TcpFlagsFilter tcpFlagsFilter(tcpFlagsBitMask, pcpp::TcpFlagsFilter::MatchAll); tcpFlagsFilter.parseToString(filterAsString); @@ -643,9 +619,8 @@ PTF_TEST_CASE(TestPcapFiltersOffline) rawPacketVec.clear(); - //------------ - //Proto filter + // Proto filter //------------ // ARP proto @@ -734,7 +709,7 @@ PTF_TEST_CASE(TestPcapFiltersOffline) rawPacketVec.clear(); //----------------------- - //And filter - Proto + IP + // And filter - Proto + IP //----------------------- pcpp::IPFilter ipFilter("10.0.0.6", pcpp::SRC); @@ -785,9 +760,8 @@ PTF_TEST_CASE(TestPcapFiltersOffline) rawPacketVec.clear(); - //------------------------------------------ - //Complex filter - (Proto1 and IP) || Proto2 + // Complex filter - (Proto1 and IP) || Proto2 //------------------------------------------ protoFilter.setProto(pcpp::GRE); @@ -826,9 +800,9 @@ PTF_TEST_CASE(TestPcapFiltersOffline) PTF_ASSERT_TRUE(packet.isPacketOfType(pcpp::GRE)); PTF_ASSERT_TRUE(packet.isPacketOfType(pcpp::IPv4)); pcpp::IPv4Layer* ipv4Layer = packet.getLayerOfType(); - PTF_ASSERT_TRUE(ipv4Layer->getSrcIPAddress().toString() == "20.0.0.1" || ipv4Layer->getDstIPAddress().toString() == "20.0.0.1"); + PTF_ASSERT_TRUE(ipv4Layer->getSrcIPAddress().toString() == "20.0.0.1" || + ipv4Layer->getDstIPAddress().toString() == "20.0.0.1"); } - } rawPacketVec.clear(); } @@ -848,12 +822,13 @@ PTF_TEST_CASE(TestPcapFilters_LinkLayer) for (pcpp::RawPacketVector::VectorIterator iter = rawPacketVec.begin(); iter != rawPacketVec.end(); iter++) { pcpp::Packet packet(*iter); - if(pcpp::IPv4Layer* ip4layer = packet.getLayerOfType()) + if (pcpp::IPv4Layer* ip4layer = packet.getLayerOfType()) { - pcpp::BPFStringFilter bpfStringFilter("host " + ip4layer->getDstIPAddress().toString()); // checking against real filter, not the "" filter + pcpp::BPFStringFilter bpfStringFilter( + "host " + ip4layer->getDstIPAddress().toString()); // checking against real filter, not the "" filter if (bpfStringFilter.matchPacketWithFilter(*iter)) { - if((*iter)->getLinkLayerType() == pcpp::LINKTYPE_DLT_RAW1) + if ((*iter)->getLinkLayerType() == pcpp::LINKTYPE_DLT_RAW1) { ++validCounter; } @@ -863,7 +838,6 @@ PTF_TEST_CASE(TestPcapFilters_LinkLayer) PTF_ASSERT_EQUAL(validCounter, 50); rawPacketVec.clear(); - // pcpp::LINKTYPE_LINUX_SLL layer pcpp::PcapFileReaderDevice fileReaderDev2(SLL_PCAP_PATH); PTF_ASSERT_TRUE(fileReaderDev2.open()); @@ -874,12 +848,13 @@ PTF_TEST_CASE(TestPcapFilters_LinkLayer) for (pcpp::RawPacketVector::VectorIterator iter = rawPacketVec.begin(); iter != rawPacketVec.end(); iter++) { pcpp::Packet packet(*iter); - if(pcpp::IPv4Layer* ip4layer = packet.getLayerOfType()) + if (pcpp::IPv4Layer* ip4layer = packet.getLayerOfType()) { - pcpp::BPFStringFilter bpfStringFilter("host " + ip4layer->getDstIPAddress().toString()); // checking against real filter, not the "" filter + pcpp::BPFStringFilter bpfStringFilter( + "host " + ip4layer->getDstIPAddress().toString()); // checking against real filter, not the "" filter if (bpfStringFilter.matchPacketWithFilter(*iter)) { - if((*iter)->getLinkLayerType() == pcpp::LINKTYPE_LINUX_SLL) + if ((*iter)->getLinkLayerType() == pcpp::LINKTYPE_LINUX_SLL) { ++validCounter; } @@ -889,7 +864,6 @@ PTF_TEST_CASE(TestPcapFilters_LinkLayer) PTF_ASSERT_EQUAL(validCounter, 510); rawPacketVec.clear(); - // pcpp::LINKTYPE_ETHERNET layer pcpp::PcapNgFileReaderDevice fileReaderDev3(EXAMPLE_PCAPNG_PATH); PTF_ASSERT_TRUE(fileReaderDev3.open()); @@ -900,12 +874,13 @@ PTF_TEST_CASE(TestPcapFilters_LinkLayer) for (pcpp::RawPacketVector::VectorIterator iter = rawPacketVec.begin(); iter != rawPacketVec.end(); iter++) { pcpp::Packet packet(*iter); - if(pcpp::IPv4Layer* ip4layer = packet.getLayerOfType()) + if (pcpp::IPv4Layer* ip4layer = packet.getLayerOfType()) { - pcpp::BPFStringFilter bpfStringFilter("host " + ip4layer->getDstIPAddress().toString()); // checking against real filter, not the "" filter + pcpp::BPFStringFilter bpfStringFilter( + "host " + ip4layer->getDstIPAddress().toString()); // checking against real filter, not the "" filter if (bpfStringFilter.matchPacketWithFilter(*iter)) { - if((*iter)->getLinkLayerType() == pcpp::LINKTYPE_ETHERNET) + if ((*iter)->getLinkLayerType() == pcpp::LINKTYPE_ETHERNET) { ++validCounter; } @@ -914,4 +889,4 @@ PTF_TEST_CASE(TestPcapFilters_LinkLayer) } PTF_ASSERT_EQUAL(validCounter, 62); rawPacketVec.clear(); -} // TestPcapFilters_LinkLayer +} // TestPcapFilters_LinkLayer diff --git a/Tests/Pcap++Test/Tests/IPFragmentationTests.cpp b/Tests/Pcap++Test/Tests/IPFragmentationTests.cpp index b7c3fae859..bb44da7d38 100644 --- a/Tests/Pcap++Test/Tests/IPFragmentationTests.cpp +++ b/Tests/Pcap++Test/Tests/IPFragmentationTests.cpp @@ -6,14 +6,13 @@ #include "PcapFileDevice.h" #include "EndianPortable.h" - static void ipReassemblyOnFragmentsClean(const pcpp::IPReassembly::PacketKey* key, void* userCookie) { - pcpp::PointerVector* packetsRemoved = (pcpp::PointerVector*)userCookie; + pcpp::PointerVector* packetsRemoved = + (pcpp::PointerVector*)userCookie; packetsRemoved->pushBack(key->clone()); } - PTF_TEST_CASE(TestIPFragmentationSanity) { std::vector packetStream; @@ -75,8 +74,7 @@ PTF_TEST_CASE(TestIPFragmentationSanity) PTF_ASSERT_BUF_COMPARE(result->getRawPacket()->getRawData(), buffer, bufferLength); delete result; - delete [] buffer; - + delete[] buffer; // basic IPv6 reassembly test // ========================== @@ -129,8 +127,7 @@ PTF_TEST_CASE(TestIPFragmentationSanity) PTF_ASSERT_BUF_COMPARE(result->getRawPacket()->getRawData(), buffer, bufferLength); delete result; - delete [] buffer; - + delete[] buffer; // non-fragment test // ================== @@ -149,7 +146,6 @@ PTF_TEST_CASE(TestIPFragmentationSanity) PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::NON_FRAGMENT, enum); } - // non-IP test // ================== @@ -163,8 +159,7 @@ PTF_TEST_CASE(TestIPFragmentationSanity) PTF_ASSERT_EQUAL(result, &packet, ptr); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::NON_IP_PACKET, enum); } -} // TestIPFragmentationSanity - +} // TestIPFragmentationSanity PTF_TEST_CASE(TestIPFragOutOfOrder) { @@ -179,7 +174,6 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) int bufferLength = 0; uint8_t* buffer = readFileIntoBuffer("PcapExamples/frag_http_req_reassembled.txt", bufferLength); - // First use-case: first and second fragments are swapped // ====================================================== @@ -203,7 +197,7 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) { PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::FIRST_FRAGMENT, enum); } - else if (i < (packetStream.size()-1)) + else if (i < (packetStream.size() - 1)) { PTF_ASSERT_NULL(result); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::FRAGMENT, enum); @@ -224,16 +218,15 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) packetStream.clear(); - // Second use-case: 6th and 10th fragments are swapped, as well as 3rd and 7th // =========================================================================== PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/frag_http_req.pcap", packetStream, errMsg)); - //swap 6th and 10th fragments + // swap 6th and 10th fragments std::swap(packetStream[5], packetStream[9]); - //swap 3rd and 7th fragments + // swap 3rd and 7th fragments std::swap(packetStream[2], packetStream[6]); PTF_PRINT_VERBOSE("Second use-case: iterating over packet stream"); @@ -252,7 +245,7 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) { PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::FIRST_FRAGMENT, enum); } - else if (i < (packetStream.size()-1)) + else if (i < (packetStream.size() - 1)) { PTF_ASSERT_NULL(result); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::FRAGMENT, enum); @@ -273,13 +266,12 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) packetStream.clear(); - // Third use-case: last fragment comes before the end // ================================================== PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/frag_http_req.pcap", packetStream, errMsg)); - //swap 6th and last fragments + // swap 6th and last fragments std::swap(packetStream[5], packetStream[10]); PTF_PRINT_VERBOSE("Third use-case: iterating over packet stream"); @@ -289,7 +281,7 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) pcpp::Packet packet(&packetStream.at(i)); result = ipReassembly.processPacket(&packet, status); - if (i >= 5 && i < (packetStream.size()-1)) + if (i >= 5 && i < (packetStream.size() - 1)) { PTF_ASSERT_NULL(result); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::OUT_OF_ORDER_FRAGMENT, enum); @@ -319,7 +311,6 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) packetStream.clear(); - // Fourth use-case: last fragment comes first // ========================================== @@ -346,7 +337,7 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) { PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::FIRST_FRAGMENT, enum); } - else if (i < (packetStream.size()-1)) + else if (i < (packetStream.size() - 1)) { PTF_ASSERT_NULL(result); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::FRAGMENT, enum); @@ -367,7 +358,6 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) packetStream.clear(); - // Fifth use-case: fragments come in reverse order // =============================================== @@ -388,7 +378,7 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) pcpp::Packet packet(&packetStream.at(i)); result = ipReassembly.processPacket(&packet, status); - if (i < (packetStream.size()-1)) + if (i < (packetStream.size() - 1)) { PTF_ASSERT_NULL(result); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::OUT_OF_ORDER_FRAGMENT, enum); @@ -408,8 +398,7 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) packetStream.clear(); - delete [] buffer; - + delete[] buffer; // Sixth use-case: IPv6: fragments 1 and 3 are swapped, as well as fragments 6 and 7 // ================================================================================= @@ -457,9 +446,8 @@ PTF_TEST_CASE(TestIPFragOutOfOrder) delete result; - delete [] buffer2; -} // TestIPFragOutOfOrder - + delete[] buffer2; +} // TestIPFragOutOfOrder PTF_TEST_CASE(TestIPFragPartialData) { @@ -483,7 +471,8 @@ PTF_TEST_CASE(TestIPFragPartialData) ipReassembly.processPacket(&packet, status); } - pcpp::IPReassembly::IPv4PacketKey ip4Key(16991, pcpp::IPv4Address(std::string("172.16.133.54")), pcpp::IPv4Address(std::string("216.137.33.81"))); + pcpp::IPReassembly::IPv4PacketKey ip4Key(16991, pcpp::IPv4Address(std::string("172.16.133.54")), + pcpp::IPv4Address(std::string("216.137.33.81"))); pcpp::Packet* partialPacket = ipReassembly.getCurrentPacket(ip4Key); PTF_ASSERT_NOT_NULL(partialPacket); @@ -491,8 +480,7 @@ PTF_TEST_CASE(TestIPFragPartialData) PTF_ASSERT_BUF_COMPARE(partialPacket->getRawPacket()->getRawData(), buffer, bufferLength); delete partialPacket; - delete [] buffer; - + delete[] buffer; // IPv6 partial data // ~~~~~~~~~~~~~~~~~ @@ -515,7 +503,8 @@ PTF_TEST_CASE(TestIPFragPartialData) ipReassembly.processPacket(&packet, status); } - pcpp::IPReassembly::IPv6PacketKey ip6Key(0x2c5323, pcpp::IPv6Address(std::string("fe80::21f:f3ff:fecd:f617")), pcpp::IPv6Address(std::string("ff02::fb"))); + pcpp::IPReassembly::IPv6PacketKey ip6Key(0x2c5323, pcpp::IPv6Address(std::string("fe80::21f:f3ff:fecd:f617")), + pcpp::IPv6Address(std::string("ff02::fb"))); partialPacket = ipReassembly.getCurrentPacket(ip6Key); PTF_ASSERT_EQUAL(partialPacket->getRawPacket()->getRawDataLen(), bufferLength); PTF_ASSERT_BUF_COMPARE(partialPacket->getRawPacket()->getRawData(), buffer, bufferLength); @@ -523,9 +512,8 @@ PTF_TEST_CASE(TestIPFragPartialData) PTF_ASSERT_NOT_NULL(partialPacket); delete partialPacket; - delete [] buffer; -} // TestIPFragPartialData - + delete[] buffer; +} // TestIPFragPartialData PTF_TEST_CASE(TestIPFragMultipleFrags) { @@ -549,7 +537,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) pcpp::RawPacketVector ip6Packet3Frags; pcpp::RawPacketVector ip6Packet4Frags; - PTF_ASSERT_EQUAL(reader.getNextPackets(ip4Packet1Frags, 6), 6); PTF_ASSERT_EQUAL(reader.getNextPackets(ip4Packet2Frags, 6), 6); PTF_ASSERT_EQUAL(reader.getNextPackets(ip4Packet3Frags, 6), 6); @@ -585,7 +572,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) pcpp::Packet* ip6Packet3; pcpp::Packet* ip6Packet4; - pcpp::IPReassembly ipReassembly; pcpp::IPReassembly::ReassemblyStatus status; @@ -628,13 +614,12 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_EQUAL(ipReassembly.getCurrentCapacity(), 10); - // read 2nd - 5th frag in each packet PTF_PRINT_VERBOSE("read 2nd - 5th frag in each packet"); for (int i = 1; i < 5; i++) { - PTF_PRINT_VERBOSE("Frag#" << i+1); + PTF_PRINT_VERBOSE("Frag#" << i + 1); ip4Packet1 = ipReassembly.processPacket(ip4Packet1Frags.at(i), status); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::FRAGMENT, enum); @@ -670,7 +655,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_EQUAL(ipReassembly.getCurrentCapacity(), 10); - // read 6th frag in IPv4 packets 1,2,3 ip4Packet1 = ipReassembly.processPacket(ip4Packet1Frags.at(5), status); @@ -685,7 +669,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_EQUAL(ipReassembly.getCurrentCapacity(), 7); - // read IPv4 packet5 ip4Packet5 = ipReassembly.processPacket(ip4Packet5Vec.at(0), status); @@ -693,7 +676,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_NOT_NULL(ip4Packet5); PTF_ASSERT_EQUAL(ip4Packet5->getRawPacket(), ip4Packet5Vec.at(0), ptr); - // read 6th - 7th frag in IPv6 packets 1,4 ip6Packet1 = ipReassembly.processPacket(ip6Packet1Frags.at(5), status); @@ -711,13 +693,12 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_EQUAL(ipReassembly.getCurrentCapacity(), 5); - // read 6th - 9th frag in IPv4 packets 4,6,8 and IPv6 packet 2 PTF_PRINT_VERBOSE("read 6th - 9th frag in IPv4 packets 4,6,8 and IPv6 packet 2"); for (int i = 5; i < 9; i++) { - PTF_PRINT_VERBOSE("Frag#" << i+1); + PTF_PRINT_VERBOSE("Frag#" << i + 1); ip4Packet4 = ipReassembly.processPacket(ip4Packet4Frags.at(i), status); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::FRAGMENT, enum); @@ -733,13 +714,12 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_NULL(ip6Packet2); } - // read 6th - 9th frag in IPv6 packet 3 PTF_PRINT_VERBOSE("read 6th - 8th frag in IPv6 packet 3"); for (int i = 5; i < 8; i++) { - PTF_PRINT_VERBOSE("Frag#" << i+1); + PTF_PRINT_VERBOSE("Frag#" << i + 1); ip6Packet3 = ipReassembly.processPacket(ip6Packet3Frags.at(i), status); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::FRAGMENT, enum); PTF_ASSERT_NULL(ip6Packet3); @@ -751,7 +731,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_EQUAL(ipReassembly.getCurrentCapacity(), 4, enum); - // read IPv4 packet7 ip4Packet7 = ipReassembly.processPacket(ip4Packet7Vec.at(0), status); @@ -759,7 +738,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_NOT_NULL(ip4Packet7); PTF_ASSERT_EQUAL(ip4Packet7->getRawPacket(), ip4Packet7Vec.at(0), ptr); - // read 10th frag in IPv4 packets 4,6,8 ip4Packet4 = ipReassembly.processPacket(ip4Packet4Frags.at(9), status); @@ -774,7 +752,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_EQUAL(ipReassembly.getCurrentCapacity(), 1); - // read IPv4 packet 9 ip4Packet9 = ipReassembly.processPacket(ip4Packet9Vec.at(0), status); @@ -782,7 +759,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_NOT_NULL(ip4Packet9); PTF_ASSERT_EQUAL(ip4Packet9->getRawPacket(), ip4Packet9Vec.at(0), ptr); - // read 11th frag in IPv4 packets 4,6 (duplicated last frag) PTF_ASSERT_NULL(ipReassembly.processPacket(ip4Packet4Frags.at(10), status)); @@ -790,13 +766,12 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_NULL(ipReassembly.processPacket(ip4Packet6Frags.at(10), status)); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::OUT_OF_ORDER_FRAGMENT, enum); - // read 10th - 13th frag in IPv6 packet 2 PTF_PRINT_VERBOSE("read 10th - 12th frag in IPv6 packet 2"); for (int i = 9; i < 12; i++) { - PTF_PRINT_VERBOSE("Frag#" << i+1); + PTF_PRINT_VERBOSE("Frag#" << i + 1); ip6Packet2 = ipReassembly.processPacket(ip6Packet2Frags.at(i), status); PTF_ASSERT_EQUAL(status, pcpp::IPReassembly::FRAGMENT, enum); PTF_ASSERT_NULL(ip6Packet2); @@ -808,7 +783,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_EQUAL(ipReassembly.getCurrentCapacity(), 2); - int buffer1Length = 0; uint8_t* buffer1 = readFileIntoBuffer("PcapExamples/ip4_fragments_packet1.txt", buffer1Length); PTF_ASSERT_EQUAL(ip4Packet1->getRawPacket()->getRawDataLen(), buffer1Length); @@ -838,7 +812,6 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) PTF_ASSERT_EQUAL(ip6Packet2->getRawPacket()->getRawDataLen(), buffer62Length); PTF_ASSERT_BUF_COMPARE(ip6Packet2->getRawPacket()->getRawData(), buffer62, buffer62Length); - delete ip4Packet1; delete ip4Packet2; delete ip4Packet3; @@ -853,13 +826,12 @@ PTF_TEST_CASE(TestIPFragMultipleFrags) delete ip6Packet3; delete ip6Packet4; - delete [] buffer1; - delete [] buffer4; - delete [] buffer6; - delete [] buffer61; - delete [] buffer62; -} // TestIPFragMultipleFrags - + delete[] buffer1; + delete[] buffer4; + delete[] buffer6; + delete[] buffer61; + delete[] buffer62; +} // TestIPFragMultipleFrags PTF_TEST_CASE(TestIPFragMapOverflow) { @@ -901,7 +873,6 @@ PTF_TEST_CASE(TestIPFragMapOverflow) PTF_ASSERT_EQUAL(reader2.getNextPackets(ip6Packet3Frags, 9), 9); PTF_ASSERT_EQUAL(reader2.getNextPackets(ip6Packet4Frags, 7), 7); - pcpp::PointerVector packetsRemovedFromIPReassemblyEngine; pcpp::IPReassembly ipReassembly(ipReassemblyOnFragmentsClean, &packetsRemovedFromIPReassemblyEngine, 3); @@ -909,7 +880,6 @@ PTF_TEST_CASE(TestIPFragMapOverflow) PTF_ASSERT_EQUAL(ipReassembly.getMaxCapacity(), 3); PTF_ASSERT_EQUAL(ipReassembly.getCurrentCapacity(), 0); - pcpp::IPReassembly::ReassemblyStatus status; ipReassembly.processPacket(ip6Packet1Frags.at(0), status); @@ -967,8 +937,7 @@ PTF_TEST_CASE(TestIPFragMapOverflow) PTF_ASSERT_EQUAL(ip4Key->getIpID(), 0x1ea3); PTF_ASSERT_EQUAL(ip4Key->getSrcIP(), pcpp::IPv4Address(std::string("10.118.213.212"))); PTF_ASSERT_EQUAL(ip4Key->getDstIP(), pcpp::IPv4Address(std::string("10.118.213.211"))); -} // TestIPFragMapOverflow - +} // TestIPFragMapOverflow PTF_TEST_CASE(TestIPFragRemove) { @@ -1071,8 +1040,7 @@ PTF_TEST_CASE(TestIPFragRemove) ipReassembly.processPacket(ip4Packet8Frags.at(0), status); PTF_ASSERT_EQUAL(ipReassembly.getCurrentCapacity(), 6); -} // TestIPFragRemove - +} // TestIPFragRemove PTF_TEST_CASE(TestIPFragWithPadding) { @@ -1103,5 +1071,5 @@ PTF_TEST_CASE(TestIPFragWithPadding) PTF_ASSERT_BUF_COMPARE(result->getRawPacket()->getRawData(), buffer, bufferLength); delete result; - delete [] buffer; -} // TestIPFragWithPadding + delete[] buffer; +} // TestIPFragWithPadding diff --git a/Tests/Pcap++Test/Tests/IpMacTests.cpp b/Tests/Pcap++Test/Tests/IpMacTests.cpp index 88a09a4760..4d9c2eee37 100644 --- a/Tests/Pcap++Test/Tests/IpMacTests.cpp +++ b/Tests/Pcap++Test/Tests/IpMacTests.cpp @@ -17,7 +17,6 @@ #include "PcapLiveDeviceList.h" #include "SystemUtils.h" - extern PcapTestArgs PcapTestGlobalArgs; PTF_TEST_CASE(TestIPAddress) @@ -64,7 +63,7 @@ PTF_TEST_CASE(TestIPAddress) PTF_ASSERT_TRUE(ip4AddrFromIpAddr != inAddr_v4); PTF_ASSERT_TRUE(inAddr_v4 != ip4AddrFromIpAddr); - // Equality between different in_addr and IPAddress. + // Equality between different in_addr and IPAddress. PTF_ASSERT_FALSE(ip4Addr == inAddr_v4); PTF_ASSERT_FALSE(inAddr_v4 == ip4Addr); PTF_ASSERT_TRUE(ip4Addr != inAddr_v4); @@ -74,8 +73,8 @@ PTF_TEST_CASE(TestIPAddress) // networks pcpp::IPv4Address ipv4Addr("10.0.0.4"); auto networks = std::vector>{ - std::tuple{"10.8.0.0", "8", "255.0.0.0"}, - std::tuple{"10.0.0.0", "24", "255.255.255.0"} + std::tuple{ "10.8.0.0", "8", "255.0.0.0" }, + std::tuple{ "10.0.0.0", "24", "255.255.255.0" } }; for (const auto& network : networks) { @@ -87,7 +86,8 @@ PTF_TEST_CASE(TestIPAddress) } pcpp::Logger::getInstance().suppressLogs(); - auto invalidMasks = std::vector{"aaaa", "10.0.0.0", "10.0.0.0/aa", "10.0.0.0/33", "999.999.1.1/24", "10.10.10.10/99.99.99"}; + auto invalidMasks = std::vector{ "aaaa", "10.0.0.0", "10.0.0.0/aa", + "10.0.0.0/33", "999.999.1.1/24", "10.10.10.10/99.99.99" }; for (const auto& invalidMask : invalidMasks) { PTF_ASSERT_FALSE(ipv4Addr.matchNetwork(invalidMask)); @@ -95,7 +95,8 @@ PTF_TEST_CASE(TestIPAddress) pcpp::Logger::getInstance().enableLogs(); PTF_ASSERT_RAISES(pcpp::IPv4Address("invalid"), std::invalid_argument, "Not a valid IPv4 address: invalid"); - PTF_ASSERT_RAISES(pcpp::IPv4Address("321.123.1000.1"), std::invalid_argument, "Not a valid IPv4 address: 321.123.1000.1"); + PTF_ASSERT_RAISES(pcpp::IPv4Address("321.123.1000.1"), std::invalid_argument, + "Not a valid IPv4 address: 321.123.1000.1"); std::string ip6AddrString("2607:f0d0:1002:51::4"); pcpp::IPAddress ip6Addr = pcpp::IPAddress(ip6AddrString); @@ -114,7 +115,8 @@ PTF_TEST_CASE(TestIPAddress) } uint8_t addrAsByteArray[16]; ip6AddrFromIpAddr.copyTo(addrAsByteArray); - uint8_t expectedByteArray[16] = { 0x26, 0x07, 0xF0, 0xD0, 0x10, 0x02, 0x00, 0x51, 0x00, 0x00 , 0x00, 0x00, 0x00, 0x00, 0x00, 0x04 }; + uint8_t expectedByteArray[16] = { 0x26, 0x07, 0xF0, 0xD0, 0x10, 0x02, 0x00, 0x51, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04 }; for (int i = 0; i < 16; i++) { PTF_ASSERT_EQUAL(addrAsByteArray[i], expectedByteArray[i]); @@ -158,16 +160,17 @@ PTF_TEST_CASE(TestIPAddress) PTF_ASSERT_EQUAL(ip6AddrFromIpAddr, secondIPv6Address); PTF_ASSERT_RAISES(pcpp::IPv6Address("invalid"), std::invalid_argument, "Not a valid IPv6 address: invalid"); - PTF_ASSERT_RAISES(pcpp::IPv6Address("zzzz:2222:1002:0051:0000:0000:0000:0004"), std::invalid_argument, "Not a valid IPv6 address: zzzz:2222:1002:0051:0000:0000:0000:0004"); + PTF_ASSERT_RAISES(pcpp::IPv6Address("zzzz:2222:1002:0051:0000:0000:0000:0004"), std::invalid_argument, + "Not a valid IPv6 address: zzzz:2222:1002:0051:0000:0000:0000:0004"); // networks pcpp::IPv6Address ip6Addr2("2607:f0d0:1002:0051:ffff::0004"); pcpp::IPv6Address ipv6NetworkPrefix("2607:f0d0:1002:0051:fffe::"); auto ipv6Networks = std::vector>{ - std::tuple{64, "64", "ffff:ffff:ffff:ffff::"}, - std::tuple{32, "32", "ffff:ffff::"}, - std::tuple{79, "79", "ffff:ffff:ffff:ffff:fffe::"}, - std::tuple{0, "0", "::"} + std::tuple{ 64, "64", "ffff:ffff:ffff:ffff::" }, + std::tuple{ 32, "32", "ffff:ffff::" }, + std::tuple{ 79, "79", "ffff:ffff:ffff:ffff:fffe::" }, + std::tuple{ 0, "0", "::" } }; for (const auto& ipv6Network : ipv6Networks) @@ -181,8 +184,8 @@ PTF_TEST_CASE(TestIPAddress) } auto ipv6NetworksNotMatch = std::vector>{ - std::tuple{80, "80", "ffff:ffff:ffff:ffff:ffff::"}, - std::tuple{128, "128", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"} + std::tuple{ 80, "80", "ffff:ffff:ffff:ffff:ffff::" }, + std::tuple{ 128, "128", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" } }; for (const auto& ipv6Network : ipv6NetworksNotMatch) @@ -242,13 +245,12 @@ PTF_TEST_CASE(TestIPAddress) PTF_ASSERT_FALSE(baseIPv6_2 < baseIpv4_1); PTF_ASSERT_FALSE(baseIPv6_1 < baseIpv4_2); PTF_ASSERT_FALSE(baseIPv6_2 < baseIpv4_2); -} // TestIPAddress - +} // TestIPAddress PTF_TEST_CASE(TestMacAddress) { - pcpp::MacAddress macAddr1(0x11,0x2,0x33,0x4,0x55,0x6); - pcpp::MacAddress macAddr2(0x11,0x2,0x33,0x4,0x55,0x6); + pcpp::MacAddress macAddr1(0x11, 0x2, 0x33, 0x4, 0x55, 0x6); + pcpp::MacAddress macAddr2(0x11, 0x2, 0x33, 0x4, 0x55, 0x6); PTF_ASSERT_EQUAL(macAddr1, macAddr2); pcpp::MacAddress macAddr3(std::string("11:02:33:04:55:06")); @@ -260,7 +262,8 @@ PTF_TEST_CASE(TestMacAddress) // verify if some one try to use char[6] or char* to express MAC address in bytes char invalidCharArrayAddress[6] = { 0x11, 0x2, 0x33, 0x4, 0x55, 0x6 }; - PTF_ASSERT_RAISES(pcpp::MacAddress{invalidCharArrayAddress}, std::invalid_argument, "Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); + PTF_ASSERT_RAISES(pcpp::MacAddress{ invalidCharArrayAddress }, std::invalid_argument, + "Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); PTF_ASSERT_EQUAL(macAddr1.toString(), "11:02:33:04:55:06"); std::ostringstream oss; @@ -275,29 +278,33 @@ PTF_TEST_CASE(TestMacAddress) PTF_ASSERT_EQUAL(arrToCopyTo[3], 0x04, hex); PTF_ASSERT_EQUAL(arrToCopyTo[4], 0x55, hex); PTF_ASSERT_EQUAL(arrToCopyTo[5], 0x06, hex); - delete [] arrToCopyTo; + delete[] arrToCopyTo; uint8_t macBytes[6]; macAddr3.copyTo(macBytes); PTF_ASSERT_BUF_COMPARE(macBytes, addrAsArr, 6); - #if __cplusplus > 199711L || _MSC_VER >= 1800 - pcpp::MacAddress macCpp11Valid { 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB }; - PTF_ASSERT_RAISES(pcpp::MacAddress({ 0xBB, 0xBB, 0xBB, 0xBB, 0xBB }), std::invalid_argument, "Invalid initializer list size, should be 6"); - #endif +#if __cplusplus > 199711L || _MSC_VER >= 1800 + pcpp::MacAddress macCpp11Valid{ 0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB }; + PTF_ASSERT_RAISES(pcpp::MacAddress({ 0xBB, 0xBB, 0xBB, 0xBB, 0xBB }), std::invalid_argument, + "Invalid initializer list size, should be 6"); +#endif pcpp::MacAddress mac6(macAddr1); PTF_ASSERT_EQUAL(mac6, macAddr1); mac6 = macAddr2; PTF_ASSERT_EQUAL(mac6, macAddr2); - pcpp::MacAddress macWithZero("aa:aa:00:aa:00:aa"); // valid - PTF_ASSERT_RAISES(pcpp::MacAddress("aa:aa:aa:aa:aa:aa:bb:bb:bb:bb"), std::invalid_argument, "Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); - PTF_ASSERT_RAISES(pcpp::MacAddress("aa:aa:aa"), std::invalid_argument, "Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); - PTF_ASSERT_RAISES(pcpp::MacAddress("aa:aa:aa:ZZ:aa:aa"), std::invalid_argument, "Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); - PTF_ASSERT_RAISES(pcpp::MacAddress("aa:aa:aa:aa:aa:aa:"), std::invalid_argument, "Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); -} // TestMacAddress - + pcpp::MacAddress macWithZero("aa:aa:00:aa:00:aa"); // valid + PTF_ASSERT_RAISES(pcpp::MacAddress("aa:aa:aa:aa:aa:aa:bb:bb:bb:bb"), std::invalid_argument, + "Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); + PTF_ASSERT_RAISES(pcpp::MacAddress("aa:aa:aa"), std::invalid_argument, + "Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); + PTF_ASSERT_RAISES(pcpp::MacAddress("aa:aa:aa:ZZ:aa:aa"), std::invalid_argument, + "Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); + PTF_ASSERT_RAISES(pcpp::MacAddress("aa:aa:aa:aa:aa:aa:"), std::invalid_argument, + "Invalid MAC address format, should be xx:xx:xx:xx:xx:xx"); +} // TestMacAddress PTF_TEST_CASE(TestLRUList) { @@ -316,8 +323,7 @@ PTF_TEST_CASE(TestLRUList) lruList.eraseElement(2); lruList.eraseElement(3); PTF_ASSERT_EQUAL(lruList.getSize(), 0); -} // TestLRUList - +} // TestLRUList PTF_TEST_CASE(TestGeneralUtils) { @@ -343,8 +349,7 @@ PTF_TEST_CASE(TestGeneralUtils) result = pcpp::hexStringToByteArray("0102030405", resultArr, sizeof(resultArr)); PTF_ASSERT_EQUAL(result, 4); PTF_ASSERT_BUF_COMPARE(resultArr, expectedBytes2, result); -} // TestGeneralUtils - +} // TestGeneralUtils PTF_TEST_CASE(TestGetMacAddress) { @@ -355,11 +360,13 @@ PTF_TEST_CASE(TestGetMacAddress) PTF_ASSERT_TRUE(liveDev->open()); DeviceTeardown devTeardown(liveDev); - //fetch all IP addresses from arp table + // fetch all IP addresses from arp table std::string ipsInArpTableAsString; #ifdef _WIN32 - ipsInArpTableAsString = pcpp::executeShellCommand("arp -a | for /f \"tokens=1\" \%i in ('findstr dynamic') do @echo \%i"); - ipsInArpTableAsString.erase(std::remove(ipsInArpTableAsString.begin(), ipsInArpTableAsString.end(), ' '), ipsInArpTableAsString.end() ) ; + ipsInArpTableAsString = + pcpp::executeShellCommand("arp -a | for /f \"tokens=1\" \%i in ('findstr dynamic') do @echo \%i"); + ipsInArpTableAsString.erase(std::remove(ipsInArpTableAsString.begin(), ipsInArpTableAsString.end(), ' '), + ipsInArpTableAsString.end()); #else ipsInArpTableAsString = pcpp::executeShellCommand("arp -a | awk '{print $2}' | sed 's/.$//; s/^.//'"); #endif @@ -406,48 +413,73 @@ PTF_TEST_CASE(TestGetMacAddress) { PTF_ASSERT_NOT_EQUAL(result, pcpp::MacAddress::Zero); } -} // TestGetMacAddress - +} // TestGetMacAddress PTF_TEST_CASE(TestIPv4Network) { // Invalid c'tor: IPv4 address + prefix len - PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), -1), std::invalid_argument, "prefixLen must be an integer between 0 and 32"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), 33), std::invalid_argument, "prefixLen must be an integer between 0 and 32"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), -1), std::invalid_argument, + "prefixLen must be an integer between 0 and 32"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), 33), std::invalid_argument, + "prefixLen must be an integer between 0 and 32"); // Invalid c'tor: IPv4 address + netmask - PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "invalid"), std::invalid_argument, "Netmask is not valid IPv4 format: invalid"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "999.999.999.999"), std::invalid_argument, "Netmask is not valid IPv4 format: 999.999.999.999"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "255.255.0.255"), std::invalid_argument, "Netmask is not valid IPv4 format: 255.255.0.255"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "10.10.10.10"), std::invalid_argument, "Netmask is not valid IPv4 format: 10.10.10.10"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "0.255.255.255"), std::invalid_argument, "Netmask is not valid IPv4 format: 0.255.255.255"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "127.255.255.255"), std::invalid_argument, "Netmask is not valid IPv4 format: 127.255.255.255"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "invalid"), std::invalid_argument, + "Netmask is not valid IPv4 format: invalid"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "999.999.999.999"), std::invalid_argument, + "Netmask is not valid IPv4 format: 999.999.999.999"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "255.255.0.255"), std::invalid_argument, + "Netmask is not valid IPv4 format: 255.255.0.255"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "10.10.10.10"), std::invalid_argument, + "Netmask is not valid IPv4 format: 10.10.10.10"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "0.255.255.255"), std::invalid_argument, + "Netmask is not valid IPv4 format: 0.255.255.255"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(pcpp::IPv4Address("1.1.1.1"), "127.255.255.255"), std::invalid_argument, + "Netmask is not valid IPv4 format: 127.255.255.255"); // Invalid c'tor: address + netmask in one string - PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("invalid")), std::invalid_argument, "The input should be in the format of
/ or
/"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("invalid/255.255.255.0")), std::invalid_argument, "The input doesn't contain a valid IPv4 network prefix: invalid"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/255.255.255.0/24")), std::invalid_argument, "Netmask is not valid IPv4 format: 255.255.255.0/24"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/33")), std::invalid_argument, "Prefix length must be an integer between 0 and 32"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/-1")), std::invalid_argument, "Netmask is not valid IPv4 format: -1"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/invalid")), std::invalid_argument, "Netmask is not valid IPv4 format: invalid"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/999.999.999.999")), std::invalid_argument, "Netmask is not valid IPv4 format: 999.999.999.999"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/255.255.0.1")), std::invalid_argument, "Netmask is not valid IPv4 format: 255.255.0.1"); - PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/0.0.255.255")), std::invalid_argument, "Netmask is not valid IPv4 format: 0.0.255.255"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("invalid")), std::invalid_argument, + "The input should be in the format of
/ or
/"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("invalid/255.255.255.0")), std::invalid_argument, + "The input doesn't contain a valid IPv4 network prefix: invalid"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/255.255.255.0/24")), std::invalid_argument, + "Netmask is not valid IPv4 format: 255.255.255.0/24"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/33")), std::invalid_argument, + "Prefix length must be an integer between 0 and 32"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/-1")), std::invalid_argument, + "Netmask is not valid IPv4 format: -1"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/invalid")), std::invalid_argument, + "Netmask is not valid IPv4 format: invalid"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/999.999.999.999")), std::invalid_argument, + "Netmask is not valid IPv4 format: 999.999.999.999"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/255.255.0.1")), std::invalid_argument, + "Netmask is not valid IPv4 format: 255.255.0.1"); + PTF_ASSERT_RAISES(pcpp::IPv4Network(std::string("1.1.1.1/0.0.255.255")), std::invalid_argument, + "Netmask is not valid IPv4 format: 0.0.255.255"); // Valid c'tor auto addressAsStr = std::string("192.168.10.100"); auto address = pcpp::IPv4Address(addressAsStr); - auto networksPrefixLensAndNetPrefix = std::vector> { - std::tuple{"255.255.255.255", 32, "192.168.10.100", "192.168.10.100", "192.168.10.100", 1}, - std::tuple{"255.255.255.0", 24, "192.168.10.0", "192.168.10.1", "192.168.10.254", 256}, - std::tuple{"255.255.0.0", 16, "192.168.0.0", "192.168.0.1", "192.168.255.254", 65536}, - std::tuple{"255.240.0.0", 12, "192.160.0.0", "192.160.0.1", "192.175.255.254", 1048576}, - std::tuple{"255.0.0.0", 8, "192.0.0.0", "192.0.0.1", "192.255.255.254", 16777216}, - std::tuple{"192.0.0.0", 2, "192.0.0.0", "192.0.0.1", "255.255.255.254", 1073741824}, - std::tuple{"128.0.0.0", 1, "128.0.0.0", "128.0.0.1", "255.255.255.254", 2147483648}, - std::tuple{"0.0.0.0", 0, "0.0.0.0", "0.0.0.1", "255.255.255.254", 4294967296} - }; + auto networksPrefixLensAndNetPrefix = + std::vector>{ + std::tuple{ + "255.255.255.255", 32, "192.168.10.100", "192.168.10.100", "192.168.10.100", 1 }, + std::tuple{ + "255.255.255.0", 24, "192.168.10.0", "192.168.10.1", "192.168.10.254", 256 }, + std::tuple{ + "255.255.0.0", 16, "192.168.0.0", "192.168.0.1", "192.168.255.254", 65536 }, + std::tuple{ + "255.240.0.0", 12, "192.160.0.0", "192.160.0.1", "192.175.255.254", 1048576 }, + std::tuple{ + "255.0.0.0", 8, "192.0.0.0", "192.0.0.1", "192.255.255.254", 16777216 }, + std::tuple{ + "192.0.0.0", 2, "192.0.0.0", "192.0.0.1", "255.255.255.254", 1073741824 }, + std::tuple{ + "128.0.0.0", 1, "128.0.0.0", "128.0.0.1", "255.255.255.254", 2147483648 }, + std::tuple{ + "0.0.0.0", 0, "0.0.0.0", "0.0.0.1", "255.255.255.254", 4294967296 } + }; for (auto networkPrefixLenAndNetPrefix : networksPrefixLensAndNetPrefix) { @@ -468,13 +500,15 @@ PTF_TEST_CASE(TestIPv4Network) PTF_ASSERT_EQUAL(iPv4NetworkA.getNetworkPrefix(), std::get<2>(networkPrefixLenAndNetPrefix)); // Valid c'tor: address + prefix len in one string - std::string addressAndPrefixLen = addressAsStr + "/" + std::to_string(std::get<1>(networkPrefixLenAndNetPrefix)); + std::string addressAndPrefixLen = + addressAsStr + "/" + std::to_string(std::get<1>(networkPrefixLenAndNetPrefix)); pcpp::IPv4Network iPv4NetworkD(addressAndPrefixLen); PTF_ASSERT_EQUAL(iPv4NetworkA.getNetmask(), std::get<0>(networkPrefixLenAndNetPrefix)); PTF_ASSERT_EQUAL(iPv4NetworkA.getNetworkPrefix(), std::get<2>(networkPrefixLenAndNetPrefix)); PTF_ASSERT_EQUAL(iPv4NetworkD.getLowestAddress(), pcpp::IPv4Address(std::get<3>(networkPrefixLenAndNetPrefix))); - PTF_ASSERT_EQUAL(iPv4NetworkD.getHighestAddress(), pcpp::IPv4Address(std::get<4>(networkPrefixLenAndNetPrefix))); + PTF_ASSERT_EQUAL(iPv4NetworkD.getHighestAddress(), + pcpp::IPv4Address(std::get<4>(networkPrefixLenAndNetPrefix))); PTF_ASSERT_EQUAL(iPv4NetworkD.getTotalAddressCount(), std::get<5>(networkPrefixLenAndNetPrefix)); } @@ -503,53 +537,87 @@ PTF_TEST_CASE(TestIPv4Network) std::stringstream stream; stream << ipv4Network; PTF_ASSERT_EQUAL(stream.str(), "172.16.0.0/16"); -} // TestIPv4Network - +} // TestIPv4Network PTF_TEST_CASE(TestIPv6Network) { // Invalid c'tor: IPv6 address + prefix len - PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), 129), std::invalid_argument, "prefixLen must be an integer between 0 and 128"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), 129), std::invalid_argument, + "prefixLen must be an integer between 0 and 128"); // Invalid c'tor: IPv6 address + netmask - PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "invalid"), std::invalid_argument, "Netmask is not valid IPv6 format: invalid"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "ffff:ff10::"), std::invalid_argument, "Netmask is not valid IPv6 format: ffff:ff10::"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "ffff:ee00::"), std::invalid_argument, "Netmask is not valid IPv6 format: ffff:ee00::"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "7f00::"), std::invalid_argument, "Netmask is not valid IPv6 format: 7f00::"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "ffff::ffff"), std::invalid_argument, "Netmask is not valid IPv6 format: ffff::ffff"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "f000::0001"), std::invalid_argument, "Netmask is not valid IPv6 format: f000::0001"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "invalid"), std::invalid_argument, + "Netmask is not valid IPv6 format: invalid"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "ffff:ff10::"), std::invalid_argument, + "Netmask is not valid IPv6 format: ffff:ff10::"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "ffff:ee00::"), std::invalid_argument, + "Netmask is not valid IPv6 format: ffff:ee00::"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "7f00::"), std::invalid_argument, + "Netmask is not valid IPv6 format: 7f00::"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "ffff::ffff"), std::invalid_argument, + "Netmask is not valid IPv6 format: ffff::ffff"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(pcpp::IPv6Address("2001:db8::"), "f000::0001"), std::invalid_argument, + "Netmask is not valid IPv6 format: f000::0001"); // Invalid c'tor: address + netmask in one string - PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("invalid")), std::invalid_argument, "The input should be in the format of
/ or
/"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("invalid/32")), std::invalid_argument, "The input doesn't contain a valid IPv6 network prefix: invalid"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/32/24")), std::invalid_argument, "Netmask is not valid IPv6 format: 32/24"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/255.255.0.0")), std::invalid_argument, "Netmask is not valid IPv6 format: 255.255.0.0"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/130")), std::invalid_argument, "Prefix length must be an integer between 0 and 128"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/-1")), std::invalid_argument, "Netmask is not valid IPv6 format: -1"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/invalid")), std::invalid_argument, "Netmask is not valid IPv6 format: invalid"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/a2cb:d625::")), std::invalid_argument, "Netmask is not valid IPv6 format: a2cb:d625::"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/ffff::0001")), std::invalid_argument, "Netmask is not valid IPv6 format: ffff::0001"); - PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/0fff::")), std::invalid_argument, "Netmask is not valid IPv6 format: 0fff::"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("invalid")), std::invalid_argument, + "The input should be in the format of
/ or
/"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("invalid/32")), std::invalid_argument, + "The input doesn't contain a valid IPv6 network prefix: invalid"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/32/24")), std::invalid_argument, + "Netmask is not valid IPv6 format: 32/24"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/255.255.0.0")), std::invalid_argument, + "Netmask is not valid IPv6 format: 255.255.0.0"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/130")), std::invalid_argument, + "Prefix length must be an integer between 0 and 128"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/-1")), std::invalid_argument, + "Netmask is not valid IPv6 format: -1"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/invalid")), std::invalid_argument, + "Netmask is not valid IPv6 format: invalid"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/a2cb:d625::")), std::invalid_argument, + "Netmask is not valid IPv6 format: a2cb:d625::"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/ffff::0001")), std::invalid_argument, + "Netmask is not valid IPv6 format: ffff::0001"); + PTF_ASSERT_RAISES(pcpp::IPv6Network(std::string("ef3c:7157:a084:23c0::/0fff::")), std::invalid_argument, + "Netmask is not valid IPv6 format: 0fff::"); // Valid c'tor auto addressAsStr = std::string("39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5746"); auto address = pcpp::IPv6Address(addressAsStr); - auto netmasksPrefixLensAndNetPrefix = std::vector> { - std::tuple{"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 128, "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5746", "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5746", "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5746", 1}, - std::tuple{"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8", 125, "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5740", "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5741", "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5747", 8}, - std::tuple{"ffff:ffff:ffff:ffff:8000::", 65, "39e1:f90e:14dd:f9a1::", "39e1:f90e:14dd:f9a1::1", "39e1:f90e:14dd:f9a1:7fff:ffff:ffff:ffff", 9223372036854775808ULL}, - std::tuple{"ffff:ffff:ffff:ffff::", 64, "39e1:f90e:14dd:f9a1::", "39e1:f90e:14dd:f9a1::1", "39e1:f90e:14dd:f9a1:ffff:ffff:ffff:ffff", 0}, - std::tuple{"ffff:ffff::", 32, "39e1:f90e::", "39e1:f90e::1", "39e1:f90e:ffff:ffff:ffff:ffff:ffff:ffff", 0}, - std::tuple{"ffff:e000::", 19, "39e1:e000::", "39e1:e000::1", "39e1:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0}, - std::tuple{"ffff:8000::", 17, "39e1:8000::", "39e1:8000::1", "39e1:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0}, - std::tuple{"ffff::", 16, "39e1::", "39e1::1", "39e1:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0}, - std::tuple{"ff80::", 9, "3980::", "3980::1", "39ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0}, - std::tuple{"ff00::", 8, "3900::", "3900::1", "39ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0}, - std::tuple{"fc00::", 6, "3800::", "3800::1", "3bff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0}, - std::tuple{"c000::", 2, "00::", "00::1", "3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0}, - std::tuple{"::", 0, "::", "::1", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0} - }; + auto netmasksPrefixLensAndNetPrefix = + std::vector>{ + std::tuple{ + "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 128, "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5746", + "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5746", "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5746", 1 }, + std::tuple{ + "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff8", 125, "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5740", + "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5741", "39e1:f90e:14dd:f9a1:4d0a:7f9f:da18:5747", 8 }, + std::tuple{ + "ffff:ffff:ffff:ffff:8000::", 65, "39e1:f90e:14dd:f9a1::", "39e1:f90e:14dd:f9a1::1", + "39e1:f90e:14dd:f9a1:7fff:ffff:ffff:ffff", 9223372036854775808ULL }, + std::tuple{ + "ffff:ffff:ffff:ffff::", 64, "39e1:f90e:14dd:f9a1::", "39e1:f90e:14dd:f9a1::1", + "39e1:f90e:14dd:f9a1:ffff:ffff:ffff:ffff", 0 }, + std::tuple{ + "ffff:ffff::", 32, "39e1:f90e::", "39e1:f90e::1", "39e1:f90e:ffff:ffff:ffff:ffff:ffff:ffff", 0 }, + std::tuple{ + "ffff:e000::", 19, "39e1:e000::", "39e1:e000::1", "39e1:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0 }, + std::tuple{ + "ffff:8000::", 17, "39e1:8000::", "39e1:8000::1", "39e1:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0 }, + std::tuple{ + "ffff::", 16, "39e1::", "39e1::1", "39e1:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0 }, + std::tuple{ + "ff80::", 9, "3980::", "3980::1", "39ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0 }, + std::tuple{ + "ff00::", 8, "3900::", "3900::1", "39ff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0 }, + std::tuple{ + "fc00::", 6, "3800::", "3800::1", "3bff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0 }, + std::tuple{ + "c000::", 2, "00::", "00::1", "3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0 }, + std::tuple{ + "::", 0, "::", "::1", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", 0 } + }; for (auto netmaskPrefixLenAndNetPrefix : netmasksPrefixLensAndNetPrefix) { @@ -570,13 +638,15 @@ PTF_TEST_CASE(TestIPv6Network) PTF_ASSERT_EQUAL(iPv6NetworkC.getNetworkPrefix(), std::get<2>(netmaskPrefixLenAndNetPrefix)); // Valid c'tor: address + prefix len in one string - std::string addressAndPrefixLen = addressAsStr + "/" + std::to_string(std::get<1>(netmaskPrefixLenAndNetPrefix)); + std::string addressAndPrefixLen = + addressAsStr + "/" + std::to_string(std::get<1>(netmaskPrefixLenAndNetPrefix)); pcpp::IPv6Network iPv6NetworkD(addressAndPrefixLen); PTF_ASSERT_EQUAL(iPv6NetworkD.getNetmask(), std::get<0>(netmaskPrefixLenAndNetPrefix)); PTF_ASSERT_EQUAL(iPv6NetworkD.getNetworkPrefix(), std::get<2>(netmaskPrefixLenAndNetPrefix)); PTF_ASSERT_EQUAL(iPv6NetworkD.getLowestAddress(), pcpp::IPv6Address(std::get<3>(netmaskPrefixLenAndNetPrefix))); - PTF_ASSERT_EQUAL(iPv6NetworkD.getHighestAddress(), pcpp::IPv6Address(std::get<4>(netmaskPrefixLenAndNetPrefix))); + PTF_ASSERT_EQUAL(iPv6NetworkD.getHighestAddress(), + pcpp::IPv6Address(std::get<4>(netmaskPrefixLenAndNetPrefix))); auto expectedNumOfAddresses = std::get<5>(netmaskPrefixLenAndNetPrefix); if (expectedNumOfAddresses != 0) { @@ -584,7 +654,8 @@ PTF_TEST_CASE(TestIPv6Network) } else { - PTF_ASSERT_RAISES(iPv6NetworkD.getTotalAddressCount(), std::out_of_range, "Number of addresses exceeds uint64_t"); + PTF_ASSERT_RAISES(iPv6NetworkD.getTotalAddressCount(), std::out_of_range, + "Number of addresses exceeds uint64_t"); } } @@ -599,29 +670,40 @@ PTF_TEST_CASE(TestIPv6Network) for (auto prefixLen = 0; prefixLen < 64; prefixLen++) { - PTF_ASSERT_FALSE(ipv6Network.includes(pcpp::IPv6Network(pcpp::IPv6Address("a88e:2765:5349:01f9:9a9a:a444:2739:2f4a"), prefixLen))); + PTF_ASSERT_FALSE(ipv6Network.includes( + pcpp::IPv6Network(pcpp::IPv6Address("a88e:2765:5349:01f9:9a9a:a444:2739:2f4a"), prefixLen))); } for (auto prefixLen = 64; prefixLen <= 128; prefixLen++) { - PTF_ASSERT_TRUE(ipv6Network.includes(pcpp::IPv6Network(pcpp::IPv6Address("a88e:2765:5349:01f9:9a9a:a444:2739:2f4a"), prefixLen))); + PTF_ASSERT_TRUE(ipv6Network.includes( + pcpp::IPv6Network(pcpp::IPv6Address("a88e:2765:5349:01f9:9a9a:a444:2739:2f4a"), prefixLen))); } - PTF_ASSERT_FALSE(ipv6Network.includes(pcpp::IPv6Network(pcpp::IPv6Address("4447:3c98:ee01:fd0a:bf73:ad00:89ac:1a89"), 64))); + PTF_ASSERT_FALSE( + ipv6Network.includes(pcpp::IPv6Network(pcpp::IPv6Address("4447:3c98:ee01:fd0a:bf73:ad00:89ac:1a89"), 64))); // to string PTF_ASSERT_EQUAL(ipv6Network.toString(), "a88e:2765:5349:1f9::/64"); std::stringstream stream; stream << ipv6Network; PTF_ASSERT_EQUAL(stream.str(), "a88e:2765:5349:1f9::/64"); -} // TestIPv6Network - +} // TestIPv6Network PTF_TEST_CASE(TestIPNetwork) { - auto networkInfos = std::vector> { - std::tuple{"192.168.1.1", pcpp::IPv4Address("192.168.1.1"), 16, "255.255.0.0", pcpp::IPv4Address("192.168.0.0"), 4, pcpp::IPv4Address("192.168.0.1"), pcpp::IPv4Address("192.168.255.254"), 65536}, - std::tuple{"fe26:d0a1:beb6:5957:e77a:9983:ec84:b23e", pcpp::IPv6Address("fe26:d0a1:beb6:5957:e77a:9983:ec84:b23e"), 64, "ffff:ffff:ffff:ffff::", pcpp::IPv6Address("fe26:d0a1:beb6:5957::"), 6, pcpp::IPv6Address("fe26:d0a1:beb6:5957::1"), pcpp::IPv6Address("fe26:d0a1:beb6:5957:ffff:ffff:ffff:ffff"), 0} + auto networkInfos = std::vector>{ + std::tuple{ "192.168.1.1", pcpp::IPv4Address("192.168.1.1"), 16, "255.255.0.0", + pcpp::IPv4Address("192.168.0.0"), 4, pcpp::IPv4Address("192.168.0.1"), + pcpp::IPv4Address("192.168.255.254"), 65536 }, + std::tuple{ "fe26:d0a1:beb6:5957:e77a:9983:ec84:b23e", + pcpp::IPv6Address("fe26:d0a1:beb6:5957:e77a:9983:ec84:b23e"), 64, + "ffff:ffff:ffff:ffff::", pcpp::IPv6Address("fe26:d0a1:beb6:5957::"), 6, + pcpp::IPv6Address("fe26:d0a1:beb6:5957::1"), + pcpp::IPv6Address("fe26:d0a1:beb6:5957:ffff:ffff:ffff:ffff"), 0 } }; for (auto networkInfo : networkInfos) @@ -666,7 +748,8 @@ PTF_TEST_CASE(TestIPNetwork) } else { - PTF_ASSERT_RAISES(networkD.getTotalAddressCount(), std::out_of_range, "Number of addresses exceeds uint64_t"); + PTF_ASSERT_RAISES(networkD.getTotalAddressCount(), std::out_of_range, + "Number of addresses exceeds uint64_t"); } } @@ -719,4 +802,4 @@ PTF_TEST_CASE(TestIPNetwork) PTF_ASSERT_EQUAL(ipv4Network.toString(), "10.1.2.0/24"); ipv6Network = ipv4NetworkCopy; PTF_ASSERT_EQUAL(ipv6Network.toString(), "4348:58d6::/32"); -} // TestIPNetwork +} // TestIPNetwork diff --git a/Tests/Pcap++Test/Tests/KniTests.cpp b/Tests/Pcap++Test/Tests/KniTests.cpp index 09563619f2..cd92439a10 100644 --- a/Tests/Pcap++Test/Tests/KniTests.cpp +++ b/Tests/Pcap++Test/Tests/KniTests.cpp @@ -3,25 +3,44 @@ #include "../Common/PcapFileNamesDef.h" #ifdef USE_DPDK_KNI -#include "KniDeviceList.h" -#include "PcapFileDevice.h" -#include "RawSocketDevice.h" -#include "SystemUtils.h" +# include "KniDeviceList.h" +# include "PcapFileDevice.h" +# include "RawSocketDevice.h" +# include "SystemUtils.h" extern PcapTestArgs PcapTestGlobalArgs; -#define KNI_TEST_NAME "tkni" +# define KNI_TEST_NAME "tkni" struct KniRequestsCallbacksMock { - static int change_mtu_new(uint16_t, unsigned int) { return 0; } - static int change_mtu_old(uint8_t, unsigned int) { return 0; } - static int config_network_if_new(uint16_t, uint8_t) { return 0; } - static int config_network_if_old(uint8_t, uint8_t) { return 0; } - static int config_mac_address(uint16_t, uint8_t[]) { return 0; } - static int config_promiscusity(uint16_t, uint8_t) { return 0; } - - static bool onPacketsCallbackSingleBurst(pcpp::MBufRawPacket*, uint32_t numOfPackets, pcpp::KniDevice*, void* userCookie) + static int change_mtu_new(uint16_t, unsigned int) + { + return 0; + } + static int change_mtu_old(uint8_t, unsigned int) + { + return 0; + } + static int config_network_if_new(uint16_t, uint8_t) + { + return 0; + } + static int config_network_if_old(uint8_t, uint8_t) + { + return 0; + } + static int config_mac_address(uint16_t, uint8_t[]) + { + return 0; + } + static int config_promiscusity(uint16_t, uint8_t) + { + return 0; + } + + static bool onPacketsCallbackSingleBurst(pcpp::MBufRawPacket*, uint32_t numOfPackets, pcpp::KniDevice*, + void* userCookie) { unsigned int* counter = static_cast(userCookie); *counter = numOfPackets; @@ -77,28 +96,26 @@ static bool setKniDeviceIp(const pcpp::IPAddress& ip, int kniDeviceId) class KniDeviceTeardown { - private: - pcpp::KniDevice* m_KniDevice; - - public: +private: + pcpp::KniDevice* m_KniDevice; - explicit KniDeviceTeardown(pcpp::KniDevice* dev) - { - m_KniDevice = dev; - } +public: + explicit KniDeviceTeardown(pcpp::KniDevice* dev) + { + m_KniDevice = dev; + } - ~KniDeviceTeardown() + ~KniDeviceTeardown() + { + if (m_KniDevice != NULL && m_KniDevice->isInitialized() && m_KniDevice->isOpened()) { - if (m_KniDevice != NULL && m_KniDevice->isInitialized() && m_KniDevice->isOpened()) - { - m_KniDevice->stopRequestHandlerThread(); - m_KniDevice->close(); - } + m_KniDevice->stopRequestHandlerThread(); + m_KniDevice->close(); } + } }; -#endif // USE_DPDK_KNI - +#endif // USE_DPDK_KNI PTF_TEST_CASE(TestKniDevice) { @@ -176,7 +193,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 + pcpp::multiPlatformSleep(2); // Wait for thread to start if (pcpp::KniDeviceList::isCallbackSupported(pcpp::KniDeviceList::CALLBACK_PROMISC)) { bool modeSet = device->setPromiscuous(pcpp::KniDevice::PROMISC_ENABLE); @@ -239,37 +256,40 @@ PTF_TEST_CASE(TestKniDevice) } } { - pcpp::KniDevice::KniLinkState ls = device->updateLinkState(isLinkUp ? pcpp::KniDevice::LINK_DOWN : pcpp::KniDevice::LINK_UP); + pcpp::KniDevice::KniLinkState ls = + device->updateLinkState(isLinkUp ? pcpp::KniDevice::LINK_DOWN : pcpp::KniDevice::LINK_UP); switch (ls) { - case pcpp::KniDevice::LINK_NOT_SUPPORTED: - { - PTF_PRINT_VERBOSE("KNI updateLinkState not supported"); - } break; - case pcpp::KniDevice::LINK_ERROR: - { - PTF_PRINT_VERBOSE("KNI updateLinkState have failed with LINK_ERROR"); - } break; - case pcpp::KniDevice::LINK_DOWN: - { // If previous known state was UP -> yield an error - PTF_ASSERT_FALSE(isLinkUp); - } break; - case pcpp::KniDevice::LINK_UP: - { // If previous known state was DOWN -> yield an error - PTF_ASSERT_TRUE(isLinkUp); - } break; + case pcpp::KniDevice::LINK_NOT_SUPPORTED: + { + PTF_PRINT_VERBOSE("KNI updateLinkState not supported"); + } + break; + case pcpp::KniDevice::LINK_ERROR: + { + PTF_PRINT_VERBOSE("KNI updateLinkState have failed with LINK_ERROR"); + } + break; + case pcpp::KniDevice::LINK_DOWN: + { // If previous known state was UP -> yield an error + PTF_ASSERT_FALSE(isLinkUp); + } + break; + case pcpp::KniDevice::LINK_UP: + { // If previous known state was DOWN -> yield an error + PTF_ASSERT_TRUE(isLinkUp); + } + break; } } device->stopRequestHandlerThread(); device->close(); // Device will be destroyed later - #else PTF_SKIP_TEST("DPDK and DPDK_KNI not configured"); #endif -} // TestKniDevice - +} // TestKniDevice PTF_TEST_CASE(TestKniDeviceSendReceive) { @@ -281,7 +301,11 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) } // Assume that DPDK was initialized correctly in DpdkDevice tests - enum { KNI_MTU = 1500, BLOCK_TIMEOUT = 3 }; + enum + { + KNI_MTU = 1500, + BLOCK_TIMEOUT = 3 + }; pcpp::KniDevice* device = NULL; unsigned int counter = 0; pcpp::KniDevice::KniDeviceConfiguration devConfig; @@ -313,7 +337,7 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) PTF_ASSERT_TRUE(device->startRequestHandlerThread(0, 250000000)); KniDeviceTeardown devTeardown(device); - pcpp::multiPlatformSleep(1); // Wait for thread to start + pcpp::multiPlatformSleep(1); // Wait for thread to start // KNI device management PTF_ASSERT_TRUE(setKniDeviceIp(kniIp, KNI_DEVICE1)); @@ -325,7 +349,7 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) pcpp::PcapFileReaderDevice fileReaderDev(EXAMPLE_PCAP_PATH); PTF_ASSERT_TRUE(rsdevice.open()); - { // Receive test part + { // Receive test part pcpp::RawPacket rawPacket; pcpp::RawPacketVector rawPacketVec; pcpp::MBufRawPacketVector mbufRawPacketVec; @@ -339,7 +363,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 + pcpp::multiPlatformSleep(1); // Give some time to start capture thread for (int i = 0; i < 10; ++i) { fileReaderDev.getNextPacket(rawPacket); @@ -350,12 +374,12 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) rsdevice.sendPackets(rawPacketVec); pcpp::Logger::getInstance().enableLogs(); rawPacketVec.clear(); - pcpp::multiPlatformSleep(1); // Give some time to receive packets + pcpp::multiPlatformSleep(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 + pcpp::multiPlatformSleep(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); @@ -371,7 +395,7 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) rsdevice.sendPackets(rawPacketVec); pcpp::Logger::getInstance().enableLogs(); rawPacketVec.clear(); - pcpp::multiPlatformSleep(1); // Give some time to receive packets + pcpp::multiPlatformSleep(1); // Give some time to receive packets device->stopCapture(); PTF_PRINT_VERBOSE("KNI have captured " << counter << " packets on device " << KNI_DEVICE1); counter = 0; @@ -386,21 +410,25 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) rawPacketVec.clear(); //? Note(echo-Mike): Some amount of packets are always queued inside kernel //? so blocking mode has a slight chance to obtain this packets - int blockResult = device->startCaptureBlockingMode(KniRequestsCallbacksMock::onPacketsCallbackSingleBurst, &counter, BLOCK_TIMEOUT); + int blockResult = device->startCaptureBlockingMode(KniRequestsCallbacksMock::onPacketsCallbackSingleBurst, + &counter, BLOCK_TIMEOUT); switch (blockResult) { - case -1: - { - PTF_PRINT_VERBOSE("KNI startCaptureBlockingMode have exited by timeout"); - } break; - case 0: - { - PTF_PRINT_VERBOSE("KNI startCaptureBlockingMode have exited by an ERROR"); - } break; - case 1: - { - PTF_PRINT_VERBOSE("KNI have captured " << counter << " packets (blocking mode) on device " << KNI_DEVICE1); - } break; + case -1: + { + PTF_PRINT_VERBOSE("KNI startCaptureBlockingMode have exited by timeout"); + } + break; + case 0: + { + PTF_PRINT_VERBOSE("KNI startCaptureBlockingMode have exited by an ERROR"); + } + break; + case 1: + { + PTF_PRINT_VERBOSE("KNI have captured " << counter << " packets (blocking mode) on device " << KNI_DEVICE1); + } + break; } } @@ -409,7 +437,7 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) pcpp::Logger::getInstance().enableLogs(); PTF_ASSERT_TRUE(fileReaderDev.open()); - { // Send test part + { // Send test part pcpp::PointerVector packetVec; pcpp::RawPacketVector sendRawPacketVec; pcpp::RawPacketVector receiveRawPacketVec; @@ -417,7 +445,7 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) uint16_t packetsRead = 0; int packetsReceived = 0; pcpp::RawPacket rawPacket; - while(fileReaderDev.getNextPacket(rawPacket)) + while (fileReaderDev.getNextPacket(rawPacket)) { if (packetsRead == 100) break; @@ -430,7 +458,7 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) packetsRead++; } - //send packets as parsed EthPacekt array + // send packets as parsed EthPacekt array uint16_t packetsSentAsParsed = device->sendPackets(packetArr, packetsRead); PTF_ASSERT_EQUAL(packetsSentAsParsed, packetsRead); @@ -443,7 +471,7 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) PTF_ASSERT_NOT_EQUAL(packetsReceived, 0); packetsReceived = 0; - //send packets are RawPacketVector + // send packets are RawPacketVector uint16_t packetsSentAsRawVector = device->sendPackets(sendRawPacketVec); PTF_ASSERT_EQUAL(packetsSentAsRawVector, packetsRead); @@ -458,8 +486,8 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) //? Note (echo-Mike): this will not be checked by raw socket because there is //? a chance that packets will be thrown away before we can receive them - PTF_ASSERT_TRUE(device->sendPacket(*(sendRawPacketVec.at(packetsRead/3)))); - PTF_ASSERT_TRUE(device->sendPacket(*(packetArr[packetsRead/2]))); + PTF_ASSERT_TRUE(device->sendPacket(*(sendRawPacketVec.at(packetsRead / 3)))); + PTF_ASSERT_TRUE(device->sendPacket(*(packetArr[packetsRead / 2]))); } //! Note(echo-Mike): RawSocket device must be closed before KNI @@ -472,4 +500,4 @@ PTF_TEST_CASE(TestKniDeviceSendReceive) PTF_SKIP_TEST("DPDK and DPDK_KNI not configured"); #endif -} // TestKniDeviceSendReceive +} // TestKniDeviceSendReceive diff --git a/Tests/Pcap++Test/Tests/LiveDeviceTests.cpp b/Tests/Pcap++Test/Tests/LiveDeviceTests.cpp index 9a93989704..052d49b1cb 100644 --- a/Tests/Pcap++Test/Tests/LiveDeviceTests.cpp +++ b/Tests/Pcap++Test/Tests/LiveDeviceTests.cpp @@ -13,10 +13,10 @@ #include #include #if defined(_WIN32) -#include "PcapRemoteDevice.h" -#include "PcapRemoteDeviceList.h" -#include "WinPcapLiveDevice.h" -#include +# include "PcapRemoteDevice.h" +# include "PcapRemoteDeviceList.h" +# include "WinPcapLiveDevice.h" +# include #endif extern PcapTestArgs PcapTestGlobalArgs; @@ -46,7 +46,8 @@ static bool packetArrivesBlockingModeNoTimeout(pcpp::RawPacket* rawPacket, pcpp: return false; } -static bool packetArrivesBlockingModeStartCapture(pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* dev, void* userCookie) +static bool packetArrivesBlockingModeStartCapture(pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* dev, + void* userCookie) { pcpp::Logger::getInstance().suppressLogs(); if (dev->startCaptureBlockingMode(packetArrivesBlockingModeTimeout, nullptr, 5) != 0) @@ -66,7 +67,8 @@ static bool packetArrivesBlockingModeStartCapture(pcpp::RawPacket* rawPacket, pc return false; } -static bool packetArrivesBlockingModeStopCapture(pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* dev, void* userCookie) +static bool packetArrivesBlockingModeStopCapture(pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* dev, + void* userCookie) { // shouldn't do anything dev->stopCapture(); @@ -79,14 +81,16 @@ static bool packetArrivesBlockingModeStopCapture(pcpp::RawPacket* rawPacket, pcp return false; } -static bool packetArrivesBlockingModeNoTimeoutPacketCount(pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* dev, void* userCookie) +static bool packetArrivesBlockingModeNoTimeoutPacketCount(pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* dev, + void* userCookie) { int* packetCount = static_cast(userCookie); (*packetCount)++; return false; } -static bool packetArrivesBlockingModeWithSnaplen(pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* dev, void* userCookie) +static bool packetArrivesBlockingModeWithSnaplen(pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* dev, + void* userCookie) { int snaplen = *static_cast(userCookie); return rawPacket->getRawDataLen() > snaplen; @@ -115,6 +119,7 @@ class RpcapdServerInitializer m_JobHandle = nullptr; } } + public: RpcapdServerInitializer(bool activateRemoteDevice, const std::string& ip, uint16_t port) : m_ProcessHandle(nullptr), m_JobHandle(nullptr) @@ -138,37 +143,35 @@ class RpcapdServerInitializer m_JobHandle = CreateJobObject(nullptr, nullptr); if (m_JobHandle == nullptr) { - throw std::runtime_error("Failed to create a job object with error code: " + std::to_string(GetLastError())); + throw std::runtime_error("Failed to create a job object with error code: " + + std::to_string(GetLastError())); } // Sets up the job limits so closing the job will automatically kill all processes assigned to the job. - // This will prevent the subprocess continuing to live if the current process is killed without unwinding the stack (i.e. std::terminate is called), - // as the OS itself will kill the subprocesses when the last job handle is closed. + // This will prevent the subprocess continuing to live if the current process is killed without unwinding the + // stack (i.e. std::terminate is called), as the OS itself will kill the subprocesses when the last job handle + // is closed. JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobLimitInfo{}; jobLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - if (!SetInformationJobObject(m_JobHandle, JobObjectExtendedLimitInformation, &jobLimitInfo, sizeof(jobLimitInfo))) + if (!SetInformationJobObject(m_JobHandle, JobObjectExtendedLimitInformation, &jobLimitInfo, + sizeof(jobLimitInfo))) { DWORD errCode = GetLastError(); CloseHandle(m_JobHandle); - throw std::runtime_error("Failed to set settings to job object with error code: " + std::to_string(errCode)); + throw std::runtime_error("Failed to set settings to job object with error code: " + + std::to_string(errCode)); } STARTUPINFO si; PROCESS_INFORMATION pi; - ZeroMemory( &si, sizeof(si) ); + ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); - ZeroMemory( &pi, sizeof(pi) ); - if (!CreateProcess ( + ZeroMemory(&pi, sizeof(pi)); + if (!CreateProcess( TEXT(cmd.c_str()), // CreateProcessW (Unicode version) modifies the argument string inplace during internal processing. - TEXT(args.data()), - nullptr, nullptr, false, - CREATE_NEW_CONSOLE, - nullptr, nullptr, - &si, - &pi - )) + TEXT(args.data()), nullptr, nullptr, false, CREATE_NEW_CONSOLE, nullptr, nullptr, &si, &pi)) { DWORD errCode = GetLastError(); CloseHandle(m_JobHandle); @@ -176,7 +179,7 @@ class RpcapdServerInitializer } m_ProcessHandle = pi.hProcess; - CloseHandle(pi.hThread); // We don't need the thread handle, so we can close it. + CloseHandle(pi.hThread); // We don't need the thread handle, so we can close it. if (!AssignProcessToJobObject(m_JobHandle, m_ProcessHandle)) { @@ -204,12 +207,18 @@ class RpcapdServerInitializer return *this; } - ~RpcapdServerInitializer() { killProcessAndCloseHandles(); } + ~RpcapdServerInitializer() + { + killProcessAndCloseHandles(); + } - HANDLE getHandle() const { return m_ProcessHandle; } + HANDLE getHandle() const + { + return m_ProcessHandle; + } }; -#endif // defined(_WIN32) +#endif // defined(_WIN32) PTF_TEST_CASE(TestPcapLiveDeviceList) { @@ -217,7 +226,7 @@ PTF_TEST_CASE(TestPcapLiveDeviceList) PTF_ASSERT_FALSE(devList.empty()); pcpp::IPv4Address defaultGateway = pcpp::IPv4Address::Zero; - for(const auto &iter : devList) + for (const auto& iter : devList) { PTF_ASSERT_FALSE(iter->getName().empty()); if (defaultGateway == pcpp::IPv4Address::Zero) @@ -235,33 +244,32 @@ PTF_TEST_CASE(TestPcapLiveDeviceList) devList = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDevicesList(); PTF_ASSERT_FALSE(devList.empty()); - for(const auto &iter : devList) + for (const auto& iter : devList) { PTF_ASSERT_FALSE(iter->getName().empty()); } - pcpp::PcapLiveDeviceList *clonedDevList = pcpp::PcapLiveDeviceList::getInstance().clone(); + pcpp::PcapLiveDeviceList* clonedDevList = pcpp::PcapLiveDeviceList::getInstance().clone(); PTF_ASSERT_NOT_NULL(clonedDevList); std::vector clonedDevListVector = clonedDevList->getPcapLiveDevicesList(); PTF_ASSERT_EQUAL(clonedDevListVector.size(), devList.size()); auto iterCloned = clonedDevListVector.begin(); - for(auto iter = devList.begin(); iter != devList.end(); ++iter, ++iterCloned) + for (auto iter = devList.begin(); iter != devList.end(); ++iter, ++iterCloned) { PTF_ASSERT_EQUAL((*iter)->getName(), (*iterCloned)->getName()); } delete clonedDevList; PTF_ASSERT_EQUAL(pcpp::PcapLiveDeviceList::getInstance().getDnsServers().size(), dnsServerCount); -} // TestPcapLiveDeviceList - - +} // TestPcapLiveDeviceList PTF_TEST_CASE(TestPcapLiveDeviceListSearch) { pcpp::PcapLiveDevice* liveDev = nullptr; - liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(liveDev); std::string devName(liveDev->getName()); @@ -272,14 +280,13 @@ PTF_TEST_CASE(TestPcapLiveDeviceListSearch) pcpp::PcapLiveDevice* liveDev3 = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIpOrName(devName); PTF_ASSERT_EQUAL(liveDev3, liveDev2, ptr); - liveDev3 = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIpOrName(PcapTestGlobalArgs.ipToSendReceivePackets); + liveDev3 = + pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIpOrName(PcapTestGlobalArgs.ipToSendReceivePackets); PTF_ASSERT_EQUAL(liveDev3, liveDev, ptr); liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp("255.255.255.250"); PTF_ASSERT_NULL(liveDev); -} // TestPcapLiveDeviceListSearch - - +} // TestPcapLiveDeviceListSearch PTF_TEST_CASE(TestPcapLiveDevice) { @@ -292,7 +299,8 @@ PTF_TEST_CASE(TestPcapLiveDevice) DeviceTeardown devTeardown(liveDev); int packetCount = 0; int numOfTimeStatsWereInvoked = 0; - PTF_ASSERT_TRUE(liveDev->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, static_cast(&numOfTimeStatsWereInvoked))); + PTF_ASSERT_TRUE(liveDev->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, + static_cast(&numOfTimeStatsWereInvoked))); int totalSleepTime = 0; while (totalSleepTime <= 20) { @@ -306,22 +314,21 @@ PTF_TEST_CASE(TestPcapLiveDevice) liveDev->stopCapture(); PTF_ASSERT_GREATER_THAN(packetCount, 0); - PTF_ASSERT_GREATER_OR_EQUAL_THAN(numOfTimeStatsWereInvoked, totalSleepTime-2); + PTF_ASSERT_GREATER_OR_EQUAL_THAN(numOfTimeStatsWereInvoked, totalSleepTime - 2); pcpp::IPcapDevice::PcapStats statistics; liveDev->getStatistics(statistics); - //Bad test - on high traffic libpcap/WinPcap/Npcap sometimes drop packets - //PTF_ASSERT_EQUALS((uint32_t)statistics.ps_drop, 0); + // Bad test - on high traffic libpcap/WinPcap/Npcap sometimes drop packets + // PTF_ASSERT_EQUALS((uint32_t)statistics.ps_drop, 0); liveDev->close(); PTF_ASSERT_FALSE(liveDev->isOpened()); // a negative test pcpp::Logger::getInstance().suppressLogs(); - PTF_ASSERT_FALSE(liveDev->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, static_cast(&numOfTimeStatsWereInvoked))); + PTF_ASSERT_FALSE(liveDev->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, + static_cast(&numOfTimeStatsWereInvoked))); pcpp::Logger::getInstance().enableLogs(); -} // TestPcapLiveDevice - - +} // TestPcapLiveDevice PTF_TEST_CASE(TestPcapLiveDeviceClone) { @@ -336,7 +343,7 @@ PTF_TEST_CASE(TestPcapLiveDeviceClone) #ifdef _WIN32 // Tests if device pointer points to a Windows Live Device on a Windows machine. PTF_ASSERT_NOT_NULL(dynamic_cast(originalDev)); -#endif // _WIN32 +#endif // _WIN32 liveDev = originalDev->clone(); } @@ -346,14 +353,15 @@ PTF_TEST_CASE(TestPcapLiveDeviceClone) #ifdef _WIN32 // Tests if the clone is correctly returns a Windows Live Device on Windows systems. PTF_ASSERT_NOT_NULL(dynamic_cast(liveDev)); -#endif // _WIN32 +#endif // _WIN32 PTF_ASSERT_GREATER_THAN(liveDev->getMtu(), 0); PTF_ASSERT_TRUE(liveDev->open()); DeviceTeardown devTeardown(liveDev, true); int packetCount = 0; int numOfTimeStatsWereInvoked = 0; - PTF_ASSERT_TRUE(liveDev->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, static_cast(&numOfTimeStatsWereInvoked))); + PTF_ASSERT_TRUE(liveDev->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, + static_cast(&numOfTimeStatsWereInvoked))); int totalSleepTime = 0; while (totalSleepTime <= 20) { @@ -367,22 +375,21 @@ PTF_TEST_CASE(TestPcapLiveDeviceClone) liveDev->stopCapture(); PTF_ASSERT_GREATER_THAN(packetCount, 0); - PTF_ASSERT_GREATER_OR_EQUAL_THAN(numOfTimeStatsWereInvoked, totalSleepTime-1); + PTF_ASSERT_GREATER_OR_EQUAL_THAN(numOfTimeStatsWereInvoked, totalSleepTime - 1); pcpp::IPcapDevice::PcapStats statistics; liveDev->getStatistics(statistics); - //Bad test - on high traffic libpcap/WinPcap/Npcap sometimes drop packets - //PTF_ASSERT_EQUALS((uint32_t)statistics.ps_drop, 0); + // Bad test - on high traffic libpcap/WinPcap/Npcap sometimes drop packets + // PTF_ASSERT_EQUALS((uint32_t)statistics.ps_drop, 0); liveDev->close(); PTF_ASSERT_FALSE(liveDev->isOpened()); // a negative test pcpp::Logger::getInstance().suppressLogs(); - PTF_ASSERT_FALSE(liveDev->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, static_cast(&numOfTimeStatsWereInvoked))); + PTF_ASSERT_FALSE(liveDev->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, + static_cast(&numOfTimeStatsWereInvoked))); pcpp::Logger::getInstance().enableLogs(); -} // TestPcapLiveDeviceClone - - +} // TestPcapLiveDeviceClone PTF_TEST_CASE(TestPcapLiveDeviceNoNetworking) { @@ -393,7 +400,7 @@ PTF_TEST_CASE(TestPcapLiveDeviceNoNetworking) std::vector devList = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDevicesList(); PTF_ASSERT_FALSE(devList.empty()); - auto iter = std::find_if(devList.begin(), devList.end(), [](const pcpp::PcapLiveDevice *dev) { + auto iter = std::find_if(devList.begin(), devList.end(), [](const pcpp::PcapLiveDevice* dev) { return !dev->getLoopback() && dev->getIPv4Address() != pcpp::IPv4Address::Zero; }); if (iter != devList.end()) @@ -413,13 +420,12 @@ PTF_TEST_CASE(TestPcapLiveDeviceNoNetworking) pcpp::Logger::getInstance().enableLogs(); PTF_ASSERT_NULL(liveDev); -} // TestPcapLiveDeviceNoNetworking - - +} // TestPcapLiveDeviceNoNetworking PTF_TEST_CASE(TestPcapLiveDeviceStatsMode) { - pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(liveDev); PTF_ASSERT_TRUE(liveDev->open()); DeviceTeardown devTeardown(liveDev); @@ -430,7 +436,7 @@ PTF_TEST_CASE(TestPcapLiveDeviceStatsMode) while (totalSleepTime <= 6) { pcpp::multiPlatformSleep(2); - totalSleepTime +=2; + totalSleepTime += 2; pcpp::IPcapDevice::PcapStats statistics; liveDev->getStatistics(statistics); if (statistics.packetsRecv > 2) @@ -440,12 +446,12 @@ PTF_TEST_CASE(TestPcapLiveDeviceStatsMode) PTF_PRINT_VERBOSE("Total sleep time: " << totalSleepTime << " secs"); liveDev->stopCapture(); - PTF_ASSERT_GREATER_OR_EQUAL_THAN(numOfTimeStatsWereInvoked, totalSleepTime-1); + PTF_ASSERT_GREATER_OR_EQUAL_THAN(numOfTimeStatsWereInvoked, totalSleepTime - 1); pcpp::IPcapDevice::PcapStats statistics; liveDev->getStatistics(statistics); PTF_ASSERT_GREATER_THAN((uint32_t)statistics.packetsRecv, 2); - //Bad test - on high traffic libpcap/WinPcap/Npcap sometimes drop packets - //PTF_ASSERT_EQUAL((uint32_t)statistics.ps_drop, 0); + // Bad test - on high traffic libpcap/WinPcap/Npcap sometimes drop packets + // PTF_ASSERT_EQUAL((uint32_t)statistics.ps_drop, 0); liveDev->close(); PTF_ASSERT_FALSE(liveDev->isOpened()); @@ -453,25 +459,24 @@ PTF_TEST_CASE(TestPcapLiveDeviceStatsMode) pcpp::Logger::getInstance().suppressLogs(); PTF_ASSERT_FALSE(liveDev->startCapture(1, &statsUpdate, static_cast(&numOfTimeStatsWereInvoked))); pcpp::Logger::getInstance().enableLogs(); -} // TestPcapLiveDeviceStatsMode - - +} // TestPcapLiveDeviceStatsMode PTF_TEST_CASE(TestPcapLiveDeviceBlockingMode) { std::vector configs; - configs.emplace_back(); // the default config + configs.emplace_back(); // the default config #if !defined(_WIN32) - configs.emplace_back(); // the config used poll + configs.emplace_back(); // the config used poll configs[1].usePoll = true; #endif // test the common behaviour for all configs - for(const auto & config: configs) + for (const auto& config : configs) { // open device - pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(liveDev); PTF_ASSERT_TRUE(liveDev->open(config)); DeviceTeardown devTeardown(liveDev); @@ -555,8 +560,7 @@ PTF_TEST_CASE(TestPcapLiveDeviceBlockingMode) PTF_ASSERT_FALSE(liveDev->startCapture(packetArrives, &packetCount)); pcpp::Logger::getInstance().enableLogs(); } -} // TestPcapLiveDeviceBlockingMode - +} // TestPcapLiveDeviceBlockingMode PTF_TEST_CASE(TestPcapLiveDeviceWithLambda) { @@ -570,17 +574,16 @@ PTF_TEST_CASE(TestPcapLiveDeviceWithLambda) int packetCount = 0; int numOfTimeStatsWereInvoked = 0; - auto packetArrivesLambda = [](pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* pDevice, void* userCookie) - { + auto packetArrivesLambda = [](pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* pDevice, void* userCookie) { (*static_cast(userCookie))++; }; - auto statsUpdateLambda = [](pcpp::IPcapDevice::PcapStats& stats, void* userCookie) - { + auto statsUpdateLambda = [](pcpp::IPcapDevice::PcapStats& stats, void* userCookie) { (*static_cast(userCookie))++; }; - PTF_ASSERT_TRUE(liveDev->startCapture(packetArrivesLambda , static_cast(&packetCount), 1, statsUpdateLambda, static_cast(&numOfTimeStatsWereInvoked))); + PTF_ASSERT_TRUE(liveDev->startCapture(packetArrivesLambda, static_cast(&packetCount), 1, statsUpdateLambda, + static_cast(&numOfTimeStatsWereInvoked))); int totalSleepTime = 0; while (totalSleepTime <= 20) { @@ -594,17 +597,14 @@ PTF_TEST_CASE(TestPcapLiveDeviceWithLambda) liveDev->stopCapture(); PTF_ASSERT_GREATER_THAN(packetCount, 0); - PTF_ASSERT_GREATER_OR_EQUAL_THAN(numOfTimeStatsWereInvoked, totalSleepTime-2); -} // TestPcapLiveDeviceWithLambda - - + PTF_ASSERT_GREATER_OR_EQUAL_THAN(numOfTimeStatsWereInvoked, totalSleepTime - 2); +} // TestPcapLiveDeviceWithLambda PTF_TEST_CASE(TestPcapLiveDeviceBlockingModeWithLambda) { - auto packetArrivesBlockingModeNoTimeoutLambda = []( - pcpp::RawPacket *rawPacket, pcpp::PcapLiveDevice *dev, void *userCookie) - { - int *packetCount = static_cast(userCookie); + auto packetArrivesBlockingModeNoTimeoutLambda = [](pcpp::RawPacket* rawPacket, pcpp::PcapLiveDevice* dev, + void* userCookie) { + int* packetCount = static_cast(userCookie); if ((*packetCount) == 5) return true; @@ -613,7 +613,8 @@ PTF_TEST_CASE(TestPcapLiveDeviceBlockingModeWithLambda) }; // open device - pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(liveDev); PTF_ASSERT_TRUE(liveDev->open()); DeviceTeardown devTeardown(liveDev); @@ -628,13 +629,12 @@ PTF_TEST_CASE(TestPcapLiveDeviceBlockingModeWithLambda) pcpp::Logger::getInstance().suppressLogs(); PTF_ASSERT_FALSE(liveDev->startCapture(packetArrives, &packetCount)); pcpp::Logger::getInstance().enableLogs(); -} // TestPcapLiveDeviceBlockingModeWithLambda - - +} // TestPcapLiveDeviceBlockingModeWithLambda PTF_TEST_CASE(TestPcapLiveDeviceSpecialCfg) { - pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(liveDev); // open device in default mode @@ -643,7 +643,8 @@ PTF_TEST_CASE(TestPcapLiveDeviceSpecialCfg) // sanity test - make sure packets are captured in default mode int packetCount = 0; - PTF_ASSERT_EQUAL(liveDev->startCaptureBlockingMode(packetArrivesBlockingModeNoTimeoutPacketCount, &packetCount, 7), -1); + PTF_ASSERT_EQUAL(liveDev->startCaptureBlockingMode(packetArrivesBlockingModeNoTimeoutPacketCount, &packetCount, 7), + -1); liveDev->close(); PTF_ASSERT_FALSE(liveDev->isOpened()); @@ -657,7 +658,8 @@ PTF_TEST_CASE(TestPcapLiveDeviceSpecialCfg) PTF_ASSERT_TRUE(liveDev->open(devConfig)); // start capturing in non-default configuration - PTF_ASSERT_EQUAL(liveDev->startCaptureBlockingMode(packetArrivesBlockingModeNoTimeoutPacketCount, &packetCount, 7), -1); + PTF_ASSERT_EQUAL(liveDev->startCaptureBlockingMode(packetArrivesBlockingModeNoTimeoutPacketCount, &packetCount, 7), + -1); liveDev->close(); PTF_ASSERT_FALSE(liveDev->isOpened()); @@ -668,11 +670,13 @@ PTF_TEST_CASE(TestPcapLiveDeviceSpecialCfg) packetCount = 0; // create a non-default configuration with only capturing incoming packets and open the device again - pcpp::PcapLiveDevice::DeviceConfiguration devConfigWithDirection(pcpp::PcapLiveDevice::Promiscuous, 10, 2000000, pcpp::PcapLiveDevice::PCPP_OUT); + pcpp::PcapLiveDevice::DeviceConfiguration devConfigWithDirection(pcpp::PcapLiveDevice::Promiscuous, 10, 2000000, + pcpp::PcapLiveDevice::PCPP_OUT); PTF_ASSERT_TRUE(liveDev->open(devConfigWithDirection)); // start capturing in non-default configuration witch only captures incoming traffics - PTF_ASSERT_EQUAL(liveDev->startCaptureBlockingMode(packetArrivesBlockingModeNoTimeoutPacketCount, &packetCount, 7), -1); + PTF_ASSERT_EQUAL(liveDev->startCaptureBlockingMode(packetArrivesBlockingModeNoTimeoutPacketCount, &packetCount, 7), + -1); liveDev->close(); PTF_ASSERT_FALSE(liveDev->isOpened()); @@ -683,25 +687,26 @@ PTF_TEST_CASE(TestPcapLiveDeviceSpecialCfg) // create a non-default configuration with a snapshot length of 10 bytes int snaplen = 20; - pcpp::PcapLiveDevice::DeviceConfiguration devConfigWithSnaplen(pcpp::PcapLiveDevice::Promiscuous, 0, 0, pcpp::PcapLiveDevice::PCPP_INOUT, snaplen); + pcpp::PcapLiveDevice::DeviceConfiguration devConfigWithSnaplen(pcpp::PcapLiveDevice::Promiscuous, 0, 0, + pcpp::PcapLiveDevice::PCPP_INOUT, snaplen); liveDev->open(devConfigWithSnaplen); // start capturing in non-default configuration witch only captures incoming traffics - // TODO: for some reason snaplen change doesn't work in Windows (WinPcap and Npcap). Setting the check as NON_CRITICAL until we figure it out + // TODO: for some reason snaplen change doesn't work in Windows (WinPcap and Npcap). Setting the check as + // NON_CRITICAL until we figure it out PTF_NON_CRITICAL_EQUAL(liveDev->startCaptureBlockingMode(packetArrivesBlockingModeWithSnaplen, &snaplen, 3), -1); liveDev->close(); -} // TestPcapLiveDeviceSpecialCfg - - +} // TestPcapLiveDeviceSpecialCfg PTF_TEST_CASE(TestWinPcapLiveDevice) { #if defined(_WIN32) - pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(liveDev); PTF_ASSERT_EQUAL(liveDev->getDeviceType(), pcpp::PcapLiveDevice::WinPcapDevice, enum); @@ -713,7 +718,8 @@ PTF_TEST_CASE(TestWinPcapLiveDevice) PTF_ASSERT_TRUE(winPcapLiveDevice->setMinAmountOfDataToCopyFromKernelToApplication(100000)); int packetCount = 0; int numOfTimeStatsWereInvoked = 0; - PTF_ASSERT_TRUE(winPcapLiveDevice->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, static_cast(&numOfTimeStatsWereInvoked))); + PTF_ASSERT_TRUE(winPcapLiveDevice->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, + static_cast(&numOfTimeStatsWereInvoked))); for (int i = 0; i < 5; i++) { sendURLRequest("www.ebay.com"); @@ -722,8 +728,8 @@ PTF_TEST_CASE(TestWinPcapLiveDevice) pcpp::IPcapDevice::PcapStats statistics; winPcapLiveDevice->getStatistics(statistics); PTF_ASSERT_GREATER_THAN(statistics.packetsRecv, 20); - //Bad test - on high traffic libpcap/WinPcap/Npcap sometimes drop packets - //PTF_ASSERT_EQUAL((uint32_t)statistics.packetsDrop, 0); + // Bad test - on high traffic libpcap/WinPcap/Npcap sometimes drop packets + // PTF_ASSERT_EQUAL((uint32_t)statistics.packetsDrop, 0); winPcapLiveDevice->stopCapture(); PTF_ASSERT_TRUE(winPcapLiveDevice->setMinAmountOfDataToCopyFromKernelToApplication(defaultDataToCopy)); winPcapLiveDevice->close(); @@ -731,18 +737,18 @@ PTF_TEST_CASE(TestWinPcapLiveDevice) // a negative test pcpp::Logger::getInstance().suppressLogs(); - PTF_ASSERT_FALSE(winPcapLiveDevice->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, static_cast(&numOfTimeStatsWereInvoked))); + PTF_ASSERT_FALSE(winPcapLiveDevice->startCapture(&packetArrives, static_cast(&packetCount), 1, &statsUpdate, + static_cast(&numOfTimeStatsWereInvoked))); pcpp::Logger::getInstance().enableLogs(); #else - pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* liveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(liveDev); PTF_ASSERT_EQUAL(liveDev->getDeviceType(), pcpp::PcapLiveDevice::LibPcapDevice, enum); #endif -} // TestWinPcapLiveDevice - - +} // TestWinPcapLiveDevice PTF_TEST_CASE(TestSendPacket) { @@ -758,7 +764,7 @@ PTF_TEST_CASE(TestSendPacket) PTF_ASSERT_GREATER_THAN(liveDev->getMtu(), 0); uint32_t mtu = liveDev->getMtu(); - int buffLen = mtu+1 + sizeof(pcpp::ether_header); + int buffLen = mtu + 1 + sizeof(pcpp::ether_header); uint8_t* buff = new uint8_t[buffLen]; memset(buff, 0, buffLen); pcpp::Logger::getInstance().suppressLogs(); @@ -768,17 +774,17 @@ PTF_TEST_CASE(TestSendPacket) pcpp::RawPacket rawPacket; int packetsSent = 0; int packetsRead = 0; - while(fileReaderDev.getNextPacket(rawPacket)) + while (fileReaderDev.getNextPacket(rawPacket)) { packetsRead++; - //send packet as RawPacket + // send packet as RawPacket PTF_ASSERT_TRUE(liveDev->sendPacket(rawPacket)); - //send packet as raw data + // send packet as raw data PTF_ASSERT_TRUE(liveDev->sendPacket(rawPacket.getRawData(), rawPacket.getRawDataLen())); - //send packet as parsed EthPacekt + // send packet as parsed EthPacekt pcpp::Packet packet(&rawPacket); PTF_ASSERT_TRUE(liveDev->sendPacket(&packet)); @@ -791,10 +797,7 @@ PTF_TEST_CASE(TestSendPacket) fileReaderDev.close(); delete[] buff; -} // TestSendPacket - - - +} // TestSendPacket PTF_TEST_CASE(TestSendPackets) { @@ -812,16 +815,16 @@ PTF_TEST_CASE(TestSendPackets) pcpp::PointerVector packetVec; pcpp::Packet* packetArr[10000]; int packetsRead = 0; - while(fileReaderDev.getNextPacket(rawPacketArr[packetsRead])) + while (fileReaderDev.getNextPacket(rawPacketArr[packetsRead])) { packetVec.pushBack(new pcpp::Packet(&rawPacketArr[packetsRead])); packetsRead++; } - //send packets as RawPacket array + // send packets as RawPacket array int packetsSentAsRaw = liveDev->sendPackets(rawPacketArr, packetsRead); - //send packets as parsed EthPacekt array + // send packets as parsed EthPacekt array std::copy(packetVec.begin(), packetVec.end(), packetArr); int packetsSentAsParsed = liveDev->sendPackets(packetArr, packetsRead); @@ -830,10 +833,7 @@ PTF_TEST_CASE(TestSendPackets) liveDev->close(); fileReaderDev.close(); -} // TestSendPackets - - - +} // TestSendPackets PTF_TEST_CASE(TestMtuSize) { @@ -881,9 +881,10 @@ PTF_TEST_CASE(TestMtuSize) // Try sending the packet PTF_ASSERT_TRUE(liveDev->sendPacket(&smallPacket)); pcpp::RawPacket* rawSmallPacketPtr = smallPacket.getRawPacket(); - pcpp::RawPacket &rawSmallPacketRef = *rawSmallPacketPtr; + pcpp::RawPacket& rawSmallPacketRef = *rawSmallPacketPtr; PTF_ASSERT_TRUE(liveDev->sendPacket(rawSmallPacketRef, true)); - PTF_ASSERT_TRUE(liveDev->sendPacket(rawSmallPacketPtr->getRawData(), rawSmallPacketPtr->getRawDataLen(), true, pcpp::LINKTYPE_ETHERNET)); + PTF_ASSERT_TRUE(liveDev->sendPacket(rawSmallPacketPtr->getRawData(), rawSmallPacketPtr->getRawDataLen(), true, + pcpp::LINKTYPE_ETHERNET)); delete[] smallData; @@ -914,23 +915,22 @@ PTF_TEST_CASE(TestMtuSize) PTF_ASSERT_FALSE(liveDev->sendPacket(&largePacket)); pcpp::RawPacket* rawLargePacketPtr = largePacket.getRawPacket(); - pcpp::RawPacket &rawLargePacketRef = *rawLargePacketPtr; + pcpp::RawPacket& rawLargePacketRef = *rawLargePacketPtr; PTF_ASSERT_FALSE(liveDev->sendPacket(rawLargePacketRef, true)); - PTF_ASSERT_FALSE(liveDev->sendPacket(rawLargePacketPtr->getRawData(), rawLargePacketPtr->getRawDataLen(), true, pcpp::LINKTYPE_ETHERNET)); + PTF_ASSERT_FALSE(liveDev->sendPacket(rawLargePacketPtr->getRawData(), rawLargePacketPtr->getRawDataLen(), true, + pcpp::LINKTYPE_ETHERNET)); pcpp::Logger::getInstance().enableLogs(); delete[] largeData; -} // TestMtuSize - - - +} // TestMtuSize PTF_TEST_CASE(TestRemoteCapture) { #if defined(_WIN32) bool useRemoteDevicesFromArgs = (PcapTestGlobalArgs.remoteIp != "") && (PcapTestGlobalArgs.remotePort > 0); - std::string remoteDeviceIP = (useRemoteDevicesFromArgs ? PcapTestGlobalArgs.remoteIp : PcapTestGlobalArgs.ipToSendReceivePackets); + std::string remoteDeviceIP = + (useRemoteDevicesFromArgs ? PcapTestGlobalArgs.remoteIp : PcapTestGlobalArgs.ipToSendReceivePackets); uint16_t remoteDevicePort = (useRemoteDevicesFromArgs ? PcapTestGlobalArgs.remotePort : 12321); RpcapdServerInitializer rpcapdInitializer(!useRemoteDevicesFromArgs, remoteDeviceIP, remoteDevicePort); @@ -938,9 +938,11 @@ PTF_TEST_CASE(TestRemoteCapture) PTF_ASSERT_NOT_NULL(rpcapdInitializer.getHandle()); pcpp::IPv4Address remoteDeviceIPAddr(remoteDeviceIP); - pcpp::PcapRemoteDeviceList* remoteDevices = pcpp::PcapRemoteDeviceList::getRemoteDeviceList(remoteDeviceIPAddr, remoteDevicePort); + pcpp::PcapRemoteDeviceList* remoteDevices = + pcpp::PcapRemoteDeviceList::getRemoteDeviceList(remoteDeviceIPAddr, remoteDevicePort); PTF_ASSERT_NOT_NULL(remoteDevices); - for (pcpp::PcapRemoteDeviceList::RemoteDeviceListIterator remoteDevIter = remoteDevices->begin(); remoteDevIter != remoteDevices->end(); remoteDevIter++) + for (pcpp::PcapRemoteDeviceList::RemoteDeviceListIterator remoteDevIter = remoteDevices->begin(); + remoteDevIter != remoteDevices->end(); remoteDevIter++) { PTF_ASSERT_FALSE((*remoteDevIter)->getName().empty()); } @@ -1000,7 +1002,7 @@ PTF_TEST_CASE(TestRemoteCapture) int packetsSent = remoteDevice->sendPackets(packetsToSend); PTF_ASSERT_EQUAL(packetsSent, (int)packetsToSend.size()); - //check statistics + // check statistics pcpp::IPcapDevice::PcapStats stats; remoteDevice->getStatistics(stats); PTF_ASSERT_EQUAL((uint32_t)stats.packetsRecv, capturedPacketsSize); @@ -1015,4 +1017,4 @@ PTF_TEST_CASE(TestRemoteCapture) PTF_SKIP_TEST("This test can only run in Windows environment"); #endif -} // TestRemoteCapture +} // TestRemoteCapture diff --git a/Tests/Pcap++Test/Tests/LoggerTests.cpp b/Tests/Pcap++Test/Tests/LoggerTests.cpp index 5312ec14ce..96ffc58054 100644 --- a/Tests/Pcap++Test/Tests/LoggerTests.cpp +++ b/Tests/Pcap++Test/Tests/LoggerTests.cpp @@ -8,7 +8,6 @@ #include #include "SystemUtils.h" - namespace pcpp { void invokeDebugLog() @@ -20,49 +19,49 @@ namespace pcpp { PCPP_LOG_ERROR("error log" << message); } -} - +} // namespace pcpp class LogPrinter { - public: - static int lastLogLevelSeen; - static std::string* lastLogMessageSeen; - static std::string* lastFilenameSeen; - static std::string* lastMethodSeen; - static int lastLineSeen; - - static void logPrinter(pcpp::Logger::LogLevel logLevel, const std::string& logMessage, const std::string& fileName, const std::string& method, const int line) +public: + static int lastLogLevelSeen; + static std::string* lastLogMessageSeen; + static std::string* lastFilenameSeen; + static std::string* lastMethodSeen; + static int lastLineSeen; + + static void logPrinter(pcpp::Logger::LogLevel logLevel, const std::string& logMessage, const std::string& fileName, + const std::string& method, const int line) + { + LogPrinter::clean(); + LogPrinter::lastLogLevelSeen = (int)logLevel; + LogPrinter::lastLogMessageSeen = new std::string(logMessage); + LogPrinter::lastFilenameSeen = new std::string(fileName); + LogPrinter::lastMethodSeen = new std::string(method); + LogPrinter::lastLineSeen = line; + } + + static void clean() + { + LogPrinter::lastLogLevelSeen = 999; + LogPrinter::lastLineSeen = 99999; + if (LogPrinter::lastLogMessageSeen != nullptr) { - LogPrinter::clean(); - LogPrinter::lastLogLevelSeen = (int)logLevel; - LogPrinter::lastLogMessageSeen = new std::string(logMessage); - LogPrinter::lastFilenameSeen = new std::string(fileName); - LogPrinter::lastMethodSeen = new std::string(method); - LogPrinter::lastLineSeen = line; + delete LogPrinter::lastLogMessageSeen; + LogPrinter::lastLogMessageSeen = nullptr; + } + if (LogPrinter::lastFilenameSeen != nullptr) + { + delete LogPrinter::lastFilenameSeen; + LogPrinter::lastFilenameSeen = nullptr; } - static void clean() + if (LogPrinter::lastMethodSeen != nullptr) { - LogPrinter::lastLogLevelSeen = 999; - LogPrinter::lastLineSeen = 99999; - if (LogPrinter::lastLogMessageSeen != nullptr) - { - delete LogPrinter::lastLogMessageSeen; - LogPrinter::lastLogMessageSeen = nullptr; - } - if (LogPrinter::lastFilenameSeen != nullptr) - { - delete LogPrinter::lastFilenameSeen; - LogPrinter::lastFilenameSeen = nullptr; - } - - if (LogPrinter::lastMethodSeen != nullptr) - { - delete LogPrinter::lastMethodSeen; - LogPrinter::lastMethodSeen = nullptr; - } + delete LogPrinter::lastMethodSeen; + LogPrinter::lastMethodSeen = nullptr; } + } }; int LogPrinter::lastLogLevelSeen = 999; @@ -71,29 +70,27 @@ std::string* LogPrinter::lastFilenameSeen = nullptr; std::string* LogPrinter::lastMethodSeen = nullptr; int LogPrinter::lastLineSeen = 99999; - class MultiThreadLogCounter { - public: - static const int ThreadCount = 5; - static int logMessageThreadCount[ThreadCount]; - static void logPrinter(pcpp::Logger::LogLevel logLevel, const std::string& logMessage, const std::string& fileName, const std::string& method, const int line) - { - int threadId = logMessage[logMessage.length() - 1] - '0'; - MultiThreadLogCounter::logMessageThreadCount[threadId]++; - } +public: + static const int ThreadCount = 5; + static int logMessageThreadCount[ThreadCount]; + static void logPrinter(pcpp::Logger::LogLevel logLevel, const std::string& logMessage, const std::string& fileName, + const std::string& method, const int line) + { + int threadId = logMessage[logMessage.length() - 1] - '0'; + MultiThreadLogCounter::logMessageThreadCount[threadId]++; + } }; -int MultiThreadLogCounter::logMessageThreadCount[MultiThreadLogCounter::ThreadCount] = {0, 0, 0, 0, 0}; - +int MultiThreadLogCounter::logMessageThreadCount[MultiThreadLogCounter::ThreadCount] = { 0, 0, 0, 0, 0 }; #if defined(_WIN32) -#define SEPARATOR '\\' +# define SEPARATOR '\\' #else -#define SEPARATOR '/' +# define SEPARATOR '/' #endif - std::string getLFileName(const std::string& path) { std::string result = path; @@ -101,18 +98,17 @@ std::string getLFileName(const std::string& path) size_t i = result.rfind('/', result.length()); if (i != std::string::npos) { - result = result.substr(i+1, result.length() - i); + result = result.substr(i + 1, result.length() - i); } // check the "\\" separator i = result.rfind('\\', result.length()); if (i != std::string::npos) { - result = result.substr(i+1, result.length() - i); + result = result.substr(i + 1, result.length() - i); } return result; } - std::string getLowerCaseFileName(const std::string& path) { std::string result = getLFileName(path); @@ -120,33 +116,30 @@ std::string getLowerCaseFileName(const std::string& path) return result; } - std::string getMethodWithoutNamespace(const std::string& method) { std::string result = method; size_t i = result.rfind(':', result.length()); if (i != std::string::npos) { - result = result.substr(i+1, result.length() - i); + result = result.substr(i + 1, result.length() - i); } return result; } - class LoggerCleaner { - public: - ~LoggerCleaner() - { - pcpp::Logger::getInstance().enableLogs(); - pcpp::Logger::getInstance().setAllModulesToLogLevel(pcpp::Logger::Info); - pcpp::Logger::getInstance().resetLogPrinter(); - std::cout.clear(); - LogPrinter::clean(); - } +public: + ~LoggerCleaner() + { + pcpp::Logger::getInstance().enableLogs(); + pcpp::Logger::getInstance().setAllModulesToLogLevel(pcpp::Logger::Info); + pcpp::Logger::getInstance().resetLogPrinter(); + std::cout.clear(); + LogPrinter::clean(); + } }; - void printLogThread(int threadId) { std::random_device rd; @@ -158,7 +151,7 @@ void printLogThread(int threadId) for (int i = 0; i < 1000; i++) { pcpp::invokeErrorLog(threadIdAsString); - int sleepTime = dist(simpleRand); + int sleepTime = dist(simpleRand); pcpp::multiPlatformMSleep(sleepTime); } } @@ -177,7 +170,7 @@ PTF_TEST_CASE(TestLoggerMultiThread) threads[i] = std::thread(printLogThread, i); } - for (auto & thread : threads) + for (auto& thread : threads) { thread.join(); } @@ -190,8 +183,7 @@ PTF_TEST_CASE(TestLoggerMultiThread) } PTF_ASSERT_EQUAL(totalLogMessages, 5000); -} // TestLoggerMultiThread - +} // TestLoggerMultiThread PTF_TEST_CASE(TestLogger) { @@ -305,4 +297,4 @@ PTF_TEST_CASE(TestLogger) pcpp::invokeErrorLog(); PTF_ASSERT_EQUAL(LogPrinter::lastLogLevelSeen, 999); PTF_ASSERT_NULL(LogPrinter::lastLogMessageSeen); -} // TestLogger +} // TestLogger diff --git a/Tests/Pcap++Test/Tests/PacketParsingTests.cpp b/Tests/Pcap++Test/Tests/PacketParsingTests.cpp index 230c5393b1..c25f91f9cb 100644 --- a/Tests/Pcap++Test/Tests/PacketParsingTests.cpp +++ b/Tests/Pcap++Test/Tests/PacketParsingTests.cpp @@ -8,7 +8,6 @@ #include "DnsLayer.h" #include "PcapFileDevice.h" - PTF_TEST_CASE(TestHttpRequestParsing) { pcpp::PcapFileReaderDevice readerDev(EXAMPLE_PCAP_HTTP_REQUEST); @@ -103,10 +102,10 @@ PTF_TEST_CASE(TestHttpRequestParsing) PTF_ASSERT_EQUAL(packetCount, 385); - // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET " || tcp contains "POST " || tcp contains "HEAD " || tcp contains "OPTIONS ") + // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET " || tcp contains "POST " || + // tcp contains "HEAD " || tcp contains "OPTIONS ") PTF_ASSERT_EQUAL(httpPackets, 385); - PTF_ASSERT_EQUAL(otherMethodReqs, 0); // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET ") @@ -118,8 +117,8 @@ PTF_TEST_CASE(TestHttpRequestParsing) // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "HEAD ") PTF_ASSERT_EQUAL(headReqs, 5); - - // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET " || tcp contains "POST ") && (tcp matches "home.*HTTP/1.1") + // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET " || tcp contains "POST ") && + // (tcp matches "home.*HTTP/1.1") PTF_ASSERT_EQUAL(homeReqs, 13); // Wireshark filter: http.request.full_uri contains .swf PTF_ASSERT_EQUAL(swfReqs, 4); @@ -131,17 +130,16 @@ PTF_TEST_CASE(TestHttpRequestParsing) // Wireshark filter: tcp contains "Host: www.winwin.co.il" PTF_ASSERT_EQUAL(winwinReqs, 20); - - // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET " || tcp contains "POST " || tcp contains "HEAD " || tcp contains "OPTIONS ") && (tcp contains "Firefox/33.0") + // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET " || tcp contains "POST " || + // tcp contains "HEAD " || tcp contains "OPTIONS ") && (tcp contains "Firefox/33.0") PTF_ASSERT_EQUAL(ffReqs, 233); - // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET " || tcp contains "POST " || tcp contains "HEAD " || tcp contains "OPTIONS ") && (tcp contains "Chrome/38.0") + // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET " || tcp contains "POST " || + // tcp contains "HEAD " || tcp contains "OPTIONS ") && (tcp contains "Chrome/38.0") PTF_ASSERT_EQUAL(chromeReqs, 82); - // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET " || tcp contains "POST " || tcp contains "HEAD " || tcp contains "OPTIONS ") && (tcp contains "Trident/7.0") + // Wireshark filter: (tcp.dstport == 80 || tcp.dstport == 8080) && (tcp contains "GET " || tcp contains "POST " || + // tcp contains "HEAD " || tcp contains "OPTIONS ") && (tcp contains "Trident/7.0") PTF_ASSERT_EQUAL(ieReqs, 55); -} // TestHttpRequestParsing - - - +} // TestHttpRequestParsing PTF_TEST_CASE(TestHttpResponseParsing) { @@ -175,11 +173,16 @@ PTF_TEST_CASE(TestHttpResponseParsing) pcpp::HttpResponseLayer* httpResLayer = packet.getLayerOfType(); PTF_ASSERT_NOT_NULL(httpResLayer->getFirstLine()); - if(httpResLayer->getFirstLine()->getStatusCode() == pcpp::HttpResponseStatusCode::Http200OK) { + if (httpResLayer->getFirstLine()->getStatusCode() == pcpp::HttpResponseStatusCode::Http200OK) + { http200OKCounter++; - } else if(httpResLayer->getFirstLine()->getStatusCode() == pcpp::HttpResponseStatusCode::Http302) { + } + else if (httpResLayer->getFirstLine()->getStatusCode() == pcpp::HttpResponseStatusCode::Http302) + { http302Counter++; - } else if(httpResLayer->getFirstLine()->getStatusCode() == pcpp::HttpResponseStatusCode::Http304NotModified ) { + } + else if (httpResLayer->getFirstLine()->getStatusCode() == pcpp::HttpResponseStatusCode::Http304NotModified) + { http304NotModifiedCounter++; } @@ -209,7 +212,6 @@ PTF_TEST_CASE(TestHttpResponseParsing) if (length > 100000) bigResponses++; } - } PTF_ASSERT_EQUAL(packetCount, 682); @@ -228,21 +230,22 @@ PTF_TEST_CASE(TestHttpResponseParsing) // wireshark filter: http.response && (tcp.srcport == 80 || tcp.srcport == 8080) && http.content_type == "text/html" PTF_ASSERT_EQUAL(textHtmlCount, 38); - // wireshark filter: http.response && (tcp.srcport == 80 || tcp.srcport == 8080) && http.content_type contains "image/" + // wireshark filter: http.response && (tcp.srcport == 80 || tcp.srcport == 8080) && http.content_type contains + // "image/" PTF_ASSERT_EQUAL(imageCount, 369); - // wireshark filter: (tcp.srcport == 80 || tcp.srcport == 8080) && tcp contains "HTTP/1." && (tcp contains "Transfer-Encoding: chunked" || tcp contains "Transfer-Encoding: chunked" || tcp contains "transfer-encoding: chunked") + // wireshark filter: (tcp.srcport == 80 || tcp.srcport == 8080) && tcp contains "HTTP/1." && (tcp contains + // "Transfer-Encoding: chunked" || tcp contains "Transfer-Encoding: chunked" || tcp contains "transfer-encoding: + // chunked") PTF_ASSERT_EQUAL(chunkedCount, 45); - // wireshark filter: (tcp.srcport == 80 || tcp.srcport == 8080) && tcp contains "HTTP/1." && tcp contains "Content-Encoding: gzip" + // wireshark filter: (tcp.srcport == 80 || tcp.srcport == 8080) && tcp contains "HTTP/1." && tcp contains + // "Content-Encoding: gzip" PTF_ASSERT_EQUAL(gzipCount, 148); // wireshark filter: http.content_length > 100000 PTF_ASSERT_EQUAL(bigResponses, 14); -} // TestHttpResponseParsing - - - +} // TestHttpResponseParsing PTF_TEST_CASE(TestPrintPacketAndLayers) { @@ -273,15 +276,14 @@ PTF_TEST_CASE(TestPrintPacketAndLayers) while (true) { index = referenceBufferAsString.find("\r\n", index); - if (index == std::string::npos) break; + if (index == std::string::npos) + break; referenceBufferAsString.replace(index, 2, "\n"); index += 1; } PTF_ASSERT_EQUAL(referenceBufferAsString, outputStream.str()); -} // TestPrintPacketAndLayers - - +} // TestPrintPacketAndLayers PTF_TEST_CASE(TestDnsParsing) { @@ -297,7 +299,7 @@ PTF_TEST_CASE(TestDnsParsing) int packetsContainingDnsAdditional = 0; int queriesWithNameGoogle = 0; - int queriesWithNameMozillaOrg = 0; //aus3.mozilla.org + int queriesWithNameMozillaOrg = 0; // aus3.mozilla.org int queriesWithTypeA = 0; int queriesWithTypeNotA = 0; int queriesWithClassIN = 0; @@ -334,7 +336,8 @@ PTF_TEST_CASE(TestDnsParsing) bool isTypeA = false; bool isClassIN = false; - for (pcpp::DnsQuery* query = dnsLayer->getFirstQuery(); query != nullptr; query = dnsLayer->getNextQuery(query)) + for (pcpp::DnsQuery* query = dnsLayer->getFirstQuery(); query != nullptr; + query = dnsLayer->getNextQuery(query)) { if (query->getDnsType() == pcpp::DNS_TYPE_A) isTypeA = true; @@ -361,7 +364,8 @@ PTF_TEST_CASE(TestDnsParsing) bool isTypePTR = false; bool isTtlLessThan30 = false; - for (pcpp::DnsResource* answer = dnsLayer->getFirstAnswer(); answer != nullptr; answer = dnsLayer->getNextAnswer(answer)) + for (pcpp::DnsResource* answer = dnsLayer->getFirstAnswer(); answer != nullptr; + answer = dnsLayer->getNextAnswer(answer)) { if (answer->getTTL() < 30) isTtlLessThan30 = true; @@ -388,7 +392,8 @@ PTF_TEST_CASE(TestDnsParsing) if (dnsLayer->getAuthority("Yaels-iPhone.local", true) != nullptr) authoritiesWithNameYaelPhone++; - for (pcpp::DnsResource* auth = dnsLayer->getFirstAuthority(); auth != nullptr; auth = dnsLayer->getNextAuthority(auth)) + for (pcpp::DnsResource* auth = dnsLayer->getFirstAuthority(); auth != nullptr; + auth = dnsLayer->getNextAuthority(auth)) { if (auth->getData()->toString() == "10.0.0.2") { @@ -405,12 +410,14 @@ PTF_TEST_CASE(TestDnsParsing) if (dnsLayer->getAdditionalRecord("", true) != nullptr) additionalWithEmptyName++; - if (dnsLayer->getAdditionalRecord("D.9.F.3.F.4.E.F.F.F.A.A.F.1.A.5.0.0.0.0.0.0.0.0.0.0.0.0.0.8.E.F.ip6.arpa", true) != nullptr) + if (dnsLayer->getAdditionalRecord( + "D.9.F.3.F.4.E.F.F.F.A.A.F.1.A.5.0.0.0.0.0.0.0.0.0.0.0.0.0.8.E.F.ip6.arpa", true) != nullptr) additionalWithLongUglyName++; bool isTypeNSEC = false; - for (pcpp::DnsResource* add = dnsLayer->getFirstAdditionalRecord(); add != nullptr; add = dnsLayer->getNextAdditionalRecord(add)) + for (pcpp::DnsResource* add = dnsLayer->getFirstAdditionalRecord(); add != nullptr; + add = dnsLayer->getNextAdditionalRecord(add)) { if (add->getDnsType() == pcpp::DNS_TYPE_NSEC) isTypeNSEC = true; @@ -461,8 +468,9 @@ PTF_TEST_CASE(TestDnsParsing) // wireshark filter: dns.count.add_rr > 0 and dns.resp.name == "" PTF_ASSERT_EQUAL(additionalWithEmptyName, 23); - // wireshark filter: dns.count.add_rr > 0 and dns.resp.name == D.9.F.3.F.4.E.F.F.F.A.A.F.1.A.5.0.0.0.0.0.0.0.0.0.0.0.0.0.8.E.F.ip6.arpa + // wireshark filter: dns.count.add_rr > 0 and dns.resp.name == + // D.9.F.3.F.4.E.F.F.F.A.A.F.1.A.5.0.0.0.0.0.0.0.0.0.0.0.0.0.8.E.F.ip6.arpa PTF_ASSERT_EQUAL(additionalWithLongUglyName, 12); // wireshark filter: dns.count.add_rr > 0 and dns.resp.type == 47 PTF_ASSERT_EQUAL(additionalWithTypeNSEC, 14); -} // TestDnsParsing +} // TestDnsParsing diff --git a/Tests/Pcap++Test/Tests/PfRingTests.cpp b/Tests/Pcap++Test/Tests/PfRingTests.cpp index b12828beda..1258ad8fac 100644 --- a/Tests/Pcap++Test/Tests/PfRingTests.cpp +++ b/Tests/Pcap++Test/Tests/PfRingTests.cpp @@ -5,12 +5,12 @@ #include #ifdef USE_PF_RING -#include "Logger.h" -#include "PacketUtils.h" -#include "IPv4Layer.h" -#include "PfRingDeviceList.h" -#include "PcapFileDevice.h" -#include "PcapLiveDeviceList.h" +# include "Logger.h" +# include "PacketUtils.h" +# include "IPv4Layer.h" +# include "PfRingDeviceList.h" +# include "PcapFileDevice.h" +# include "PcapLiveDeviceList.h" #endif extern PcapTestArgs PcapTestGlobalArgs; @@ -27,11 +27,20 @@ struct PfRingPacketData int UdpCount; std::unordered_map FlowKeys; - PfRingPacketData() : ThreadId(-1), PacketCount(0), EthCount(0), IpCount(0), TcpCount(0), UdpCount(0) {} - void clear() { ThreadId = -1; PacketCount = 0; EthCount = 0; IpCount = 0; TcpCount = 0; UdpCount = 0; FlowKeys.clear(); } + PfRingPacketData() : ThreadId(-1), PacketCount(0), EthCount(0), IpCount(0), TcpCount(0), UdpCount(0) + {} + void clear() + { + ThreadId = -1; + PacketCount = 0; + EthCount = 0; + IpCount = 0; + TcpCount = 0; + UdpCount = 0; + FlowKeys.clear(); + } }; - struct SetFilterInstruction { int Instruction; @@ -39,8 +48,8 @@ struct SetFilterInstruction int PacketCount; }; - -static void pfRingPacketsArrive(pcpp::RawPacket* packets, uint32_t numOfPackets, uint8_t threadId, pcpp::PfRingDevice* device, void* userCookie) +static void pfRingPacketsArrive(pcpp::RawPacket* packets, uint32_t numOfPackets, uint8_t threadId, + pcpp::PfRingDevice* device, void* userCookie) { PfRingPacketData* data = static_cast(userCookie); @@ -61,8 +70,8 @@ static void pfRingPacketsArrive(pcpp::RawPacket* packets, uint32_t numOfPackets, } } - -static void pfRingPacketsArriveMultiThread(pcpp::RawPacket* packets, uint32_t numOfPackets, uint8_t threadId, pcpp::PfRingDevice* device, void* userCookie) +static void pfRingPacketsArriveMultiThread(pcpp::RawPacket* packets, uint32_t numOfPackets, uint8_t threadId, + pcpp::PfRingDevice* device, void* userCookie) { PfRingPacketData* data = static_cast(userCookie); @@ -90,13 +99,13 @@ static void pfRingPacketsArriveMultiThread(pcpp::RawPacket* packets, uint32_t nu } } - -void pfRingPacketsArriveSetFilter(pcpp::RawPacket* packets, uint32_t numOfPackets, uint8_t threadId, pcpp::PfRingDevice* device, void* userCookie) +void pfRingPacketsArriveSetFilter(pcpp::RawPacket* packets, uint32_t numOfPackets, uint8_t threadId, + pcpp::PfRingDevice* device, void* userCookie) { SetFilterInstruction* instruction = static_cast(userCookie); - switch(instruction->Instruction) + switch (instruction->Instruction) { - case 1: //verify TCP packet + case 1: // verify TCP packet for (uint32_t i = 0; i < numOfPackets; i++) { pcpp::Packet packet(&packets[i]); @@ -108,7 +117,7 @@ void pfRingPacketsArriveSetFilter(pcpp::RawPacket* packets, uint32_t numOfPacket } break; - case 2: //verify IP filter + case 2: // verify IP filter pcpp::IPv4Address addr(instruction->Data); for (uint32_t i = 0; i < numOfPackets; i++) { @@ -142,7 +151,8 @@ int incSleep(int maxSleepTime, const PfRingPacketData& packetData) return totalSleepTime; } -int incSleepMultiThread(int maxSleepTime, PfRingPacketData packetData[], int totalNumOfCores, int numOfCoresInUse, pcpp::CoreMask coreMask) +int incSleepMultiThread(int maxSleepTime, PfRingPacketData packetData[], int totalNumOfCores, int numOfCoresInUse, + pcpp::CoreMask coreMask) { int totalSleepTime = 0; while (totalSleepTime < maxSleepTime) @@ -185,9 +195,6 @@ static pcpp::CoreMask TestPfRingMultiThreadCoreMask; #endif - - - PTF_TEST_CASE(TestPfRingDevice) { #ifdef USE_PF_RING @@ -195,7 +202,8 @@ PTF_TEST_CASE(TestPfRingDevice) pcpp::PfRingDeviceList& devList = pcpp::PfRingDeviceList::getInstance(); PTF_ASSERT_GREATER_THAN(devList.getPfRingDevicesList().size(), 0); PTF_ASSERT_NOT_EQUAL(devList.getPfRingVersion(), ""); - pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(pcapLiveDev); pcpp::PfRingDevice* dev = devList.getPfRingDeviceByName(pcapLiveDev->getName()); @@ -237,26 +245,24 @@ PTF_TEST_CASE(TestPfRingDevice) #else PTF_SKIP_TEST("PF_RING not configured"); #endif -} // TestPfRingDevice - - - +} // TestPfRingDevice PTF_TEST_CASE(TestPfRingDeviceSingleChannel) { #ifdef USE_PF_RING pcpp::PfRingDeviceList& devList = pcpp::PfRingDeviceList::getInstance(); - pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(pcapLiveDev); pcpp::PfRingDevice* dev = devList.getPfRingDeviceByName(pcapLiveDev->getName()); PTF_ASSERT_NOT_NULL(dev); PfRingPacketData packetData; pcpp::Logger::getInstance().suppressLogs(); - PTF_ASSERT_FALSE(dev->openSingleRxChannel(dev->getTotalNumOfRxChannels()+1)); + PTF_ASSERT_FALSE(dev->openSingleRxChannel(dev->getTotalNumOfRxChannels() + 1)); pcpp::Logger::getInstance().enableLogs(); - PTF_ASSERT_TRUE(dev->openSingleRxChannel(dev->getTotalNumOfRxChannels()-1)); + PTF_ASSERT_TRUE(dev->openSingleRxChannel(dev->getTotalNumOfRxChannels() - 1)); PTF_ASSERT_TRUE(dev->startCaptureSingleThread(pfRingPacketsArrive, &packetData)); int totalSleepTime = incSleep(10, packetData); dev->stopCapture(); @@ -281,22 +287,20 @@ PTF_TEST_CASE(TestPfRingDeviceSingleChannel) #else PTF_SKIP_TEST("PF_RING not configured"); #endif -} // TestPfRingDeviceSingleChannel - - - +} // TestPfRingDeviceSingleChannel PTF_TEST_CASE(TestPfRingDeviceMultiThread) { #ifdef USE_PF_RING pcpp::PfRingDeviceList& devList = pcpp::PfRingDeviceList::getInstance(); - pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(pcapLiveDev); pcpp::PfRingDevice* dev = devList.getPfRingDeviceByName(pcapLiveDev->getName()); PTF_ASSERT_NOT_NULL(dev); uint8_t numOfChannels = dev->getTotalNumOfRxChannels(); - PTF_ASSERT_TRUE(dev->openMultiRxChannels(numOfChannels*2.5, pcpp::PfRingDevice::PerFlow)); + PTF_ASSERT_TRUE(dev->openMultiRxChannels(numOfChannels * 2.5, pcpp::PfRingDevice::PerFlow)); DeviceTeardown devTeardown(dev); dev->close(); PTF_ASSERT_EQUAL(dev->getNumOfOpenedRxChannels(), 0); @@ -315,8 +319,10 @@ PTF_TEST_CASE(TestPfRingDeviceMultiThread) PTF_ASSERT_TRUE(dev->openMultiRxChannels((uint8_t)numOfCoresInUse, pcpp::PfRingDevice::PerFlow)); PfRingPacketData packetDataMultiThread[totalnumOfCores]; - PTF_ASSERT_TRUE(dev->startCaptureMultiThread(pfRingPacketsArriveMultiThread, packetDataMultiThread, TestPfRingMultiThreadCoreMask)); - int totalSleepTime = incSleepMultiThread(15, packetDataMultiThread, totalnumOfCores, numOfCoresInUse, TestPfRingMultiThreadCoreMask); + PTF_ASSERT_TRUE(dev->startCaptureMultiThread(pfRingPacketsArriveMultiThread, packetDataMultiThread, + TestPfRingMultiThreadCoreMask)); + int totalSleepTime = + incSleepMultiThread(15, packetDataMultiThread, totalnumOfCores, numOfCoresInUse, TestPfRingMultiThreadCoreMask); dev->stopCapture(); PTF_PRINT_VERBOSE("Total sleep time: " << totalSleepTime); pcpp::PfRingDevice::PfRingStats aggrStats; @@ -344,7 +350,7 @@ PTF_TEST_CASE(TestPfRingDeviceMultiThread) PTF_PRINT_VERBOSE("Packets captured: " << stats.recv); PTF_PRINT_VERBOSE("Packets dropped: " << stats.drop); PTF_PRINT_VERBOSE("Total flows: " << packetDataMultiThread[i].FlowKeys.size()); - for(const auto &iter : packetDataMultiThread[i].FlowKeys) + for (const auto& iter : packetDataMultiThread[i].FlowKeys) { PTF_PRINT_VERBOSE("Key=0x" << std::hex << iter.first << "; Value=" << std::dec << iter.second.size()); } @@ -359,10 +365,11 @@ PTF_TEST_CASE(TestPfRingDeviceMultiThread) for (int firstCoreId = 0; firstCoreId < totalnumOfCores; firstCoreId++) { - for (int secondCoreId = firstCoreId+1; secondCoreId < totalnumOfCores; secondCoreId++) + for (int secondCoreId = firstCoreId + 1; secondCoreId < totalnumOfCores; secondCoreId++) { - std::unordered_map > res; - intersectMaps(packetDataMultiThread[firstCoreId].FlowKeys, packetDataMultiThread[secondCoreId].FlowKeys, res); + std::unordered_map> res; + intersectMaps( + packetDataMultiThread[firstCoreId].FlowKeys, packetDataMultiThread[secondCoreId].FlowKeys, res); PTF_ASSERT_EQUAL(res.size(), 0); } @@ -374,11 +381,7 @@ PTF_TEST_CASE(TestPfRingDeviceMultiThread) #else PTF_SKIP_TEST("PF_RING not configured"); #endif -} // TestPfRingDeviceMultiThread (internal test case) - - - - +} // TestPfRingDeviceMultiThread (internal test case) PTF_TEST_CASE(TestPfRingMultiThreadAllCores) { @@ -400,10 +403,7 @@ PTF_TEST_CASE(TestPfRingMultiThreadAllCores) #else PTF_SKIP_TEST("PF_RING not configured"); #endif -} // TestPfRingMultiThreadAllCores - - - +} // TestPfRingMultiThreadAllCores PTF_TEST_CASE(TestPfRingMultiThreadSomeCores) { @@ -428,16 +428,14 @@ PTF_TEST_CASE(TestPfRingMultiThreadSomeCores) #else PTF_SKIP_TEST("PF_RING not configured"); #endif -} // TestPfRingMultiThreadSomeCores - - - +} // TestPfRingMultiThreadSomeCores PTF_TEST_CASE(TestPfRingSendPacket) { #ifdef USE_PF_RING pcpp::PfRingDeviceList& devList = pcpp::PfRingDeviceList::getInstance(); - pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(pcapLiveDev); pcpp::PfRingDevice* dev = devList.getPfRingDeviceByName(pcapLiveDev->getName()); PTF_ASSERT_NOT_NULL(dev); @@ -449,25 +447,25 @@ PTF_TEST_CASE(TestPfRingSendPacket) PTF_ASSERT_GREATER_THAN(dev->getMtu(), 0); uint16_t mtu = dev->getMtu(); - int buffLen = mtu+1; + int buffLen = mtu + 1; uint8_t buff[buffLen]; memset(buff, 0, buffLen); pcpp::RawPacket rawPacket; int packetsSent = 0; int packetsRead = 0; - while(fileReaderDev.getNextPacket(rawPacket)) + while (fileReaderDev.getNextPacket(rawPacket)) { packetsRead++; pcpp::RawPacket origRawPacket = rawPacket; - //send packet as RawPacket + // send packet as RawPacket PTF_ASSERT_TRUE(dev->sendPacket(rawPacket)); - //send packet as raw data + // send packet as raw data PTF_ASSERT_TRUE(dev->sendPacket(rawPacket.getRawData(), rawPacket.getRawDataLen())); - //send packet as parsed EthPacekt + // send packet as parsed EthPacekt pcpp::Packet packet(&rawPacket); PTF_ASSERT_TRUE(dev->sendPacket(packet)); @@ -483,7 +481,7 @@ PTF_TEST_CASE(TestPfRingSendPacket) // send some packets with single channel open PTF_ASSERT_TRUE(dev->openSingleRxChannel(0)); fileReaderDev.open(); - while(fileReaderDev.getNextPacket(rawPacket)) + while (fileReaderDev.getNextPacket(rawPacket)) { PTF_ASSERT_TRUE(dev->sendPacket(rawPacket)); } @@ -495,16 +493,14 @@ PTF_TEST_CASE(TestPfRingSendPacket) #else PTF_SKIP_TEST("PF_RING not configured"); #endif -} // TestPfRingSendPacket - - - +} // TestPfRingSendPacket PTF_TEST_CASE(TestPfRingSendPackets) { #ifdef USE_PF_RING pcpp::PfRingDeviceList& devList = pcpp::PfRingDeviceList::getInstance(); - pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(pcapLiveDev); pcpp::PfRingDevice* dev = devList.getPfRingDeviceByName(pcapLiveDev->getName()); PTF_ASSERT_NOT_NULL(dev); @@ -518,16 +514,16 @@ PTF_TEST_CASE(TestPfRingSendPackets) pcpp::PointerVector packetVec; const pcpp::Packet* packetArr[10000]; int packetsRead = 0; - while(fileReaderDev.getNextPacket(rawPacketArr[packetsRead])) + while (fileReaderDev.getNextPacket(rawPacketArr[packetsRead])) { packetVec.pushBack(new pcpp::Packet(&rawPacketArr[packetsRead])); packetsRead++; } - //send packets as RawPacket array + // send packets as RawPacket array int packetsSentAsRaw = dev->sendPackets(rawPacketArr, packetsRead); - //send packets as parsed EthPacekt array + // send packets as parsed EthPacekt array std::copy(packetVec.begin(), packetVec.end(), packetArr); int packetsSentAsParsed = dev->sendPackets(packetArr, packetsRead); @@ -540,16 +536,14 @@ PTF_TEST_CASE(TestPfRingSendPackets) #else PTF_SKIP_TEST("PF_RING not configured"); #endif -} // TestPfRingSendPackets - - - +} // TestPfRingSendPackets PTF_TEST_CASE(TestPfRingFilters) { #ifdef USE_PF_RING pcpp::PfRingDeviceList& devList = pcpp::PfRingDeviceList::getInstance(); - pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + pcpp::PcapLiveDevice* pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); PTF_ASSERT_NOT_NULL(pcapLiveDev); pcpp::PfRingDevice* dev = devList.getPfRingDeviceByName(pcapLiveDev->getName()); PTF_ASSERT_NOT_NULL(dev); @@ -566,7 +560,7 @@ PTF_TEST_CASE(TestPfRingFilters) PTF_ASSERT_TRUE(dev->setFilter(protocolFilter)); // verify TCP filter - SetFilterInstruction instruction = { 1, "", 0 }; // instruction #1: verify all packets are of type TCP + SetFilterInstruction instruction = { 1, "", 0 }; // instruction #1: verify all packets are of type TCP PTF_ASSERT_TRUE(dev->startCaptureSingleThread(pfRingPacketsArriveSetFilter, &instruction)); int totalSleepTime = incSleepSetFilter(10, instruction); dev->stopCapture(); diff --git a/Tests/Pcap++Test/Tests/RawSocketTests.cpp b/Tests/Pcap++Test/Tests/RawSocketTests.cpp index 3d77179ac5..34b8c24f57 100644 --- a/Tests/Pcap++Test/Tests/RawSocketTests.cpp +++ b/Tests/Pcap++Test/Tests/RawSocketTests.cpp @@ -54,7 +54,7 @@ PTF_TEST_CASE(TestRawSockets) rawSock.receivePackets(packetVec, 2, failedRecv); if (packetVec.size() > 0) { - PTF_PRINT_VERBOSE("Total wait time: " << 2*i); + PTF_PRINT_VERBOSE("Total wait time: " << 2 * i); break; } } @@ -158,4 +158,4 @@ PTF_TEST_CASE(TestRawSockets) PTF_ASSERT_FALSE(rawSock.sendPackets(packetVec)); pcpp::Logger::getInstance().enableLogs(); } -} // TestRawSockets +} // TestRawSockets diff --git a/Tests/Pcap++Test/Tests/SystemUtilsTests.cpp b/Tests/Pcap++Test/Tests/SystemUtilsTests.cpp index e871996d0f..599e59f2f9 100644 --- a/Tests/Pcap++Test/Tests/SystemUtilsTests.cpp +++ b/Tests/Pcap++Test/Tests/SystemUtilsTests.cpp @@ -2,7 +2,6 @@ #include "SystemUtils.h" #include - PTF_TEST_CASE(TestSystemCoreUtils) { auto numOfCores = pcpp::getNumOfCores(); @@ -11,10 +10,11 @@ PTF_TEST_CASE(TestSystemCoreUtils) std::bitset<32> bs(pcpp::getCoreMaskForAllMachineCores()); PTF_ASSERT_EQUAL(bs.count(), numOfCores); - auto coreVector = std::vector{pcpp::SystemCores::Core0, pcpp::SystemCores::Core2, pcpp::SystemCores::Core4}; + auto coreVector = + std::vector{ pcpp::SystemCores::Core0, pcpp::SystemCores::Core2, pcpp::SystemCores::Core4 }; PTF_ASSERT_EQUAL(pcpp::createCoreMaskFromCoreVector(coreVector), 0b10101); - auto coreIdVector = std::vector{1, 3, 5}; + auto coreIdVector = std::vector{ 1, 3, 5 }; PTF_ASSERT_EQUAL(pcpp::createCoreMaskFromCoreIds(coreIdVector), 0b101010); std::vector coreVector2; diff --git a/Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp b/Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp index 224375e2f5..f233a8cec3 100644 --- a/Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp +++ b/Tests/Pcap++Test/Tests/TcpReassemblyTests.cpp @@ -11,7 +11,6 @@ #include "PayloadLayer.h" #include "PcapFileDevice.h" - // ~~~~~~~~~~~~~~~~~~ // TcpReassemblyStats // ~~~~~~~~~~~~~~~~~~ @@ -28,12 +27,25 @@ struct TcpReassemblyStats size_t totalMissingBytes; pcpp::ConnectionData connData; - TcpReassemblyStats() { clear(); } + TcpReassemblyStats() + { + clear(); + } - void clear() { reassembledData = ""; numOfDataPackets = 0; curSide = -1; numOfMessagesFromSide[0] = 0; numOfMessagesFromSide[1] = 0; connectionsStarted = false; connectionsEnded = false; connectionsEndedManually = false; totalMissingBytes = 0;} + void clear() + { + reassembledData = ""; + numOfDataPackets = 0; + curSide = -1; + numOfMessagesFromSide[0] = 0; + numOfMessagesFromSide[1] = 0; + connectionsStarted = false; + connectionsEnded = false; + connectionsEndedManually = false; + totalMissingBytes = 0; + } }; - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // TcpReassemblyMultipleConnStats // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -46,21 +58,19 @@ struct TcpReassemblyMultipleConnStats Stats stats; FlowKeysList flowKeysList; - std::vectortimestamps; + std::vector timestamps; void clear() { stats.clear(); flowKeysList.clear(); } - }; - // ~~~~~~~~~~~~~~~~~~~~ // readFileIntoString() // ~~~~~~~~~~~~~~~~~~~~ -static std::string readFileIntoString(const std::string &fileName) +static std::string readFileIntoString(const std::string& fileName) { std::ifstream infile(fileName.c_str(), std::ios::binary); std::ostringstream ostrm; @@ -70,7 +80,6 @@ static std::string readFileIntoString(const std::string &fileName) return res; } - // ~~~~~~~~~~~~~~~~~~~~ // getPayloadLen() // ~~~~~~~~~~~~~~~~~~~~ @@ -87,17 +96,16 @@ static size_t getPayloadLen(pcpp::RawPacket& rawPacket) if (ipLayer == nullptr) throw std::runtime_error("IPv4 Layer not found"); - return be16toh(ipLayer->getIPv4Header()->totalLength)-ipLayer->getHeaderLen()-tcpLayer->getHeaderLen(); + return be16toh(ipLayer->getIPv4Header()->totalLength) - ipLayer->getHeaderLen() - tcpLayer->getHeaderLen(); } - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // tcpReassemblyMsgReadyCallback() // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static void tcpReassemblyMsgReadyCallback(int8_t sideIndex, const pcpp::TcpStreamData& tcpData, void* userCookie) { - TcpReassemblyMultipleConnStats::Stats &stats = ((TcpReassemblyMultipleConnStats*)userCookie)->stats; + TcpReassemblyMultipleConnStats::Stats& stats = ((TcpReassemblyMultipleConnStats*)userCookie)->stats; TcpReassemblyMultipleConnStats::Stats::iterator iter = stats.find(tcpData.getConnectionData().flowKey); if (iter == stats.end()) @@ -114,19 +122,18 @@ static void tcpReassemblyMsgReadyCallback(int8_t sideIndex, const pcpp::TcpStrea iter->second.curSide = sideIndex; } - ((TcpReassemblyMultipleConnStats *)userCookie)->timestamps.push_back(tcpData.getTimeStamp()); + ((TcpReassemblyMultipleConnStats*)userCookie)->timestamps.push_back(tcpData.getTimeStamp()); iter->second.numOfDataPackets++; iter->second.reassembledData += std::string((char*)tcpData.getData(), tcpData.getDataLength()); } - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // tcpReassemblyConnectionStartCallback() // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static void tcpReassemblyConnectionStartCallback(const pcpp::ConnectionData& connectionData, void* userCookie) { - TcpReassemblyMultipleConnStats::Stats &stats = ((TcpReassemblyMultipleConnStats*)userCookie)->stats; + TcpReassemblyMultipleConnStats::Stats& stats = ((TcpReassemblyMultipleConnStats*)userCookie)->stats; TcpReassemblyMultipleConnStats::Stats::iterator iter = stats.find(connectionData.flowKey); if (iter == stats.end()) @@ -135,22 +142,23 @@ static void tcpReassemblyConnectionStartCallback(const pcpp::ConnectionData& con iter = stats.find(connectionData.flowKey); } - TcpReassemblyMultipleConnStats::FlowKeysList &flowKeys = ((TcpReassemblyMultipleConnStats *)userCookie)->flowKeysList; - if(std::find(flowKeys.begin(), flowKeys.end(), connectionData.flowKey) == flowKeys.end()) + TcpReassemblyMultipleConnStats::FlowKeysList& flowKeys = + ((TcpReassemblyMultipleConnStats*)userCookie)->flowKeysList; + if (std::find(flowKeys.begin(), flowKeys.end(), connectionData.flowKey) == flowKeys.end()) flowKeys.push_back(connectionData.flowKey); iter->second.connectionsStarted = true; iter->second.connData = connectionData; } - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // tcpReassemblyConnectionEndCallback() // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -static void tcpReassemblyConnectionEndCallback(const pcpp::ConnectionData& connectionData, pcpp::TcpReassembly::ConnectionEndReason reason, void* userCookie) +static void tcpReassemblyConnectionEndCallback(const pcpp::ConnectionData& connectionData, + pcpp::TcpReassembly::ConnectionEndReason reason, void* userCookie) { - TcpReassemblyMultipleConnStats::Stats &stats = ((TcpReassemblyMultipleConnStats*)userCookie)->stats; + TcpReassemblyMultipleConnStats::Stats& stats = ((TcpReassemblyMultipleConnStats*)userCookie)->stats; TcpReassemblyMultipleConnStats::Stats::iterator iter = stats.find(connectionData.flowKey); if (iter == stats.end()) @@ -159,8 +167,9 @@ static void tcpReassemblyConnectionEndCallback(const pcpp::ConnectionData& conne iter = stats.find(connectionData.flowKey); } - TcpReassemblyMultipleConnStats::FlowKeysList &flowKeys = ((TcpReassemblyMultipleConnStats *)userCookie)->flowKeysList; - if(std::find(flowKeys.begin(), flowKeys.end(), connectionData.flowKey) == flowKeys.end()) + TcpReassemblyMultipleConnStats::FlowKeysList& flowKeys = + ((TcpReassemblyMultipleConnStats*)userCookie)->flowKeysList; + if (std::find(flowKeys.begin(), flowKeys.end(), connectionData.flowKey) == flowKeys.end()) flowKeys.push_back(connectionData.flowKey); if (reason == pcpp::TcpReassembly::TcpReassemblyConnectionClosedManually) @@ -169,17 +178,19 @@ static void tcpReassemblyConnectionEndCallback(const pcpp::ConnectionData& conne iter->second.connectionsEnded = true; } - // ~~~~~~~~~~~~~~~~~~~ // tcpReassemblyTest() // ~~~~~~~~~~~~~~~~~~~ -static bool tcpReassemblyTest(const std::vector& packetStream, TcpReassemblyMultipleConnStats& results, bool monitorOpenCloseConns, bool closeConnsManually) +static bool tcpReassemblyTest(const std::vector& packetStream, TcpReassemblyMultipleConnStats& results, + bool monitorOpenCloseConns, bool closeConnsManually) { pcpp::TcpReassembly* tcpReassembly = nullptr; if (monitorOpenCloseConns) - tcpReassembly = new pcpp::TcpReassembly(tcpReassemblyMsgReadyCallback, &results, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback); + tcpReassembly = + new pcpp::TcpReassembly(tcpReassemblyMsgReadyCallback, &results, tcpReassemblyConnectionStartCallback, + tcpReassemblyConnectionEndCallback); else tcpReassembly = new pcpp::TcpReassembly(tcpReassemblyMsgReadyCallback, &results); @@ -189,7 +200,8 @@ static bool tcpReassemblyTest(const std::vector& packetStream, tcpReassembly->reassemblePacket(packet); } - //for(TcpReassemblyMultipleConnStats::Stats::iterator iter = results.stats.begin(); iter != results.stats.end(); iter++) + // for(TcpReassemblyMultipleConnStats::Stats::iterator iter = results.stats.begin(); iter != results.stats.end(); + // iter++) //{ // // replace \r\n with \n // size_t index = 0; @@ -200,7 +212,7 @@ static bool tcpReassemblyTest(const std::vector& packetStream, // iter->second.reassembledData.replace(index, 2, "\n"); // index += 1; // } - //} + // } if (closeConnsManually) tcpReassembly->closeAllConnections(); @@ -210,7 +222,6 @@ static bool tcpReassemblyTest(const std::vector& packetStream, return true; } - // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // tcpReassemblyAddRetransmissions() // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -227,21 +238,22 @@ static pcpp::RawPacket tcpReassemblyAddRetransmissions(pcpp::RawPacket rawPacket if (ipLayer == nullptr) throw std::runtime_error("IPv4 Layer not found"); - int tcpPayloadSize = be16toh(ipLayer->getIPv4Header()->totalLength)-ipLayer->getHeaderLen()-tcpLayer->getHeaderLen(); + int tcpPayloadSize = + be16toh(ipLayer->getIPv4Header()->totalLength) - ipLayer->getHeaderLen() - tcpLayer->getHeaderLen(); if (numOfBytes <= 0) - numOfBytes = tcpPayloadSize-beginning; + numOfBytes = tcpPayloadSize - beginning; uint8_t* newPayload = new uint8_t[numOfBytes]; if (beginning + numOfBytes <= tcpPayloadSize) { - memcpy(newPayload, tcpLayer->getLayerPayload()+beginning, numOfBytes); + memcpy(newPayload, tcpLayer->getLayerPayload() + beginning, numOfBytes); } else { - int bytesToCopy = tcpPayloadSize-beginning; - memcpy(newPayload, tcpLayer->getLayerPayload()+beginning, bytesToCopy); + int bytesToCopy = tcpPayloadSize - beginning; + memcpy(newPayload, tcpLayer->getLayerPayload() + beginning, bytesToCopy); for (int i = bytesToCopy; i < numOfBytes; i++) { newPayload[i] = '*'; @@ -259,20 +271,17 @@ static pcpp::RawPacket tcpReassemblyAddRetransmissions(pcpp::RawPacket rawPacket packet.computeCalculateFields(); - delete [] newPayload; + delete[] newPayload; return *(packet.getRawPacket()); } - - // ~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~ // Test Cases start here // ~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~ - PTF_TEST_CASE(TestTcpReassemblySanity) { std::string errMsg; @@ -283,7 +292,7 @@ PTF_TEST_CASE(TestTcpReassemblySanity) TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 19); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); @@ -302,9 +311,7 @@ PTF_TEST_CASE(TestTcpReassemblySanity) std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); -} // TestTcpReassemblySanity - - +} // TestTcpReassemblySanity PTF_TEST_CASE(TestTcpReassemblyRetran) { @@ -336,16 +343,16 @@ PTF_TEST_CASE(TestTcpReassemblyRetran) TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, false, true); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 21); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 2); - std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_retransmission_output.txt")); + std::string expectedReassemblyData = + readFileIntoString(std::string("PcapExamples/one_tcp_stream_retransmission_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); -} // TestTcpReassemblyRetran - +} // TestTcpReassemblyRetran PTF_TEST_CASE(TestTcpReassemblyMissingData) { @@ -376,21 +383,21 @@ PTF_TEST_CASE(TestTcpReassemblyMissingData) TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, false, true); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.begin()->second.totalMissingBytes, expectedLoss); PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 17); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[1], 2); - std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_missing_data_output.txt")); + std::string expectedReassemblyData = + readFileIntoString(std::string("PcapExamples/one_tcp_stream_missing_data_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); packetStream.clear(); tcpReassemblyResults.clear(); expectedReassemblyData.clear(); - // test flow without SYN packet PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream.pcap", packetStream, errMsg)); @@ -407,9 +414,7 @@ PTF_TEST_CASE(TestTcpReassemblyMissingData) expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); -} // TestTcpReassemblyMissingData - - +} // TestTcpReassemblyMissingData PTF_TEST_CASE(TestTcpReassemblyOutOfOrder) { @@ -437,7 +442,7 @@ PTF_TEST_CASE(TestTcpReassemblyOutOfOrder) TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 19); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); @@ -446,14 +451,14 @@ PTF_TEST_CASE(TestTcpReassemblyOutOfOrder) PTF_ASSERT_FALSE(stats.begin()->second.connectionsEnded); PTF_ASSERT_TRUE(stats.begin()->second.connectionsEndedManually); - std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_out_of_order_output.txt")); + std::string expectedReassemblyData = + readFileIntoString(std::string("PcapExamples/one_tcp_stream_out_of_order_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); packetStream.clear(); tcpReassemblyResults.clear(); expectedReassemblyData.clear(); - // test out-of-order + missing data PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream.pcap", packetStream, errMsg)); @@ -481,9 +486,7 @@ PTF_TEST_CASE(TestTcpReassemblyOutOfOrder) expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_missing_data_output_ooo.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); -} // TestTcpReassemblyOutOfOrder - - +} // TestTcpReassemblyOutOfOrder PTF_TEST_CASE(TestTcpReassemblyWithFIN_RST) { @@ -496,7 +499,7 @@ PTF_TEST_CASE(TestTcpReassemblyWithFIN_RST) PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_http_stream_fin.pcap", packetStream, errMsg)); tcpReassemblyTest(packetStream, tcpReassemblyResults, true, false); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 5); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 1); @@ -545,7 +548,7 @@ PTF_TEST_CASE(TestTcpReassemblyWithFIN_RST) tcpReassemblyResults.clear(); expectedReassemblyData.clear(); - //test fin packet in end of connection that has also data + // test fin packet in end of connection that has also data PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_http_stream_fin2.pcap", packetStream, errMsg)); tcpReassemblyTest(packetStream, tcpReassemblyResults, true, false); @@ -582,9 +585,7 @@ PTF_TEST_CASE(TestTcpReassemblyWithFIN_RST) PTF_ASSERT_FALSE(stats.begin()->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_http_stream_fin2_output2.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); -} // TestTcpReassemblyWithFIN_RST - - +} // TestTcpReassemblyWithFIN_RST PTF_TEST_CASE(TestTcpReassemblyMalformedPkts) { @@ -604,7 +605,7 @@ PTF_TEST_CASE(TestTcpReassemblyMalformedPkts) tcpReassemblyTest(packetStream, tcpReassemblyResults, true, false); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 6); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 1); @@ -614,9 +615,7 @@ PTF_TEST_CASE(TestTcpReassemblyMalformedPkts) PTF_ASSERT_FALSE(stats.begin()->second.connectionsEndedManually); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_http_stream_fin2_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); -} // TestTcpReassemblyMalformedPkts - - +} // TestTcpReassemblyMalformedPkts PTF_TEST_CASE(TestTcpReassemblyMultipleConns) { @@ -624,7 +623,8 @@ PTF_TEST_CASE(TestTcpReassemblyMultipleConns) std::string errMsg; std::string expectedReassemblyData; - pcpp::TcpReassembly tcpReassembly(tcpReassemblyMsgReadyCallback, &results, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback); + pcpp::TcpReassembly tcpReassembly(tcpReassemblyMsgReadyCallback, &results, tcpReassemblyConnectionStartCallback, + tcpReassemblyConnectionEndCallback); std::vector packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/three_http_streams.pcap", packetStream, errMsg)); @@ -636,32 +636,19 @@ PTF_TEST_CASE(TestTcpReassemblyMultipleConns) packetStream.erase(packetStream.begin() + 14); pcpp::TcpReassembly::ReassemblyStatus expectedStatuses[26] = { - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::Ignore_PacketWithNoData, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::Ignore_PacketWithNoData, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::Ignore_PacketWithNoData, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::Ignore_PacketWithNoData, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::FIN_RSTWithNoData, - pcpp::TcpReassembly::Ignore_PacketWithNoData, - pcpp::TcpReassembly::FIN_RSTWithNoData, - pcpp::TcpReassembly::Ignore_PacketWithNoData, - pcpp::TcpReassembly::Ignore_PacketWithNoData, - pcpp::TcpReassembly::TcpMessageHandled, - pcpp::TcpReassembly::Ignore_PacketWithNoData, - pcpp::TcpReassembly::FIN_RSTWithNoData, - pcpp::TcpReassembly::FIN_RSTWithNoData, - pcpp::TcpReassembly::Ignore_PacketWithNoData, - pcpp::TcpReassembly::Ignore_PacketWithNoData, + pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::TcpMessageHandled, + pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::TcpMessageHandled, + pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::TcpMessageHandled, + pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::Ignore_PacketWithNoData, + pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::TcpMessageHandled, + pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::TcpMessageHandled, + pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::Ignore_PacketWithNoData, + pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::FIN_RSTWithNoData, + pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::FIN_RSTWithNoData, + pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::Ignore_PacketWithNoData, + pcpp::TcpReassembly::TcpMessageHandled, pcpp::TcpReassembly::Ignore_PacketWithNoData, + pcpp::TcpReassembly::FIN_RSTWithNoData, pcpp::TcpReassembly::FIN_RSTWithNoData, + pcpp::TcpReassembly::Ignore_PacketWithNoData, pcpp::TcpReassembly::Ignore_PacketWithNoData, }; int statusIndex = 0; @@ -673,7 +660,7 @@ PTF_TEST_CASE(TestTcpReassemblyMultipleConns) PTF_ASSERT_EQUAL(status, expectedStatuses[statusIndex++], enum); } - TcpReassemblyMultipleConnStats::Stats &stats = results.stats; + TcpReassemblyMultipleConnStats::Stats& stats = results.stats; PTF_ASSERT_EQUAL(stats.size(), 3); PTF_ASSERT_EQUAL(results.flowKeysList.size(), 3); @@ -710,15 +697,17 @@ PTF_TEST_CASE(TestTcpReassemblyMultipleConns) expectedReassemblyData = readFileIntoString(std::string("PcapExamples/three_http_streams_conn_3_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, iter->second.reassembledData); - // test getConnectionInformation and isConnectionOpen - const pcpp::TcpReassembly::ConnectionInfoList &managedConnections = tcpReassembly.getConnectionInformation(); + const pcpp::TcpReassembly::ConnectionInfoList& managedConnections = tcpReassembly.getConnectionInformation(); PTF_ASSERT_EQUAL(managedConnections.size(), 3); - pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn1 = managedConnections.find(results.flowKeysList[0]); - pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn2 = managedConnections.find(results.flowKeysList[1]); - pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn3 = managedConnections.find(results.flowKeysList[2]); + pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn1 = + managedConnections.find(results.flowKeysList[0]); + pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn2 = + managedConnections.find(results.flowKeysList[1]); + pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn3 = + managedConnections.find(results.flowKeysList[2]); PTF_ASSERT_TRUE(iterConn1 != managedConnections.end()); PTF_ASSERT_TRUE(iterConn2 != managedConnections.end()); PTF_ASSERT_TRUE(iterConn3 != managedConnections.end()); @@ -726,7 +715,7 @@ PTF_TEST_CASE(TestTcpReassemblyMultipleConns) PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn2->second), 0); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn3->second), 0); - //test Connection Information data + // test Connection Information data pcpp::IPv4Address expectedSrcIP("172.16.133.132"); pcpp::IPv4Address expectedDstIP("98.139.161.29"); PTF_ASSERT_EQUAL(iterConn1->second.srcIP, expectedSrcIP); @@ -744,14 +733,12 @@ PTF_TEST_CASE(TestTcpReassemblyMultipleConns) dummyConn.flowKey = 0x12345678; PTF_ASSERT_LOWER_THAN(tcpReassembly.isConnectionOpen(dummyConn), 0); - // close flow manually and verify it's closed tcpReassembly.closeConnection(iter->first); PTF_ASSERT_FALSE(iter->second.connectionsEnded); PTF_ASSERT_TRUE(iter->second.connectionsEndedManually); - // now send FIN packets of conn 3 and verify they are ignored pcpp::TcpReassembly::ReassemblyStatus status = tcpReassembly.reassemblePacket(&finPacket1); @@ -761,9 +748,7 @@ PTF_TEST_CASE(TestTcpReassemblyMultipleConns) PTF_ASSERT_FALSE(iter->second.connectionsEnded); PTF_ASSERT_TRUE(iter->second.connectionsEndedManually); -} // TestTcpReassemblyMultipleConns - - +} // TestTcpReassemblyMultipleConns PTF_TEST_CASE(TestTcpReassemblyIPv6) { @@ -775,7 +760,7 @@ PTF_TEST_CASE(TestTcpReassemblyIPv6) TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 10); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 3); @@ -794,9 +779,7 @@ PTF_TEST_CASE(TestTcpReassemblyIPv6) std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_ipv6_http_stream.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); -} // TestTcpReassemblyIPv6 - - +} // TestTcpReassemblyIPv6 PTF_TEST_CASE(TestTcpReassemblyIPv6MultConns) { @@ -809,7 +792,7 @@ PTF_TEST_CASE(TestTcpReassemblyIPv6MultConns) TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 4); TcpReassemblyMultipleConnStats::Stats::iterator iter = stats.begin(); @@ -885,9 +868,7 @@ PTF_TEST_CASE(TestTcpReassemblyIPv6MultConns) PTF_ASSERT_EQUAL(stats.begin()->second.connData.endTime.tv_usec, 0); expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_ipv6_http_stream2.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, iter->second.reassembledData); -} // TestTcpReassemblyIPv6MultConns - - +} // TestTcpReassemblyIPv6MultConns PTF_TEST_CASE(TestTcpReassemblyIPv6_OOO) { @@ -909,7 +890,7 @@ PTF_TEST_CASE(TestTcpReassemblyIPv6_OOO) TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 10); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 3); @@ -928,9 +909,7 @@ PTF_TEST_CASE(TestTcpReassemblyIPv6_OOO) std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_ipv6_http_stream.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); -} // TestTcpReassemblyIPv6_OOO - - +} // TestTcpReassemblyIPv6_OOO PTF_TEST_CASE(TestTcpReassemblyCleanup) { @@ -938,7 +917,8 @@ PTF_TEST_CASE(TestTcpReassemblyCleanup) std::string errMsg; pcpp::TcpReassemblyConfiguration config(true, 2, 1); - pcpp::TcpReassembly tcpReassembly(tcpReassemblyMsgReadyCallback, &results, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback, config); + pcpp::TcpReassembly tcpReassembly(tcpReassemblyMsgReadyCallback, &results, tcpReassemblyConnectionStartCallback, + tcpReassemblyConnectionEndCallback, config); std::vector packetStream; PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/three_http_streams.pcap", packetStream, errMsg)); @@ -947,19 +927,23 @@ PTF_TEST_CASE(TestTcpReassemblyCleanup) packetStream.pop_back(); - for(auto iter : packetStream) + for (auto iter : packetStream) { pcpp::Packet packet(&iter); tcpReassembly.reassemblePacket(packet); } - pcpp::TcpReassembly::ConnectionInfoList managedConnections = tcpReassembly.getConnectionInformation(); // make a copy of list + pcpp::TcpReassembly::ConnectionInfoList managedConnections = + tcpReassembly.getConnectionInformation(); // make a copy of list PTF_ASSERT_EQUAL(managedConnections.size(), 3); PTF_ASSERT_EQUAL(results.flowKeysList.size(), 3); - pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn1 = managedConnections.find(results.flowKeysList[0]); - pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn2 = managedConnections.find(results.flowKeysList[1]); - pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn3 = managedConnections.find(results.flowKeysList[2]); + pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn1 = + managedConnections.find(results.flowKeysList[0]); + pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn2 = + managedConnections.find(results.flowKeysList[1]); + pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn3 = + managedConnections.find(results.flowKeysList[2]); PTF_ASSERT_TRUE(iterConn1 != managedConnections.end()); PTF_ASSERT_TRUE(iterConn2 != managedConnections.end()); PTF_ASSERT_TRUE(iterConn3 != managedConnections.end()); @@ -969,13 +953,13 @@ PTF_TEST_CASE(TestTcpReassemblyCleanup) pcpp::multiPlatformSleep(3); - tcpReassembly.reassemblePacket(&lastPacket); // automatic cleanup of 1 item + tcpReassembly.reassemblePacket(&lastPacket); // automatic cleanup of 1 item PTF_ASSERT_EQUAL(tcpReassembly.getConnectionInformation().size(), 2); - tcpReassembly.purgeClosedConnections(); // manually initiated cleanup of 1 item + tcpReassembly.purgeClosedConnections(); // manually initiated cleanup of 1 item PTF_ASSERT_EQUAL(tcpReassembly.getConnectionInformation().size(), 1); - tcpReassembly.purgeClosedConnections(0xFFFFFFFF); // manually initiated cleanup of all items + tcpReassembly.purgeClosedConnections(0xFFFFFFFF); // manually initiated cleanup of all items PTF_ASSERT_EQUAL(tcpReassembly.getConnectionInformation().size(), 0); const TcpReassemblyMultipleConnStats::FlowKeysList& flowKeys = results.flowKeysList; @@ -988,9 +972,7 @@ PTF_TEST_CASE(TestTcpReassemblyCleanup) PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn1->second), -1); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn2->second), -1); PTF_ASSERT_EQUAL(tcpReassembly.isConnectionOpen(iterConn3->second), -1); -} // TestTcpReassemblyCleanup - - +} // TestTcpReassemblyCleanup PTF_TEST_CASE(TestTcpReassemblyMaxOOOFrags) { @@ -999,14 +981,18 @@ PTF_TEST_CASE(TestTcpReassemblyMaxOOOFrags) std::string errMsg; pcpp::TcpReassemblyConfiguration config1(true, 5, 30); - pcpp::TcpReassemblyConfiguration config2(true, 5, 30, 5); // the fourth argument is the max allowed out-of-order fragments, so we only allow 5 - pcpp::TcpReassembly tcpReassembly1(tcpReassemblyMsgReadyCallback, &results1, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback, config1); - pcpp::TcpReassembly tcpReassembly2(tcpReassemblyMsgReadyCallback, &results2, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback, config2); + pcpp::TcpReassemblyConfiguration config2( + true, 5, 30, 5); // the fourth argument is the max allowed out-of-order fragments, so we only allow 5 + pcpp::TcpReassembly tcpReassembly1(tcpReassemblyMsgReadyCallback, &results1, tcpReassemblyConnectionStartCallback, + tcpReassemblyConnectionEndCallback, config1); + pcpp::TcpReassembly tcpReassembly2(tcpReassemblyMsgReadyCallback, &results2, tcpReassemblyConnectionStartCallback, + tcpReassemblyConnectionEndCallback, config2); std::vector packetStream; - PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/unidirectional_tcp_stream_with_missing_packet.pcap", packetStream, errMsg)); + PTF_ASSERT_TRUE( + readPcapIntoPacketVec("PcapExamples/unidirectional_tcp_stream_with_missing_packet.pcap", packetStream, errMsg)); - for(auto iter : packetStream) + for (auto iter : packetStream) { pcpp::Packet packet(&iter); tcpReassembly1.reassemblePacket(packet); @@ -1014,20 +1000,25 @@ PTF_TEST_CASE(TestTcpReassemblyMaxOOOFrags) } pcpp::TcpReassembly::ConnectionInfoList managedConnections1 = tcpReassembly1.getConnectionInformation(); - pcpp::TcpReassembly::ConnectionInfoList managedConnections2 = tcpReassembly2.getConnectionInformation(); // make a copy of list + pcpp::TcpReassembly::ConnectionInfoList managedConnections2 = + tcpReassembly2.getConnectionInformation(); // make a copy of list PTF_ASSERT_EQUAL(managedConnections1.size(), 1); PTF_ASSERT_EQUAL(managedConnections2.size(), 1); PTF_ASSERT_EQUAL(results1.flowKeysList.size(), 1); PTF_ASSERT_EQUAL(results2.flowKeysList.size(), 1); - pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn1 = managedConnections1.find(results1.flowKeysList[0]); - pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn2 = managedConnections2.find(results2.flowKeysList[0]); + pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn1 = + managedConnections1.find(results1.flowKeysList[0]); + pcpp::TcpReassembly::ConnectionInfoList::const_iterator iterConn2 = + managedConnections2.find(results2.flowKeysList[0]); PTF_ASSERT_TRUE(iterConn1 != managedConnections1.end()); PTF_ASSERT_TRUE(iterConn2 != managedConnections2.end()); PTF_ASSERT_EQUAL(tcpReassembly1.isConnectionOpen(iterConn1->second), 1); PTF_ASSERT_EQUAL(tcpReassembly2.isConnectionOpen(iterConn2->second), 1); - PTF_ASSERT_EQUAL(results1.stats.begin()->second.numOfDataPackets, 1); // The second data packet is incomplete so we stopped at one - PTF_ASSERT_EQUAL(results2.stats.begin()->second.numOfDataPackets, 7); // We hit the fragment limit so skipped the missing fragment and continued to the end + PTF_ASSERT_EQUAL(results1.stats.begin()->second.numOfDataPackets, + 1); // The second data packet is incomplete so we stopped at one + PTF_ASSERT_EQUAL(results2.stats.begin()->second.numOfDataPackets, + 7); // We hit the fragment limit so skipped the missing fragment and continued to the end // Close the connections, forcing cleanup tcpReassembly1.closeAllConnections(); @@ -1036,9 +1027,7 @@ PTF_TEST_CASE(TestTcpReassemblyMaxOOOFrags) // Everything should be processed now PTF_ASSERT_EQUAL(results1.stats.begin()->second.numOfDataPackets, 7); PTF_ASSERT_EQUAL(results2.stats.begin()->second.numOfDataPackets, 7); -} // TestTcpReassemblyCleanup - - +} // TestTcpReassemblyCleanup PTF_TEST_CASE(TestTcpReassemblyMaxSeq) { @@ -1050,7 +1039,7 @@ PTF_TEST_CASE(TestTcpReassemblyMaxSeq) TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; PTF_ASSERT_EQUAL(stats.size(), 1); PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 19); PTF_ASSERT_EQUAL(stats.begin()->second.numOfMessagesFromSide[0], 2); @@ -1069,9 +1058,9 @@ PTF_TEST_CASE(TestTcpReassemblyMaxSeq) std::string expectedReassemblyData = readFileIntoString(std::string("PcapExamples/one_tcp_stream_output.txt")); PTF_ASSERT_EQUAL(expectedReassemblyData, stats.begin()->second.reassembledData); -} //TestTcpReassemblyMaxSeq +} // TestTcpReassemblyMaxSeq -PTF_TEST_CASE(TestTcpReassemblyDisableOOOCleanup) // TestTcpReassemblyDisableBaseOutOfOrderBufferCleanupCondition +PTF_TEST_CASE(TestTcpReassemblyDisableOOOCleanup) // TestTcpReassemblyDisableBaseOutOfOrderBufferCleanupCondition { std::string errMsg; std::vector packetStream; @@ -1079,8 +1068,10 @@ PTF_TEST_CASE(TestTcpReassemblyDisableOOOCleanup) // TestTcpReassemblyDisableBas TcpReassemblyMultipleConnStats results2; pcpp::TcpReassemblyConfiguration config1(true, 5, 30, 20, true); pcpp::TcpReassemblyConfiguration config2(true, 5, 30, 20, false); - pcpp::TcpReassembly tcpReassembly1(tcpReassemblyMsgReadyCallback, &results1, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback, config1); - pcpp::TcpReassembly tcpReassembly2(tcpReassemblyMsgReadyCallback, &results2, tcpReassemblyConnectionStartCallback, tcpReassemblyConnectionEndCallback, config2); + pcpp::TcpReassembly tcpReassembly1(tcpReassemblyMsgReadyCallback, &results1, tcpReassemblyConnectionStartCallback, + tcpReassemblyConnectionEndCallback, config1); + pcpp::TcpReassembly tcpReassembly2(tcpReassemblyMsgReadyCallback, &results2, tcpReassemblyConnectionStartCallback, + tcpReassemblyConnectionEndCallback, config2); PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/one_tcp_stream.pcap", packetStream, errMsg)); // unserting a data packet from reverse direction b/w swap 2 consequent data packets @@ -1098,8 +1089,8 @@ PTF_TEST_CASE(TestTcpReassemblyDisableOOOCleanup) // TestTcpReassemblyDisableBas tcpReassembly1.closeAllConnections(); tcpReassembly2.closeAllConnections(); - TcpReassemblyMultipleConnStats::Stats &stats1 = results1.stats; - TcpReassemblyMultipleConnStats::Stats &stats2 = results2.stats; + TcpReassemblyMultipleConnStats::Stats& stats1 = results1.stats; + TcpReassemblyMultipleConnStats::Stats& stats2 = results2.stats; PTF_ASSERT_EQUAL(stats1.size(), 1); PTF_ASSERT_EQUAL(stats2.size(), 1); PTF_ASSERT_EQUAL(stats1.begin()->second.numOfDataPackets, 18); @@ -1107,31 +1098,33 @@ PTF_TEST_CASE(TestTcpReassemblyDisableOOOCleanup) // TestTcpReassemblyDisableBas packetStream.clear(); tcpReassemblyResults.clear(); -} // TestTcpReassemblyDisableOOOCleanup +} // TestTcpReassemblyDisableOOOCleanup PTF_TEST_CASE(TestTcpReassemblyTimeStamps) { std::string errMsg; std::vector packetStream; - PTF_ASSERT_TRUE(readPcapIntoPacketVec("PcapExamples/unidirectional_tcp_stream_with_missing_packet.pcap", packetStream, errMsg)); + PTF_ASSERT_TRUE( + readPcapIntoPacketVec("PcapExamples/unidirectional_tcp_stream_with_missing_packet.pcap", packetStream, errMsg)); TcpReassemblyMultipleConnStats tcpReassemblyResults; tcpReassemblyTest(packetStream, tcpReassemblyResults, true, true); - TcpReassemblyMultipleConnStats::Stats &stats = tcpReassemblyResults.stats; - PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets,7); + TcpReassemblyMultipleConnStats::Stats& stats = tcpReassemblyResults.stats; + PTF_ASSERT_EQUAL(stats.begin()->second.numOfDataPackets, 7); std::ifstream expectedOutput("PcapExamples/timestamp_output.txt"); - for(long unsigned int i = 0;i>expected; - const int expUsec = std::stoll(expected)%1000000; - const int expSec = std::stoll(expected)/1000000; - PTF_ASSERT_EQUAL(t.tv_usec,expUsec); + expectedOutput >> expected; + const int expUsec = std::stoll(expected) % 1000000; + const int expSec = std::stoll(expected) / 1000000; + PTF_ASSERT_EQUAL(t.tv_usec, expUsec); PTF_ASSERT_EQUAL(t.tv_sec, expSec); } expectedOutput.close(); packetStream.clear(); tcpReassemblyResults.clear(); -} // TestTcpReassemblyTimeStamps +} // TestTcpReassemblyTimeStamps diff --git a/Tests/Pcap++Test/Tests/XdpTests.cpp b/Tests/Pcap++Test/Tests/XdpTests.cpp index 30c9cf4042..9ea5dfeb21 100644 --- a/Tests/Pcap++Test/Tests/XdpTests.cpp +++ b/Tests/Pcap++Test/Tests/XdpTests.cpp @@ -6,7 +6,6 @@ #include "Packet.h" #include "Logger.h" - extern PcapTestArgs PcapTestGlobalArgs; #ifdef USE_XDP @@ -17,34 +16,27 @@ struct XdpPacketData int byteCount; uint64_t latestTimestamp; - XdpPacketData() : packetCount(0), byteCount(0), latestTimestamp(0) {} + XdpPacketData() : packetCount(0), byteCount(0), latestTimestamp(0) + {} }; bool assertConfig(const pcpp::XdpDevice::XdpDeviceConfiguration* config, - const pcpp::XdpDevice::XdpDeviceConfiguration::AttachMode expectedAttachMode, - const uint16_t expectedUmemNumFrames, - const uint16_t expectedUmemFrameSize, - const uint32_t expectedFillRingSize, - const uint32_t expectedCompletionRingSize, - const uint32_t expectedRxSize, - const uint32_t expectedTxSize, - const uint16_t expectedRxTxBatchSize) + const pcpp::XdpDevice::XdpDeviceConfiguration::AttachMode expectedAttachMode, + const uint16_t expectedUmemNumFrames, const uint16_t expectedUmemFrameSize, + const uint32_t expectedFillRingSize, const uint32_t expectedCompletionRingSize, + const uint32_t expectedRxSize, const uint32_t expectedTxSize, const uint16_t expectedRxTxBatchSize) { - return ( - config != nullptr && - config->attachMode == expectedAttachMode && - config->umemNumFrames == expectedUmemNumFrames && - config->umemFrameSize == expectedUmemFrameSize && - config->fillRingSize == expectedFillRingSize && - config->completionRingSize == expectedCompletionRingSize && - config->rxSize == expectedRxSize && - config->txSize == expectedTxSize && - config->rxTxBatchSize == expectedRxTxBatchSize); + return (config != nullptr && config->attachMode == expectedAttachMode && + config->umemNumFrames == expectedUmemNumFrames && config->umemFrameSize == expectedUmemFrameSize && + config->fillRingSize == expectedFillRingSize && config->completionRingSize == expectedCompletionRingSize && + config->rxSize == expectedRxSize && config->txSize == expectedTxSize && + config->rxTxBatchSize == expectedRxTxBatchSize); } std::string getDeviceName() { - auto pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); + auto pcapLiveDev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp( + PcapTestGlobalArgs.ipToSendReceivePackets.c_str()); if (pcapLiveDev) { return pcapLiveDev->getName(); @@ -53,8 +45,7 @@ std::string getDeviceName() return ""; } - -#endif // USE_XDP +#endif // USE_XDP PTF_TEST_CASE(TestXdpDeviceReceivePackets) { @@ -67,14 +58,13 @@ PTF_TEST_CASE(TestXdpDeviceReceivePackets) PTF_ASSERT_TRUE(device.open()); - PTF_ASSERT_TRUE( - assertConfig(device.getConfig(), - pcpp::XdpDevice::XdpDeviceConfiguration::AutoMode, - 4096, 4096,4096,2048,2048,2048,64)); + PTF_ASSERT_TRUE(assertConfig(device.getConfig(), pcpp::XdpDevice::XdpDeviceConfiguration::AutoMode, 4096, 4096, + 4096, 2048, 2048, 2048, 64)); XdpPacketData packetData; - auto onPacketsArrive = [](pcpp::RawPacket packets[], uint32_t packetCount, pcpp::XdpDevice* device, void* userCookie) -> void { + auto onPacketsArrive = [](pcpp::RawPacket packets[], uint32_t packetCount, pcpp::XdpDevice* device, + void* userCookie) -> void { auto packetData = static_cast(userCookie); for (uint32_t i = 0; i < packetCount; i++) @@ -83,7 +73,8 @@ PTF_TEST_CASE(TestXdpDeviceReceivePackets) { packetData->packetCount++; packetData->byteCount += packets[i].getRawDataLen(); - packetData->latestTimestamp = 1000*1000*1000*packets[i].getPacketTimeStamp().tv_sec + packets[i].getPacketTimeStamp().tv_nsec; + packetData->latestTimestamp = 1000 * 1000 * 1000 * packets[i].getPacketTimeStamp().tv_sec + + packets[i].getPacketTimeStamp().tv_nsec; } } @@ -96,7 +87,7 @@ PTF_TEST_CASE(TestXdpDeviceReceivePackets) timespec ts; clock_gettime(CLOCK_REALTIME, &ts); - uint64_t curTimestamp = 1000*1000*1000*ts.tv_sec + ts.tv_nsec; + uint64_t curTimestamp = 1000 * 1000 * 1000 * ts.tv_sec + ts.tv_nsec; PTF_ASSERT_TRUE(device.receivePackets(onPacketsArrive, &packetData, 20000)); @@ -134,8 +125,7 @@ PTF_TEST_CASE(TestXdpDeviceReceivePackets) #else PTF_SKIP_TEST("XDP not configured"); #endif -} // TestXdpDeviceReceivePackets - +} // TestXdpDeviceReceivePackets PTF_TEST_CASE(TestXdpDeviceSendPackets) { @@ -181,8 +171,7 @@ PTF_TEST_CASE(TestXdpDeviceSendPackets) #else PTF_SKIP_TEST("XDP not configured"); #endif -} // TestXdpDeviceSendPackets - +} // TestXdpDeviceSendPackets PTF_TEST_CASE(TestXdpDeviceNonDefaultConfig) { @@ -191,18 +180,17 @@ PTF_TEST_CASE(TestXdpDeviceNonDefaultConfig) PTF_ASSERT_FALSE(devName.empty()); pcpp::XdpDevice device(devName); - auto config = pcpp::XdpDevice::XdpDeviceConfiguration(pcpp::XdpDevice::XdpDeviceConfiguration::SkbMode, - 1000, 4096, 512, 512, 512, 512, 20); + auto config = pcpp::XdpDevice::XdpDeviceConfiguration(pcpp::XdpDevice::XdpDeviceConfiguration::SkbMode, 1000, 4096, + 512, 512, 512, 512, 20); PTF_ASSERT_TRUE(device.open(config)); - PTF_ASSERT_TRUE( - assertConfig(device.getConfig(), - pcpp::XdpDevice::XdpDeviceConfiguration::SkbMode, - 1000, 4096,512,512,512,512,20)); + PTF_ASSERT_TRUE(assertConfig(device.getConfig(), pcpp::XdpDevice::XdpDeviceConfiguration::SkbMode, 1000, 4096, 512, + 512, 512, 512, 20)); int numPackets = 0; - auto onPacketsArrive = [](pcpp::RawPacket packets[], uint32_t packetCount, pcpp::XdpDevice* device, void* userCookie) -> void { + auto onPacketsArrive = [](pcpp::RawPacket packets[], uint32_t packetCount, pcpp::XdpDevice* device, + void* userCookie) -> void { int* totalPacketCount = static_cast(userCookie); for (uint32_t i = 0; i < packetCount; i++) @@ -225,8 +213,7 @@ PTF_TEST_CASE(TestXdpDeviceNonDefaultConfig) #else PTF_SKIP_TEST("XDP not configured"); #endif -} // TestXdpDeviceNonDefaultConfig - +} // TestXdpDeviceNonDefaultConfig PTF_TEST_CASE(TestXdpDeviceInvalidConfig) { @@ -301,4 +288,4 @@ PTF_TEST_CASE(TestXdpDeviceInvalidConfig) #else PTF_SKIP_TEST("XDP not configured"); #endif -} // TestXdpDeviceInvalidConfig +} // TestXdpDeviceInvalidConfig diff --git a/Tests/Pcap++Test/main.cpp b/Tests/Pcap++Test/main.cpp index 98c9cda74a..e12d324b66 100644 --- a/Tests/Pcap++Test/main.cpp +++ b/Tests/Pcap++Test/main.cpp @@ -8,47 +8,46 @@ #include "Common/TestUtils.h" #include -static struct option PcapTestOptions[] = -{ - {"debug-mode", no_argument, nullptr, 'b'}, - {"use-ip", required_argument, nullptr, 'i'}, - {"remote-ip", required_argument, nullptr, 'r'}, - {"remote-port", required_argument, nullptr, 'p'}, - {"dpdk-port", required_argument, nullptr, 'd' }, - {"no-networking", no_argument, nullptr, 'n' }, - {"verbose", no_argument, nullptr, 'v' }, - {"mem-verbose", no_argument, nullptr, 'm' }, - {"kni-ip", no_argument, nullptr, 'k' }, - {"skip-mem-leak-check", no_argument, nullptr, 's' }, - {"include-tags", required_argument, nullptr, 't'}, - {"exclude-tags", required_argument, nullptr, 'x'}, - {"show-skipped-tests", no_argument, nullptr, 'w' }, - {"help", no_argument, nullptr, 'h'}, - {nullptr, 0, nullptr, 0} +static struct option PcapTestOptions[] = { + { "debug-mode", no_argument, nullptr, 'b' }, + { "use-ip", required_argument, nullptr, 'i' }, + { "remote-ip", required_argument, nullptr, 'r' }, + { "remote-port", required_argument, nullptr, 'p' }, + { "dpdk-port", required_argument, nullptr, 'd' }, + { "no-networking", no_argument, nullptr, 'n' }, + { "verbose", no_argument, nullptr, 'v' }, + { "mem-verbose", no_argument, nullptr, 'm' }, + { "kni-ip", no_argument, nullptr, 'k' }, + { "skip-mem-leak-check", no_argument, nullptr, 's' }, + { "include-tags", required_argument, nullptr, 't' }, + { "exclude-tags", required_argument, nullptr, 'x' }, + { "show-skipped-tests", no_argument, nullptr, 'w' }, + { "help", no_argument, nullptr, 'h' }, + { nullptr, 0, nullptr, 0 } }; - void printUsage() { - std::cout << "Usage: Pcap++Test -i ip_to_use | [-n] [-b] [-s] [-m] [-r remote_ip_addr] [-p remote_port] [-d dpdk_port] [-k ip_addr] [-t tags] [-w] [-h]\n\n" - << "Flags:\n" - << "-i --use-ip IP to use for sending and receiving packets\n" - << "-b --debug-mode Set log level to DEBUG\n" - << "-r --remote-ip IP of remote machine running rpcapd to test remote capture\n" - << "-p --remote-port Port of remote machine running rpcapd to test remote capture\n" - << "-d --dpdk-port The DPDK NIC port to test. Required if compiling with DPDK\n" - << "-n --no-networking Do not run tests that requires networking\n" - << "-v --verbose Run in verbose mode (emits more output in several tests)\n" - << "-m --mem-verbose Output information about each memory allocation and deallocation\n" - << "-s --skip-mem-leak-check Skip memory leak check\n" - << "-k --kni-ip IP address for KNI device tests to use must not be the same\n" - << " as any of existing network interfaces in your system.\n" - << " If this parameter is omitted KNI tests will be skipped. Must be an IPv4.\n" - << " For Linux systems only\n" - << "-t --include-tags A list of semicolon separated tags for tests to run\n" - << "-x --exclude-tags A list of semicolon separated tags for tests to exclude\n" - << "-w --show-skipped-tests Show tests that are skipped. Default is to hide them in tests results\n" - << "-h --help Display this help message and exit\n"; + std::cout << "Usage: Pcap++Test -i ip_to_use | [-n] [-b] [-s] [-m] [-r remote_ip_addr] [-p remote_port] [-d " + "dpdk_port] [-k ip_addr] [-t tags] [-w] [-h]\n\n" + << "Flags:\n" + << "-i --use-ip IP to use for sending and receiving packets\n" + << "-b --debug-mode Set log level to DEBUG\n" + << "-r --remote-ip IP of remote machine running rpcapd to test remote capture\n" + << "-p --remote-port Port of remote machine running rpcapd to test remote capture\n" + << "-d --dpdk-port The DPDK NIC port to test. Required if compiling with DPDK\n" + << "-n --no-networking Do not run tests that requires networking\n" + << "-v --verbose Run in verbose mode (emits more output in several tests)\n" + << "-m --mem-verbose Output information about each memory allocation and deallocation\n" + << "-s --skip-mem-leak-check Skip memory leak check\n" + << "-k --kni-ip IP address for KNI device tests to use must not be the same\n" + << " as any of existing network interfaces in your system.\n" + << " If this parameter is omitted KNI tests will be skipped. Must be an IPv4.\n" + << " For Linux systems only\n" + << "-t --include-tags A list of semicolon separated tags for tests to run\n" + << "-x --exclude-tags A list of semicolon separated tags for tests to exclude\n" + << "-w --show-skipped-tests Show tests that are skipped. Default is to hide them in tests results\n" + << "-h --help Display this help message and exit\n"; } PcapTestArgs PcapTestGlobalArgs; @@ -67,57 +66,57 @@ int main(int argc, char* argv[]) int optionIndex = 0; int opt = 0; - while((opt = getopt_long(argc, argv, "k:i:br:p:d:nvt:x:smw", PcapTestOptions, &optionIndex)) != -1) + while ((opt = getopt_long(argc, argv, "k:i:br:p:d:nvt:x:smw", PcapTestOptions, &optionIndex)) != -1) { switch (opt) { - case 0: - break; - case 'k': - PcapTestGlobalArgs.kniIp = optarg; - break; - case 'i': - PcapTestGlobalArgs.ipToSendReceivePackets = optarg; - break; - case 'b': - PcapTestGlobalArgs.debugMode = true; - break; - case 'r': - PcapTestGlobalArgs.remoteIp = optarg; - break; - case 'p': - PcapTestGlobalArgs.remotePort = (uint16_t)atoi(optarg); - break; - case 'd': - PcapTestGlobalArgs.dpdkPort = (int)atoi(optarg); - break; - case 'n': - runWithNetworking = false; - break; - case 'v': - PTF_SET_VERBOSE_MODE(true); - break; - case 't': - userTagsInclude = optarg; - break; - case 'x': - userTagsExclude = optarg; - break; - case 's': - skipMemLeakCheck = true; - break; - case 'm': - memVerbose = true; - break; - case 'w': - PTF_SHOW_SKIPPED_TESTS(true); - break; - case 'h': - printUsage(); - exit(0); - default: - printUsage(); - exit(-1); + case 0: + break; + case 'k': + PcapTestGlobalArgs.kniIp = optarg; + break; + case 'i': + PcapTestGlobalArgs.ipToSendReceivePackets = optarg; + break; + case 'b': + PcapTestGlobalArgs.debugMode = true; + break; + case 'r': + PcapTestGlobalArgs.remoteIp = optarg; + break; + case 'p': + PcapTestGlobalArgs.remotePort = (uint16_t)atoi(optarg); + break; + case 'd': + PcapTestGlobalArgs.dpdkPort = (int)atoi(optarg); + break; + case 'n': + runWithNetworking = false; + break; + case 'v': + PTF_SET_VERBOSE_MODE(true); + break; + case 't': + userTagsInclude = optarg; + break; + case 'x': + userTagsExclude = optarg; + break; + case 's': + skipMemLeakCheck = true; + break; + case 'm': + memVerbose = true; + break; + case 'w': + PTF_SHOW_SKIPPED_TESTS(true); + break; + case 'h': + printUsage(); + exit(0); + default: + printUsage(); + exit(-1); } } @@ -127,7 +126,7 @@ int main(int argc, char* argv[]) userTagsInclude += ";"; userTagsInclude += "no_network"; - std:: cout << "Running only tests that don't require network connection" << std::endl; + std::cout << "Running only tests that don't require network connection" << std::endl; } else if (PcapTestGlobalArgs.ipToSendReceivePackets == "") { @@ -136,11 +135,13 @@ int main(int argc, char* argv[]) exit(-1); } - #ifdef NDEBUG +#ifdef NDEBUG skipMemLeakCheck = true; - std:: cout << "Disabling memory leak check in MSVC Release builds due to caching logic in stream objects that looks like a memory leak:" << std::endl - << " https://github.com/cpputest/cpputest/issues/786#issuecomment-148921958" << std::endl; - #endif + std::cout << "Disabling memory leak check in MSVC Release builds due to caching logic in stream objects that looks " + "like a memory leak:" + << std::endl + << " https://github.com/cpputest/cpputest/issues/786#issuecomment-148921958" << std::endl; +#endif // The logger singleton looks like a memory leak. Invoke it before starting the memory check pcpp::Logger::getInstance(); @@ -152,7 +153,7 @@ int main(int argc, char* argv[]) configTags += ";"; configTags += "skip_mem_leak_check"; - std:: cout << "Skipping memory leak check for all test cases" << std::endl; + std::cout << "Skipping memory leak check for all test cases" << std::endl; } if (memVerbose) @@ -161,7 +162,7 @@ int main(int argc, char* argv[]) configTags += ";"; configTags += "mem_leak_check_verbose"; - std:: cout << "Turning on verbose information on memory allocations" << std::endl; + std::cout << "Turning on verbose information on memory allocations" << std::endl; } #ifdef USE_DPDK @@ -171,7 +172,7 @@ int main(int argc, char* argv[]) printUsage(); exit(-1); } -#endif // USE_DPDK +#endif // USE_DPDK if (PcapTestGlobalArgs.debugMode) { @@ -179,10 +180,10 @@ int main(int argc, char* argv[]) } std::cout << "PcapPlusPlus version: " << pcpp::getPcapPlusPlusVersionFull() << std::endl - << "Built: " << pcpp::getBuildDateTime() << std::endl - << "Git info: " << pcpp::getGitInfo() << std::endl - << "Using ip: " << PcapTestGlobalArgs.ipToSendReceivePackets << std::endl - << "Debug mode: " << (PcapTestGlobalArgs.debugMode ? "on" : "off") << std::endl; + << "Built: " << pcpp::getBuildDateTime() << std::endl + << "Git info: " << pcpp::getGitInfo() << std::endl + << "Using ip: " << PcapTestGlobalArgs.ipToSendReceivePackets << std::endl + << "Debug mode: " << (PcapTestGlobalArgs.debugMode ? "on" : "off") << std::endl; #ifdef USE_DPDK if (runWithNetworking) @@ -306,5 +307,5 @@ int main(int argc, char* argv[]) } #ifdef _MSC_VER -#pragma warning(pop) +# pragma warning(pop) #endif diff --git a/Tests/PcppTestFramework/PcppTestFramework.h b/Tests/PcppTestFramework/PcppTestFramework.h index 648dceeb73..37486a4eca 100644 --- a/Tests/PcppTestFramework/PcppTestFramework.h +++ b/Tests/PcppTestFramework/PcppTestFramework.h @@ -13,252 +13,270 @@ #define enum_PTF_PRINT_TYPE_EXPECTED(exp, val) exp << "[" << val << "]" #define ptr_PTF_PRINT_TYPE_ACTUAL(exp, val) exp << "[ptr: " << val << "]" #define ptr_PTF_PRINT_TYPE_EXPECTED(exp, val) exp << "[ptr: " << val << "]" -#define enumclass_PTF_PRINT_TYPE_ACTUAL(exp, val) "enum[" << +static_cast::type>(val) << "]" -#define enumclass_PTF_PRINT_TYPE_EXPECTED(exp, val) exp << "[" << +static_cast::type>(val) << "]" -#define BUFFER_PRINT(buffer, size) \ - for(size_t currentByteId = 0; currentByteId < static_cast(size); ++currentByteId) { \ - std::cout << std::setfill('0') << std::setw(2) << std::right << std::hex << static_cast(*(buffer + currentByteId)) << " "; \ - } \ - std::cout << std::setfill(' ') << std::setw(0) << std::left << std::dec; \ +#define enumclass_PTF_PRINT_TYPE_ACTUAL(exp, val) \ + "enum[" << +static_cast::type>(val) << "]" +#define enumclass_PTF_PRINT_TYPE_EXPECTED(exp, val) \ + exp << "[" << +static_cast::type>(val) << "]" +#define BUFFER_PRINT(buffer, size) \ + for (size_t currentByteId = 0; currentByteId < static_cast(size); ++currentByteId) \ + { \ + std::cout << std::setfill('0') << std::setw(2) << std::right << std::hex \ + << static_cast(*(buffer + currentByteId)) << " "; \ + } \ + std::cout << std::setfill(' ') << std::setw(0) << std::left << std::dec; \ std::cout << std::endl +#define PTF_PRINT_ASSERTION(severity, op) \ + std::cout << std::left << std::setw(35) << __FUNCTION__ << ": " << severity << " (" << __FILE__ << ":" << __LINE__ \ + << "). " \ + << "Assert " << op << " failed:" << std::endl -#define PTF_PRINT_ASSERTION(severity, op) \ - std::cout << std::left << std::setw(35) << __FUNCTION__ << ": " \ - << severity \ - << " (" << __FILE__ << ":" << __LINE__ << "). " \ - << "Assert " << op << " failed:" \ - << std::endl +#define PTF_PRINT_COMPARE_ASSERTION(severity, op, actualExp, actualVal, expectedExp, expectedVal, objType) \ + PTF_PRINT_ASSERTION(severity, op) << " Actual: " << objType##_PTF_PRINT_TYPE_ACTUAL(actualExp, actualVal) \ + << std::endl \ + << " Expected: " \ + << objType##_PTF_PRINT_TYPE_EXPECTED(expectedExp, expectedVal) << std::endl -#define PTF_PRINT_COMPARE_ASSERTION(severity, op, actualExp, actualVal, expectedExp, expectedVal, objType) \ - PTF_PRINT_ASSERTION(severity, op) \ - << " Actual: " << objType##_PTF_PRINT_TYPE_ACTUAL(actualExp, actualVal) \ - << std::endl \ - << " Expected: " << objType##_PTF_PRINT_TYPE_EXPECTED(expectedExp, expectedVal) \ - << std::endl - -#define PTF_PRINT_COMPARE_ASSERTION_FAILED(op, actualExp, actualVal, expectedExp, expectedVal, objType) \ +#define PTF_PRINT_COMPARE_ASSERTION_FAILED(op, actualExp, actualVal, expectedExp, expectedVal, objType) \ PTF_PRINT_COMPARE_ASSERTION("FAILED", op, actualExp, actualVal, expectedExp, expectedVal, objType) -#define PTF_PRINT_COMPARE_ASSERTION_NON_CRITICAL(op, actualExp, actualVal, expectedExp, expectedVal, objType) \ +#define PTF_PRINT_COMPARE_ASSERTION_NON_CRITICAL(op, actualExp, actualVal, expectedExp, expectedVal, objType) \ PTF_PRINT_COMPARE_ASSERTION("NON-CRITICAL", op, actualExp, actualVal, expectedExp, expectedVal, objType) #define PTF_TEST_CASE(TestName) void TestName(int& ptfResult, bool printVerbose, bool showSkipped) -#define PTF_INTERNAL_RUN(TestName) \ - TestName(ptfResult, printVerbose, showSkipped); \ - if (ptfResult == PTF_RESULT_FAILED) { \ - PTF_PRINT_ASSERTION("FAILED", "INTERNAL TEST") \ - << " Internal test '" << #TestName << "' failed" \ - << std::endl; \ - return; \ - } \ - else { \ - ptfResult = PTF_RESULT_PASSED; \ +#define PTF_INTERNAL_RUN(TestName) \ + TestName(ptfResult, printVerbose, showSkipped); \ + if (ptfResult == PTF_RESULT_FAILED) \ + { \ + PTF_PRINT_ASSERTION("FAILED", "INTERNAL TEST") \ + << " Internal test '" << #TestName << "' failed" << std::endl; \ + return; \ + } \ + else \ + { \ + ptfResult = PTF_RESULT_PASSED; \ } #define PTF_IS_VERBOSE_MODE printVerbose -#define PTF_TEST_CASE_PASSED \ - ptfResult = PTF_RESULT_PASSED; \ +#define PTF_TEST_CASE_PASSED \ + ptfResult = PTF_RESULT_PASSED; \ return - -#define PTF_ASSERT_EQUAL(actual, expected, ...) \ - { \ - auto ptfActual = actual; \ - auto ptfExpected = static_cast(expected); \ - if (ptfActual != ptfExpected) { \ - PTF_PRINT_COMPARE_ASSERTION_FAILED("EQUAL", #actual, ptfActual, #expected, ptfExpected, __VA_ARGS__); \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ - } \ +#define PTF_ASSERT_EQUAL(actual, expected, ...) \ + { \ + auto ptfActual = actual; \ + auto ptfExpected = static_cast(expected); \ + if (ptfActual != ptfExpected) \ + { \ + PTF_PRINT_COMPARE_ASSERTION_FAILED("EQUAL", #actual, ptfActual, #expected, ptfExpected, __VA_ARGS__); \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ + } \ } -#define PTF_ASSERT_VECTORS_EQUAL(actual, expected, ...) \ - { \ - if (actual != expected) {\ - std::ostringstream actualOss, expectedOss; \ - bool first = true; \ - for (const auto& elem : actual) { \ - if (!first) actualOss << ", "; \ - actualOss << elem; \ - first = false; \ - } \ - first = true; \ - for (const auto& elem : expected) { \ - if (!first) expectedOss << ", "; \ - expectedOss << elem; \ - first = false; \ - } \ - std::string actualValues = "[" + actualOss.str() + "]"; \ - std::string expectedValues = "[" + expectedOss.str() + "]"; \ - PTF_PRINT_COMPARE_ASSERTION_FAILED("VECTORS EQUAL", #actual, actualValues, #expected, expectedValues, __VA_ARGS__); \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ - } \ +#define PTF_ASSERT_VECTORS_EQUAL(actual, expected, ...) \ + { \ + if (actual != expected) \ + { \ + std::ostringstream actualOss, expectedOss; \ + bool first = true; \ + for (const auto& elem : actual) \ + { \ + if (!first) \ + actualOss << ", "; \ + actualOss << elem; \ + first = false; \ + } \ + first = true; \ + for (const auto& elem : expected) \ + { \ + if (!first) \ + expectedOss << ", "; \ + expectedOss << elem; \ + first = false; \ + } \ + std::string actualValues = "[" + actualOss.str() + "]"; \ + std::string expectedValues = "[" + expectedOss.str() + "]"; \ + PTF_PRINT_COMPARE_ASSERTION_FAILED("VECTORS EQUAL", #actual, actualValues, #expected, expectedValues, \ + __VA_ARGS__); \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ + } \ } -#define PTF_ASSERT_NOT_EQUAL(actual, expected, ...) \ - { \ - auto ptfActual = actual; \ - auto ptfExpected = static_cast(expected); \ - if (ptfActual == ptfExpected) { \ - PTF_PRINT_COMPARE_ASSERTION_FAILED("NOT EQUAL", #actual, ptfActual, #expected, ptfExpected, __VA_ARGS__); \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ - } \ +#define PTF_ASSERT_NOT_EQUAL(actual, expected, ...) \ + { \ + auto ptfActual = actual; \ + auto ptfExpected = static_cast(expected); \ + if (ptfActual == ptfExpected) \ + { \ + PTF_PRINT_COMPARE_ASSERTION_FAILED("NOT EQUAL", #actual, ptfActual, #expected, ptfExpected, __VA_ARGS__); \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ + } \ } -#define PTF_ASSERT_GREATER_THAN(actual, expected, ...) \ - { \ - auto ptfActual = actual; \ - auto ptfExpected = static_cast(expected); \ - if (ptfActual <= ptfExpected) { \ - PTF_PRINT_COMPARE_ASSERTION_FAILED("GREATER THAN", #actual, ptfActual, #expected, ptfExpected, __VA_ARGS__); \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ - } \ +#define PTF_ASSERT_GREATER_THAN(actual, expected, ...) \ + { \ + auto ptfActual = actual; \ + auto ptfExpected = static_cast(expected); \ + if (ptfActual <= ptfExpected) \ + { \ + PTF_PRINT_COMPARE_ASSERTION_FAILED("GREATER THAN", #actual, ptfActual, #expected, ptfExpected, \ + __VA_ARGS__); \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ + } \ } -#define PTF_ASSERT_GREATER_OR_EQUAL_THAN(actual, expected, ...) \ - { \ - auto ptfActual = actual; \ - auto ptfExpected = static_cast(expected); \ - if (ptfActual < ptfExpected) { \ - PTF_PRINT_COMPARE_ASSERTION_FAILED("GREATER OR EQUAL THAN", #actual, ptfActual, #expected, ptfExpected, __VA_ARGS__); \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ - } \ +#define PTF_ASSERT_GREATER_OR_EQUAL_THAN(actual, expected, ...) \ + { \ + auto ptfActual = actual; \ + auto ptfExpected = static_cast(expected); \ + if (ptfActual < ptfExpected) \ + { \ + PTF_PRINT_COMPARE_ASSERTION_FAILED("GREATER OR EQUAL THAN", #actual, ptfActual, #expected, ptfExpected, \ + __VA_ARGS__); \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ + } \ } -#define PTF_ASSERT_LOWER_THAN(actual, expected, ...) \ - { \ - auto ptfActual = actual; \ - auto ptfExpected = static_cast(expected); \ - if (ptfActual >= ptfExpected) { \ +#define PTF_ASSERT_LOWER_THAN(actual, expected, ...) \ + { \ + auto ptfActual = actual; \ + auto ptfExpected = static_cast(expected); \ + if (ptfActual >= ptfExpected) \ + { \ PTF_PRINT_COMPARE_ASSERTION_FAILED("LOWER THAN", #actual, ptfActual, #expected, ptfExpected, __VA_ARGS__); \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ - } \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ + } \ } -#define PTF_ASSERT_LOWER_OR_EQUAL_THAN(actual, expected, ...) \ - { \ - auto ptfActual = actual; \ - auto ptfExpected = static_cast(expected); \ - if (ptfActual > ptfExpected) { \ - PTF_PRINT_COMPARE_ASSERTION_FAILED("LOWER OR EQUAL THAN", #actual, ptfActual, #expected, ptfExpected, __VA_ARGS__); \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ - } \ +#define PTF_ASSERT_LOWER_OR_EQUAL_THAN(actual, expected, ...) \ + { \ + auto ptfActual = actual; \ + auto ptfExpected = static_cast(expected); \ + if (ptfActual > ptfExpected) \ + { \ + PTF_PRINT_COMPARE_ASSERTION_FAILED("LOWER OR EQUAL THAN", #actual, ptfActual, #expected, ptfExpected, \ + __VA_ARGS__); \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ + } \ } -#define PTF_ASSERT_BUF_COMPARE(buf1, buf2, size) \ - if (memcmp(buf1, buf2, size) != 0) { \ - PTF_PRINT_ASSERTION("FAILED", "BUFFER COMPARE") \ - << " Actual " << std::endl; \ - BUFFER_PRINT(buf1, size) \ - << " Expected " << std::endl; \ - BUFFER_PRINT(buf2, size); \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ +#define PTF_ASSERT_BUF_COMPARE(buf1, buf2, size) \ + if (memcmp(buf1, buf2, size) != 0) \ + { \ + PTF_PRINT_ASSERTION("FAILED", "BUFFER COMPARE") << " Actual " << std::endl; \ + BUFFER_PRINT(buf1, size) << " Expected " << std::endl; \ + BUFFER_PRINT(buf2, size); \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ } -#define PTF_ASSERT_TRUE(exp) \ - if (!(exp)) { \ - PTF_PRINT_ASSERTION("FAILED", "TRUE") \ - << " [" << #exp << "]" \ - << std::endl; \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ +#define PTF_ASSERT_TRUE(exp) \ + if (!(exp)) \ + { \ + PTF_PRINT_ASSERTION("FAILED", "TRUE") << " [" << #exp << "]" << std::endl; \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ } -#define PTF_ASSERT_FALSE(exp) \ - if (exp) { \ - PTF_PRINT_ASSERTION("FAILED", "FALSE") \ - << " [" << #exp << "]" \ - << std::endl; \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ +#define PTF_ASSERT_FALSE(exp) \ + if (exp) \ + { \ + PTF_PRINT_ASSERTION("FAILED", "FALSE") << " [" << #exp << "]" << std::endl; \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ } -#define PTF_ASSERT_NOT_NULL(exp) \ - if ((exp) == NULL) { \ - PTF_PRINT_ASSERTION("FAILED", "NOT NULL") \ - << " [" << #exp << "] is NULL" \ - << std::endl; \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ +#define PTF_ASSERT_NOT_NULL(exp) \ + if ((exp) == NULL) \ + { \ + PTF_PRINT_ASSERTION("FAILED", "NOT NULL") << " [" << #exp << "] is NULL" << std::endl; \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ } -#define PTF_ASSERT_NULL(exp) \ - if ((exp) != NULL) { \ - PTF_PRINT_ASSERTION("FAILED", "NULL") \ - << " [" << #exp << "] is not NULL" \ - << std::endl; \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ +#define PTF_ASSERT_NULL(exp) \ + if ((exp) != NULL) \ + { \ + PTF_PRINT_ASSERTION("FAILED", "NULL") << " [" << #exp << "] is not NULL" << std::endl; \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ } -#define PTF_ASSERT_RAISES(expression, exception_type, message) \ - { \ - auto rightExceptionCaught = false; \ - std::string messageCaught = ""; \ - try { \ - expression; \ - } \ - catch (const exception_type& e) { \ - rightExceptionCaught = true; \ - messageCaught = e.what(); \ - } \ - catch ( ... ) { /* do nothing */ } \ - if (!rightExceptionCaught) { \ - PTF_PRINT_ASSERTION("FAILED", "EXCEPTION RAISED") \ - << " " << #exception_type << " not raised" << std::endl; \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ - } \ - if (messageCaught != std::string(message)) { \ - PTF_PRINT_ASSERTION("FAILED", "EXCEPTION RAISED") \ - << " " << "Expected message: " << std::string(message) << std::endl \ - << " " << "Message caught : " << messageCaught << std::endl; \ - ptfResult = PTF_RESULT_FAILED; \ - return; \ - } \ +#define PTF_ASSERT_RAISES(expression, exception_type, message) \ + { \ + auto rightExceptionCaught = false; \ + std::string messageCaught = ""; \ + try \ + { \ + expression; \ + } \ + catch (const exception_type& e) \ + { \ + rightExceptionCaught = true; \ + messageCaught = e.what(); \ + } \ + catch (...) \ + { /* do nothing */ \ + } \ + if (!rightExceptionCaught) \ + { \ + PTF_PRINT_ASSERTION("FAILED", "EXCEPTION RAISED") \ + << " " << #exception_type << " not raised" << std::endl; \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ + } \ + if (messageCaught != std::string(message)) \ + { \ + PTF_PRINT_ASSERTION("FAILED", "EXCEPTION RAISED") \ + << " " \ + << "Expected message: " << std::string(message) << std::endl \ + << " " \ + << "Message caught : " << messageCaught << std::endl; \ + ptfResult = PTF_RESULT_FAILED; \ + return; \ + } \ } -#define PTF_NON_CRITICAL_EQUAL(actual, expected, ...) \ - { \ - auto ptfActual = actual; \ - auto ptfExpected = static_cast(expected); \ - if (ptfActual != ptfExpected) { \ - PTF_PRINT_COMPARE_ASSERTION_NON_CRITICAL("EQUAL", #actual, ptfActual, #expected, ptfExpected, __VA_ARGS__); \ - } \ +#define PTF_NON_CRITICAL_EQUAL(actual, expected, ...) \ + { \ + auto ptfActual = actual; \ + auto ptfExpected = static_cast(expected); \ + if (ptfActual != ptfExpected) \ + { \ + PTF_PRINT_COMPARE_ASSERTION_NON_CRITICAL("EQUAL", #actual, ptfActual, #expected, ptfExpected, \ + __VA_ARGS__); \ + } \ } -#define PTF_NON_CRITICAL_TRUE(exp) \ - if (!exp) { \ - PTF_PRINT_ASSERTION("NON-CRITICAL", "TRUE") \ - << " [" << #exp << "]" \ - << std::endl; \ +#define PTF_NON_CRITICAL_TRUE(exp) \ + if (!exp) \ + { \ + PTF_PRINT_ASSERTION("NON-CRITICAL", "TRUE") << " [" << #exp << "]" << std::endl; \ } -#define PTF_PRINT_VERBOSE(data) \ - if(printVerbose) { \ - std::cout << std::left << std::setw(35) << __FUNCTION__ << ": " \ - << "[VERBOSE] " \ - << data \ - << std::endl; \ - } \ +#define PTF_PRINT_VERBOSE(data) \ + if (printVerbose) \ + { \ + std::cout << std::left << std::setw(35) << __FUNCTION__ << ": " \ + << "[VERBOSE] " << data << std::endl; \ + } -#define PTF_SKIP_TEST(why) \ - { \ - if (showSkipped) { \ - std::cout << std::left << std::setw(35) << __FUNCTION__ << ": " \ - << "SKIPPED (" << why << ")" \ - << std::endl; \ - } \ - ptfResult = PTF_RESULT_SKIPPED; \ - return; \ +#define PTF_SKIP_TEST(why) \ + { \ + if (showSkipped) \ + { \ + std::cout << std::left << std::setw(35) << __FUNCTION__ << ": " \ + << "SKIPPED (" << why << ")" << std::endl; \ + } \ + ptfResult = PTF_RESULT_SKIPPED; \ + return; \ } diff --git a/Tests/PcppTestFramework/PcppTestFrameworkRun.h b/Tests/PcppTestFramework/PcppTestFrameworkRun.h index af77c5152f..9aae9794ed 100644 --- a/Tests/PcppTestFramework/PcppTestFrameworkRun.h +++ b/Tests/PcppTestFramework/PcppTestFrameworkRun.h @@ -14,13 +14,13 @@ static void __ptfSplitString(const std::string& input, std::vector& std::istringstream ss(input); std::string token; - while(std::getline(ss, token, ';')) + while (std::getline(ss, token, ';')) { result.push_back(token); } } -static bool __ptfCheckTags(const std::string &tagSet, const std::string &tagSetToCompareWith, bool emptyTagSetMeansAll) +static bool __ptfCheckTags(const std::string& tagSet, const std::string& tagSetToCompareWith, bool emptyTagSetMeansAll) { std::vector tagSetVec, tagSetToCompareWithVec; @@ -32,9 +32,10 @@ static bool __ptfCheckTags(const std::string &tagSet, const std::string &tagSetT __ptfSplitString(tagSet, tagSetVec); __ptfSplitString(tagSetToCompareWith, tagSetToCompareWithVec); - for (const auto &tagSetToCompareWithIter : tagSetToCompareWithVec) + for (const auto& tagSetToCompareWithIter : tagSetToCompareWithVec) { - if (std::any_of(tagSetVec.begin(), tagSetVec.end(), [tagSetToCompareWithIter](const std::string &val){ return val == tagSetToCompareWithIter;})) + if (std::any_of(tagSetVec.begin(), tagSetVec.end(), + [tagSetToCompareWithIter](const std::string& val) { return val == tagSetToCompareWithIter; })) { return true; } @@ -43,84 +44,88 @@ static bool __ptfCheckTags(const std::string &tagSet, const std::string &tagSetT return false; } -#define PTF_START_RUNNING_TESTS(userIncludeTags, userExcludeTags, configTags) \ - bool allTestsPassed = true; \ - int testsPassed = 0; \ - int testsFailed = 0; \ - int testsSkipped = 0; \ - std::string ptfUserIncludeTags = userIncludeTags; \ - std::string ptfUserExcludeTags = userExcludeTags; \ - std::string configTagsToRun = configTags; \ +#define PTF_START_RUNNING_TESTS(userIncludeTags, userExcludeTags, configTags) \ + bool allTestsPassed = true; \ + int testsPassed = 0; \ + int testsFailed = 0; \ + int testsSkipped = 0; \ + std::string ptfUserIncludeTags = userIncludeTags; \ + std::string ptfUserExcludeTags = userExcludeTags; \ + std::string configTagsToRun = configTags; \ std::cout << "Start running tests..." << std::endl << std::endl -#define PTF_RUN_TEST(TestName, tags) \ - std::string TestName##_tags = std::string(#TestName) + ";" + tags; \ - int TestName##_result = PTF_RESULT_PASSED; \ - if (!__ptfCheckTags(TestName##_tags, ptfUserIncludeTags, true) || __ptfCheckTags(TestName##_tags, ptfUserExcludeTags, false)) \ - { \ - if (showSkippedTests) \ - { \ - std::cout << std::left << std::setw(35) << #TestName << ": SKIPPED (tags don't match)" << std::endl; \ - } \ - TestName##_result = PTF_RESULT_SKIPPED; \ - } \ - else \ - { \ - bool runMemLeakCheck = !__ptfCheckTags("skip_mem_leak_check", configTagsToRun, false) && !__ptfCheckTags(TestName##_tags, "skip_mem_leak_check", false); \ - if (runMemLeakCheck) \ - { \ - bool memAllocVerbose = __ptfCheckTags("mem_leak_check_verbose", configTagsToRun, false); \ - MemPlumber::start(memAllocVerbose); \ - } \ - try \ - { \ - TestName(TestName##_result, verboseMode, showSkippedTests); \ - } \ - catch (std::exception const& e) \ - { \ - TestName##_result = PTF_RESULT_FAILED; \ - std::cout << std::left << std::setw(35) << #TestName << ": FAILED. Unhandled exception occurred! " \ - << "Exception: " << e.what() << std::endl; \ - } \ - if (runMemLeakCheck) \ - { \ - if (TestName##_result != PTF_RESULT_PASSED) \ - { \ - MemPlumber::stopAndFreeAllMemory(); \ - } \ - else \ - { \ - size_t memLeakCount = 0; \ - uint64_t memLeakSize = 0; \ - MemPlumber::memLeakCheck(memLeakCount, memLeakSize, true); \ - MemPlumber::stopAndFreeAllMemory(); \ - if (memLeakCount > 0 || memLeakSize > 0) \ - { \ - TestName##_result = PTF_RESULT_FAILED; \ - std::cout << std::left << std::setw(35) << #TestName << ": FAILED. Memory leak found! " \ - << memLeakCount << " objects and " \ - << memLeakSize << "[bytes] leaked" << std::endl; \ - } \ - } \ - } \ - if (TestName##_result == PTF_RESULT_PASSED) \ - { \ - std::cout << std::left << std::setw(35) << #TestName << ": PASSED" << std::endl; \ - } \ - } \ - if (TestName##_result == PTF_RESULT_PASSED) testsPassed++; \ - if (TestName##_result == PTF_RESULT_FAILED) testsFailed++; \ - if (TestName##_result == PTF_RESULT_SKIPPED) testsSkipped++; \ +#define PTF_RUN_TEST(TestName, tags) \ + std::string TestName##_tags = std::string(#TestName) + ";" + tags; \ + int TestName##_result = PTF_RESULT_PASSED; \ + if (!__ptfCheckTags(TestName##_tags, ptfUserIncludeTags, true) || \ + __ptfCheckTags(TestName##_tags, ptfUserExcludeTags, false)) \ + { \ + if (showSkippedTests) \ + { \ + std::cout << std::left << std::setw(35) << #TestName << ": SKIPPED (tags don't match)" << std::endl; \ + } \ + TestName##_result = PTF_RESULT_SKIPPED; \ + } \ + else \ + { \ + bool runMemLeakCheck = !__ptfCheckTags("skip_mem_leak_check", configTagsToRun, false) && \ + !__ptfCheckTags(TestName##_tags, "skip_mem_leak_check", false); \ + if (runMemLeakCheck) \ + { \ + bool memAllocVerbose = __ptfCheckTags("mem_leak_check_verbose", configTagsToRun, false); \ + MemPlumber::start(memAllocVerbose); \ + } \ + try \ + { \ + TestName(TestName##_result, verboseMode, showSkippedTests); \ + } \ + catch (std::exception const& e) \ + { \ + TestName##_result = PTF_RESULT_FAILED; \ + std::cout << std::left << std::setw(35) << #TestName << ": FAILED. Unhandled exception occurred! " \ + << "Exception: " << e.what() << std::endl; \ + } \ + if (runMemLeakCheck) \ + { \ + if (TestName##_result != PTF_RESULT_PASSED) \ + { \ + MemPlumber::stopAndFreeAllMemory(); \ + } \ + else \ + { \ + size_t memLeakCount = 0; \ + uint64_t memLeakSize = 0; \ + MemPlumber::memLeakCheck(memLeakCount, memLeakSize, true); \ + MemPlumber::stopAndFreeAllMemory(); \ + if (memLeakCount > 0 || memLeakSize > 0) \ + { \ + TestName##_result = PTF_RESULT_FAILED; \ + std::cout << std::left << std::setw(35) << #TestName << ": FAILED. Memory leak found! " \ + << memLeakCount << " objects and " << memLeakSize << "[bytes] leaked" << std::endl; \ + } \ + } \ + } \ + if (TestName##_result == PTF_RESULT_PASSED) \ + { \ + std::cout << std::left << std::setw(35) << #TestName << ": PASSED" << std::endl; \ + } \ + } \ + if (TestName##_result == PTF_RESULT_PASSED) \ + testsPassed++; \ + if (TestName##_result == PTF_RESULT_FAILED) \ + testsFailed++; \ + if (TestName##_result == PTF_RESULT_SKIPPED) \ + testsSkipped++; \ allTestsPassed &= (TestName##_result != PTF_RESULT_FAILED) - -#define PTF_END_RUNNING_TESTS \ - std::string message = (allTestsPassed ? "ALL TESTS PASSED!!" : "NOT ALL TESTS PASSED!!"); \ - std::cout << std::endl << message << std::endl \ - << "Test cases: " << testsPassed + testsFailed + testsSkipped << ", " \ - << "Passed: " << testsPassed << ", " \ - << "Failed: " << testsFailed << ", " \ - << "Skipped: " << testsSkipped << std::endl; \ +#define PTF_END_RUNNING_TESTS \ + std::string message = (allTestsPassed ? "ALL TESTS PASSED!!" : "NOT ALL TESTS PASSED!!"); \ + std::cout << std::endl \ + << message << std::endl \ + << "Test cases: " << testsPassed + testsFailed + testsSkipped << ", " \ + << "Passed: " << testsPassed << ", " \ + << "Failed: " << testsFailed << ", " \ + << "Skipped: " << testsSkipped << std::endl; \ return (allTestsPassed ? 0 : 1); static bool verboseMode = false;