48 {
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};
58
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)
62 {
63 throw std::runtime_error{"Invalid pcap file " + path.string() + ": " + reason};
64 };
65
66 if (file.size() < globalHeaderSize)
67 {
68 fail("missing global header");
69 }
71 auto const bigEndian = (magic == 0xA1B2C3D4U) || (magic == 0xA1B23C4DU);
72
73 if (!bigEndian && (magic != 0xD4C3B2A1U) && (magic != 0x4D3CB2A1U))
74 {
75 fail("not a classic pcap file");
76 }
78 {
79 fail("link type is not Ethernet");
80 }
81
82 auto datagrams = std::vector<UdpDatagram>{};
83 auto offset = globalHeaderSize;
84 while (offset < file.size())
85 {
86 if (file.size() - offset < recordHeaderSize)
87 {
88 fail("truncated record header");
89 }
92 offset += recordHeaderSize;
93 if ((file.size() - offset < capturedLength) || (capturedLength != originalLength))
94 {
95 fail("truncated packet");
96 }
97 auto const frame = file.subspan(offset, capturedLength);
98 offset += capturedLength;
99
100 if (frame.size() < ethernetHeaderSize)
101 {
102 continue;
103 }
104 auto ipOffset = ethernetHeaderSize;
106 if ((etherType == etherTypeVlan) && (frame.size() >= ethernetHeaderSize + vlanTagSize))
107 {
109 ipOffset += vlanTagSize;
110 }
111 if ((etherType != etherTypeIpv4) || (frame.size() < ipOffset + 20))
112 {
113 continue;
114 }
115
116 auto const ip = frame.subspan(ipOffset);
117 auto const ipHeaderSize = std::size_t{ip[0] & 0x0FU} * 4U;
119
121 if (((ip[0] >> 4U) != 4) || (ip[9] != ipProtocolUdp) || fragmented || (ipHeaderSize < 20) || (ipTotalLength > ip.size()) ||
122 (ipTotalLength < ipHeaderSize + udpHeaderSize))
123 {
124 continue;
125 }
126
127 auto const udp = ip.subspan(ipHeaderSize, ipTotalLength - ipHeaderSize);
129 if ((udpLength < udpHeaderSize) || (udpLength > udp.size()))
130 {
131 fail("invalid UDP length");
132 }
133 auto const payload = udp.subspan(udpHeaderSize, udpLength - udpHeaderSize);
136 .payload = {payload.begin(), payload.end()},
137 });
138 }
139 return datagrams;
140 }
std::uint16_t readBigEndian16(std::span< std::uint8_t const > bytes, std::size_t offset)
std::uint32_t readPcap32(std::span< std::uint8_t const > bytes, std::size_t offset, bool bigEndian)
std::string readFile(std::filesystem::path const &filepath)