49 constexpr auto globalHeaderSize = std::size_t{24};
50 constexpr auto recordHeaderSize = std::size_t{16};
51 constexpr auto ethernetHeaderSize = std::size_t{14};
52 constexpr auto vlanTagSize = std::size_t{4};
53 constexpr auto udpHeaderSize = std::size_t{8};
54 constexpr auto linkTypeEthernet = std::uint32_t{1};
55 constexpr auto etherTypeVlan = std::uint16_t{0x8100};
56 constexpr auto etherTypeIpv4 = std::uint16_t{0x0800};
57 constexpr auto ipProtocolUdp = std::uint8_t{17};
59 auto const contents =
readFile(path);
60 auto const file = std::span{
reinterpret_cast<std::uint8_t const*
>(contents.data()), contents.size()};
61 auto const fail = [&path](
char const* reason)
63 throw std::runtime_error{
"Invalid pcap file " + path.string() +
": " + reason};
66 if (file.size() < globalHeaderSize)
68 fail(
"missing global header");
71 auto const bigEndian = (magic == 0xA1B2C3D4U) || (magic == 0xA1B23C4DU);
73 if (!bigEndian && (magic != 0xD4C3B2A1U) && (magic != 0x4D3CB2A1U))
75 fail(
"not a classic pcap file");
79 fail(
"link type is not Ethernet");
82 auto datagrams = std::vector<UdpDatagram>{};
83 auto offset = globalHeaderSize;
84 while (offset < file.size())
86 if (file.size() - offset < recordHeaderSize)
88 fail(
"truncated record header");
92 offset += recordHeaderSize;
93 if ((file.size() - offset < capturedLength) || (capturedLength != originalLength))
95 fail(
"truncated packet");
97 auto const frame = file.subspan(offset, capturedLength);
98 offset += capturedLength;
100 if (frame.size() < ethernetHeaderSize)
104 auto ipOffset = ethernetHeaderSize;
106 if ((etherType == etherTypeVlan) && (frame.size() >= ethernetHeaderSize + vlanTagSize))
109 ipOffset += vlanTagSize;
111 if ((etherType != etherTypeIpv4) || (frame.size() < ipOffset + 20))
116 auto const ip = frame.subspan(ipOffset);
117 auto const ipHeaderSize = std::size_t{ip[0] & 0x0FU} * 4U;
121 if (((ip[0] >> 4U) != 4) || (ip[9] != ipProtocolUdp) || fragmented || (ipHeaderSize < 20) || (ipTotalLength > ip.size()) ||
122 (ipTotalLength < ipHeaderSize + udpHeaderSize))
127 auto const udp = ip.subspan(ipHeaderSize, ipTotalLength - ipHeaderSize);
129 if ((udpLength < udpHeaderSize) || (udpLength > udp.size()))
131 fail(
"invalid UDP length");
133 auto const payload = udp.subspan(udpHeaderSize, udpLength - udpHeaderSize);
136 .payload = {payload.begin(), payload.end()},