95 if (file_ ==
nullptr) {
96 throw std::runtime_error(std::format(
"{}: {}", path,
errno_text(errno)));
100 zstd_ = ZSTD_createDCtx();
102 codec_ = Codec::GZIP;
103 gzip_ready_ = inflateInit2(&gzip_, 15 + 16) == Z_OK;
105 if ((codec_ == Codec::ZSTD && zstd_ ==
nullptr) || (codec_ == Codec::GZIP && !gzip_ready_)) {
107 throw std::bad_alloc();
109 if (codec_ != Codec::NONE) {
110 in_.resize(IN_BYTES);
115 if (zstd_ !=
nullptr) {
116 ZSTD_freeDCtx(zstd_);
129 size_t read(uint8_t *dst,
size_t size) {
130 if (!error_.empty()) {
134 case Codec::ZSTD:
return read_zstd(dst, size);
135 case Codec::GZIP:
return read_gzip(dst, size);
136 case Codec::NONE:
break;
138 return read_file(dst, size);
142 [[nodiscard]]
const std::string &
error() const noexcept {
return error_; }
145 enum class Codec : uint8_t {
NONE, ZSTD, GZIP };
146 static constexpr size_t IN_BYTES = 1u << 18;
148 size_t read_file(uint8_t *dst,
size_t size) {
149 const size_t got = std::fread(dst, 1, size, file_);
150 if (got < size && std::ferror(file_)) {
151 error_ = std::format(
"read failed: {}",
errno_text(errno));
158 if (in_pos_ < in_len_) {
162 in_len_ = read_file(in_.data(), in_.size());
166 size_t read_zstd(uint8_t *dst,
size_t size) {
167 ZSTD_outBuffer out{dst, size, 0};
168 while (out.pos < out.size) {
169 const bool input = refill();
170 if (!error_.empty() || (!input && !open_)) {
174 ZSTD_inBuffer in{in_.data(), in_len_, in_pos_};
175 const size_t out_before = out.pos;
176 const size_t in_before = in_pos_;
177 const size_t hint = ZSTD_decompressStream(zstd_, &out, &in);
179 if (ZSTD_isError(hint)) {
180 error_ = std::format(
"zstd: {}; the file is corrupt", ZSTD_getErrorName(hint));
184 if (out.pos == out_before && in_pos_ == in_before) {
187 error_ = input ?
"zstd stopped making progress; the file is corrupt"
188 :
"the zstd stream ends inside a frame; the file is truncated";
195 size_t read_gzip(uint8_t *dst,
size_t size) {
196 gzip_.next_out = dst;
197 gzip_.avail_out =
static_cast<uInt
>(size);
198 while (gzip_.avail_out > 0) {
199 const bool input = refill();
200 if (!error_.empty() || (!input && !open_)) {
203 if (input && !open_) {
205 if (members_++ > 0) {
206 inflateReset(&gzip_);
210 gzip_.next_in = in_.data() + in_pos_;
211 gzip_.avail_in =
static_cast<uInt
>(in_len_ - in_pos_);
212 const uInt out_before = gzip_.avail_out;
213 const uInt in_before = gzip_.avail_in;
214 const int rc = inflate(&gzip_, Z_NO_FLUSH);
215 in_pos_ = in_len_ - gzip_.avail_in;
216 if (rc == Z_STREAM_END) {
218 }
else if (rc != Z_OK && rc != Z_BUF_ERROR) {
219 error_ = std::format(
"gzip: {}; the file is corrupt", gzip_.msg !=
nullptr ? gzip_.msg : zError(rc));
221 }
else if (gzip_.avail_out == out_before && gzip_.avail_in == in_before) {
223 error_ = input ?
"gzip stopped making progress; the file is corrupt"
224 :
"the gzip stream ends inside a member; the file is truncated";
228 return size - gzip_.avail_out;
231 std::FILE *file_ =
nullptr;
232 Codec codec_ = Codec::NONE;
233 ZSTD_DCtx *zstd_ =
nullptr;
235 bool gzip_ready_ =
false;
236 uint64_t members_ = 0;
238 std::vector<uint8_t> in_;
262 buffer_.resize(BUFFER_BYTES);
264 fail(stream_.error().empty() ?
"not a pcap or pcapng capture" : stream_.error());
267 std::memcpy(&magic, data(),
sizeof(magic));
268 if (magic == PCAPNG_SECTION) {
272 while (interfaces_.empty()) {
273 if (!next_block(block)) {
274 fail(error_.empty() ?
"a pcapng capture with no interface" : error_);
276 if (block.type == PCAPNG_ENHANCED || block.type == PCAPNG_SIMPLE || block.type == PCAPNG_OBSOLETE) {
277 fail(
"a pcapng packet comes before any interface is described");
291 if (!error_.empty()) {
294 return pcapng_ ? next_pcapng(out) : next_pcap(out);
299 [[nodiscard]]
const std::string &
error()
const {
return error_; }
300 [[nodiscard]]
const std::string &
path()
const {
return path_; }
303 [[nodiscard]] uint64_t
truncated() const noexcept {
return truncated_; }
306 static constexpr size_t BUFFER_BYTES = 1u << 20;
309 static constexpr uint32_t MAX_RECORD_BYTES = 16u << 20;
311 static constexpr uint32_t PCAP_MICRO = 0xa1b2c3d4;
312 static constexpr uint32_t PCAP_NANO = 0xa1b23c4d;
313 static constexpr uint32_t PCAPNG_SECTION = 0x0a0d0d0a;
314 static constexpr uint32_t PCAPNG_BYTE_ORDER = 0x1a2b3c4d;
315 static constexpr uint32_t PCAPNG_INTERFACE = 1;
316 static constexpr uint32_t PCAPNG_OBSOLETE = 2;
317 static constexpr uint32_t PCAPNG_SIMPLE = 3;
318 static constexpr uint32_t PCAPNG_ENHANCED = 6;
320 static constexpr uint16_t LINK_ETHERNET = 1;
324 static constexpr bool readable(uint32_t link_type)
noexcept {
325 return link_type == LINK_ETHERNET || link_type == 101 || link_type == 12 || link_type == 14 ||
331 uint16_t link_type = 0;
332 uint32_t snaplen = 0;
334 uint8_t exponent = 6;
335 int64_t offset_s = 0;
337 [[nodiscard]] uint64_t to_ns(uint64_t ts)
const noexcept {
340 const uint8_t e = exponent;
341 const uint64_t seconds = ts >> e;
342 const uint64_t fraction = ts & ((uint64_t(1) << e) - 1);
343 uint64_t scaled = (fraction & 0xffffffff) * 1'000'000'000ull;
346 scaled = ((fraction >> 32) * 1'000'000'000ull + (scaled >> 32)) >> (e - 32);
350 ns = seconds * 1'000'000'000ull + scaled;
351 }
else if (exponent <= 9) {
352 ns = ts * pow10(9 - exponent);
354 ns = ts / pow10(exponent - 9);
358 const uint64_t back = (uint64_t(0) -
static_cast<uint64_t
>(offset_s)) * 1'000'000'000ull;
359 return ns > back ? ns - back : 0;
361 return ns +
static_cast<uint64_t
>(offset_s) * 1'000'000'000ull;
364 static constexpr uint64_t pow10(
unsigned n)
noexcept {
376 const uint8_t *body =
nullptr;
380 [[noreturn]]
void fail(
const std::string &why)
const {
381 throw std::runtime_error(std::format(
"{}: {}", path_, why));
384 void open_pcap(uint32_t magic) {
385 if (magic == std::byteswap(PCAP_MICRO) || magic == std::byteswap(PCAP_NANO)) {
387 magic = std::byteswap(magic);
389 if (magic != PCAP_MICRO && magic != PCAP_NANO) {
390 fail(stream_.error().empty() ?
"not a pcap or pcapng capture" : stream_.error());
392 nano_ = magic == PCAP_NANO;
394 fail(stream_.error().empty() ?
"the pcap header is cut short" : stream_.error());
396 if (
const uint16_t major = u16(data() + 4); major != 2) {
397 fail(std::format(
"pcap version {} is not read", major));
399 link_type_ = u32(data() + 20) & 0xffff;
400 if (!readable(link_type_)) {
401 fail(std::format(
"unsupported link type {}", link_type_));
406 bool next_pcap(PcapPacket &out) {
409 return end_of_stream();
411 const uint32_t caplen = u32(data() + 8);
412 if (caplen > MAX_RECORD_BYTES) {
413 error_ = std::format(
"a record claims {} captured bytes; the file is corrupt", caplen);
416 if (!fill(16 +
size_t(caplen))) {
417 return end_of_stream();
419 const uint8_t *record = data();
420 consume(16 +
size_t(caplen));
421 const uint64_t fraction = u32(record + 4);
422 const uint64_t ts_ns = uint64_t(u32(record)) * 1'000'000'000ull + (nano_ ? fraction : fraction * 1000);
423 if (parse(link_type_, record + 16, caplen, ts_ns, out)) {
429 bool next_pcapng(PcapPacket &out) {
431 while (next_block(block)) {
435 const uint8_t *frame =
nullptr;
436 if (block.type == PCAPNG_ENHANCED || block.type == PCAPNG_OBSOLETE) {
437 if (block.size < 20) {
438 return malformed(
"packet");
440 if_id = block.type == PCAPNG_ENHANCED ? u32(block.body) : u16(block.body);
441 ts = (uint64_t(u32(block.body + 4)) << 32) | u32(block.body + 8);
442 caplen = u32(block.body + 12);
443 frame = block.body + 20;
444 if (caplen > block.size - 20) {
445 return malformed(
"packet");
447 }
else if (block.type == PCAPNG_SIMPLE) {
448 if (block.size < 4) {
449 return malformed(
"simple packet");
452 caplen = std::min<size_t>(u32(block.body), block.size - 4);
453 frame = block.body + 4;
457 if (if_id >= interfaces_.size()) {
458 error_ = std::format(
"a packet names interface {}, which is not described", if_id);
461 const Interface &described = interfaces_[if_id];
462 if (block.type == PCAPNG_SIMPLE && described.snaplen != 0) {
463 caplen = std::min<size_t>(caplen, described.snaplen);
466 const uint64_t ts_ns = block.type == PCAPNG_SIMPLE ? 0 : described.to_ns(ts);
467 if (parse(described.link_type, frame, caplen, ts_ns, out)) {
476 bool next_block(Block &block) {
478 return end_of_stream();
481 std::memcpy(&type, data(),
sizeof(type));
482 if (type == PCAPNG_SECTION) {
484 std::memcpy(&order, data() + 8,
sizeof(order));
485 if (order != PCAPNG_BYTE_ORDER && order != std::byteswap(PCAPNG_BYTE_ORDER)) {
486 error_ =
"a pcapng section without its byte-order magic; the file is corrupt";
489 swapped_ = order != PCAPNG_BYTE_ORDER;
493 const uint32_t length = u32(data() + 4);
494 if (length < 12 || length % 4 != 0 || length > MAX_RECORD_BYTES) {
495 error_ = std::format(
"a pcapng block claims {} bytes; the file is corrupt", length);
499 return end_of_stream();
502 if (
const uint32_t trailing = u32(data() + length - 4); trailing != length) {
503 error_ = std::format(
"a pcapng block of type {} says {} bytes at its start, {} at its end; the file is corrupt",
504 type, length, trailing);
507 block = {type, data() + 8, length - 12};
509 if (type == PCAPNG_SECTION) {
510 if (block.size < 16) {
511 return malformed(
"section header");
513 if (
const uint16_t major = u16(block.body + 4); major != 1) {
514 error_ = std::format(
"pcapng version {} is not read", major);
517 }
else if (type == PCAPNG_INTERFACE) {
518 return describe_interface(block);
523 bool describe_interface(
const Block &block) {
524 if (block.size < 8) {
525 return malformed(
"interface description");
528 described.link_type = u16(block.body);
529 described.snaplen = u32(block.body + 4);
530 const uint8_t *option = block.body + 8;
531 const uint8_t *end = block.body + block.size;
532 while (end - option >= 4) {
533 const uint16_t code = u16(option);
534 const uint16_t length = u16(option + 2);
536 if (code == 0 ||
size_t(end - option) < length) {
539 if (code == 9 && length >= 1) {
540 described.binary = (option[0] & 0x80) != 0;
541 described.exponent =
static_cast<uint8_t
>(option[0] & 0x7f);
542 }
else if (code == 14 && length >= 8) {
543 described.offset_s =
static_cast<int64_t
>(u64(option));
545 option += std::min<size_t>((
size_t(length) + 3) & ~
size_t(3),
size_t(end - option));
547 const size_t index = interfaces_.size();
548 interfaces_.push_back(described);
549 if (!readable(described.link_type)) {
550 error_ = std::format(
"unsupported link type {} on interface {}", described.link_type, index);
553 if (described.exponent > (described.binary ? 63 : 19)) {
554 error_ = std::format(
"interface {} has a timestamp resolution this reader can't use", index);
560 bool malformed(
const char *what) {
561 error_ = std::format(
"a pcapng {} block is malformed; the file is corrupt", what);
567 bool end_of_stream() {
568 if (error_.empty()) {
569 if (!stream_.error().empty()) {
570 error_ = stream_.error();
571 }
else if (end_ > begin_) {
572 error_ = std::format(
"the capture ends {} bytes into a record; the file is truncated", end_ - begin_);
578 bool cut_short() noexcept {
583 bool parse(uint32_t link_type,
const uint8_t *frame,
size_t caplen, uint64_t ts_ns, PcapPacket &out) {
584 const uint8_t *p = frame;
585 size_t left = caplen;
586 if (link_type == LINK_ETHERNET) {
590 uint16_t type =
static_cast<uint16_t
>((p[12] << 8) | p[13]);
593 while ((type == 0x8100 || type == 0x88a8) && left >= 4) {
594 type =
static_cast<uint16_t
>((p[2] << 8) | p[3]);
598 if (type == 0x8100 || type == 0x88a8) {
601 if (type != 0x0800) {
608 if ((p[0] >> 4) != 4) {
611 const size_t ihl =
static_cast<size_t>(p[0] & 0x0f) * 4;
612 const size_t total =
static_cast<size_t>((p[2] << 8) | p[3]);
613 const uint16_t frag =
static_cast<uint16_t
>(((p[6] << 8) | p[7]) & 0x3fff);
615 if (p[9] != 17 || frag != 0) {
618 if (ihl < 20 || left < ihl + 8 || total < ihl + 8) {
621 const uint8_t *udp = p + ihl;
622 const size_t udp_len =
static_cast<size_t>((udp[4] << 8) | udp[5]);
627 size_t payload = udp_len - 8;
628 if (payload > left - ihl - 8) {
632 out.dst_addr = (uint32_t(p[16]) << 24) | (uint32_t(p[17]) << 16) | (uint32_t(p[18]) << 8) | p[19];
633 out.dst_port =
static_cast<uint16_t
>((udp[2] << 8) | udp[3]);
641 bool fill(
size_t n) {
642 if (end_ - begin_ >= n) {
646 std::memmove(buffer_.data(), buffer_.data() + begin_, end_ - begin_);
650 if (n > buffer_.size()) {
651 buffer_.resize(std::bit_ceil(n));
654 const size_t got = stream_.read(buffer_.data() + end_, buffer_.size() - end_);
663 [[nodiscard]]
const uint8_t *data() const noexcept {
return buffer_.data() + begin_; }
664 void consume(
size_t n)
noexcept { begin_ += n; }
666 template <
typename T>
667 [[nodiscard]] T load(
const uint8_t *p)
const noexcept {
669 std::memcpy(&v, p,
sizeof(v));
670 return swapped_ ? std::byteswap(v) : v;
672 [[nodiscard]] uint16_t u16(
const uint8_t *p)
const noexcept {
return load<uint16_t>(p); }
673 [[nodiscard]] uint32_t u32(
const uint8_t *p)
const noexcept {
return load<uint32_t>(p); }
674 [[nodiscard]] uint64_t u64(
const uint8_t *p)
const noexcept {
return load<uint64_t>(p); }
677 detail::CaptureStream stream_;
678 std::vector<uint8_t> buffer_;
681 bool pcapng_ =
false;
682 bool swapped_ =
false;
684 uint32_t link_type_ = 0;
685 std::vector<Interface> interfaces_;
687 uint64_t truncated_ = 0;