Skip to content

Add PCAP input format for reading packet captures - #109361

Closed
remogeissbuehler wants to merge 22 commits into
ClickHouse:masterfrom
remogeissbuehler:pcap-input-format
Closed

remogeissbuehler wants to merge 22 commits into
ClickHouse:masterfrom
remogeissbuehler:pcap-input-format

Conversation

@remogeissbuehler

Copy link
Copy Markdown

Add PCAP input format for reading packet captures

(Human) Introduction

As someone who works with ClickHouse but also occasionally opens a pcap in Wireshark, I've always had a wish to be able to do some quick stats on a pcap using ClickHouse SQL. Especially for large files, I always thought it would also be nice to be able to persist them in a MergeTree, so they don't have to be re-scanned every time.

So this is my first draft at making this a reality: adding PCAP as an (experimental) input format which can be read by Clickhouse directly (and consequently be ingested, as well). It currently only parses very basic stuff (mostly L2-L4), but this could be extended in the future (imagine having all Wireshark dissectors 😍 )

I realize this may be considered "unfinished" (in the sense: lacking features), but I wanted to open a PR and get feedback on the idea early on, to see if it was worth pursuing.

Full transparency: this is basically 100% vibe-coded -- ideas and some design decisions are mine, but I didn't really write any code. Thanks Claude.

In that spirit, here's the Claude-generated description including some notes that may be relevant to reviewers:

AI-generated Overview

Adds a PCAP input format that reads packet capture files (classic pcap and pcapng) and produces one row per packet with decoded L2–L4 fields — timestamp, lengths, link type, the ordered protocol chain, Ethernet/IPv4/IPv6/TCP/UDP header fields, the L4 payload, and the raw frame. Modelled structurally on the DWARF format.

Parsing uses libtins for dissection and libpcap for reading the capture container, added as contrib submodules behind a new USE_PCAP flag (libpcap built offline-only with pre-generated BPF grammar/scanner; WPA2/ACK-tracking disabled to avoid OpenSSL and Boost.ICL). Includes documentation and a stateless test with small Wireshark sample captures.

Transparency note: this PR was vibe-coded with Claude (Anthropic claude-opus-4-8) in an agentic workflow, with human review and direction. The AI co-authorship is recorded via Co-authored-by trailers on the commits.

Notes for reviewers

  • New contrib submodules: libtins (v4.5) and libpcap (1.10.5), gated behind ENABLE_PCAP/USE_PCAP (on by default with ENABLE_LIBRARIES). They use the upstream repositories directly (not ClickHouse forks).
  • libpcap build: built offline-only using the null capture backend (no live capture / remote / optional backends). Its BPF grammar/scanner are pre-generated with bison/flex and checked in under contrib/libpcap-cmake/generated/ so the build needs no flex/bison. A hand-written config.h targets Linux/glibc.
  • libtins build: hand-written config.h; WPA2 decryption and ACK tracking are disabled to avoid pulling in OpenSSL and Boost.ICL for now. Deeper protocol dissection can be layered on later.
  • Disabled-build safety: the format is wrapped in #if USE_PCAP with empty registration stubs, so linking succeeds when the feature is off (e.g. fasttest builds with ENABLE_LIBRARIES=0). The stateless test is tagged no-fasttest for the same reason.
  • Test fixtures license: the capture files under tests/queries/0_stateless/data_pcap/ are sample captures from the Wireshark test suite (GPL-2.0); provenance is recorded in that directory's README.md. Happy to swap them for self-authored synthetic captures if the GPL-2.0 provenance is a concern.

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

New input format PCAP for reading network packet captures (pcap and pcapng), producing one row per packet with decoded Ethernet/IP/TCP/UDP fields, the protocol chain, payload, and raw frame.

remogeissbuehler and others added 6 commits July 3, 2026 18:34
Introduce a new `PCAP` input format that reads packet capture files
(both classic `pcap` and `pcapng`) and produces one row per packet with
decoded L2-L4 header fields, modelled structurally on the `DWARF` format.

The format derives from `IInputFormat` (a block input format) and is
registered via `registerRandomAccessInputFormat`; it supports a subset of
columns. It exposes: `number`, `timestamp` (`DateTime64(9)`),
`capture_length`, `original_length`, `link_type`, `protocols`
(the ordered PDU chain, e.g. `['ETHERNET_II','IP','TCP']`), Ethernet
fields (`eth_src`, `eth_dst`, `eth_type`, `vlan_id`), IP fields
(`ip_version`, `src_addr`/`dst_addr` as IPv4-mapped `IPv6`, `ip_protocol`,
`ip_ttl`), transport fields (`src_port`, `dst_port`, `tcp_flags`,
`tcp_seq`, `tcp_ack`), the L4 `payload`, and the full raw frame `raw`.

Parsing is done with `libtins`, which reads the capture container through
`libpcap`. Both are added as contrib submodules gated behind a new
`USE_PCAP` flag (`ENABLE_PCAP`, on by default with `ENABLE_LIBRARIES`):

- `libpcap` (1.10.5) is built offline-only using the `null` capture
  backend; the BPF grammar/scanner are pre-generated (bison/flex) and
  checked in under `contrib/libpcap-cmake/generated` so no flex/bison is
  needed at build time. A hand-written `config.h` targets Linux/glibc.
- `libtins` (v4.5) is built with a hand-written `config.h`; WPA2
  decryption and ACK tracking are disabled to avoid OpenSSL and Boost.ICL
  dependencies for now. Deeper protocol dissection can be layered on later.

The whole format is wrapped in `#if USE_PCAP` with empty registration
stubs in the disabled branch so linking always succeeds.

Co-authored-by: Claude (Anthropic claude-opus-4-8) <[email protected]>
Add `docs/en/interfaces/formats/PCAP.md` describing the format, its columns,
the `capture_length` vs `original_length` distinction, and example queries,
and list `PCAP` in the formats index table.

Co-authored-by: Claude (Anthropic claude-opus-4-8) <[email protected]>
The read loop previously obtained packets through libtins'
`FileSniffer::next_packet`, which discards the original per-packet pcap
header and re-serializes libtins' parsed view. As a result `raw`,
`capture_length` and `payload` came from `PDU::serialize` (which can differ
from the captured bytes), and `original_length` was merely a copy of the
serialized size rather than the packet's true wire length.

Read packets with libpcap's `pcap_next_ex` instead, using the real
`pcap_pkthdr`:

- `capture_length` = `caplen`, `original_length` = `len` (the on-wire size,
  which exceeds `caplen` when a snapshot length was used),
- `raw` = the exact captured bytes, so `length(raw) == capture_length`,
- `timestamp` from the record header.

The raw bytes are then dissected with `Tins::Internals::pdu_from_dlt_flag`
using the sniffer's datalink type. This makes the identity
`substring(raw, capture_length - payload_length + 1) == payload` hold, as
documented (verified across the whole example capture).

Co-authored-by: Claude (Anthropic claude-opus-4-8) <[email protected]>
Capture files are read with microsecond precision (libtins' file sniffer
opens savefiles that way), so nanosecond-resolution captures are truncated
to microseconds even though the `timestamp` column has a `DateTime64(9)`
type. Note this in the format documentation.

Co-authored-by: Claude (Anthropic claude-opus-4-8) <[email protected]>
Add a "Storing captures in a table" section to the PCAP format docs showing
how to create a `MergeTree` table and `INSERT ... SELECT` from a capture file.
Explain that storing both `raw` and `payload` is redundant because the payload
is a suffix of the raw frame
(`substring(raw, (capture_length - payload_length) + 1) = payload`), and give
guidance on choosing a sorting key for flow-oriented vs time-series analysis,
including the `MergeTree` restriction on nullable columns in the key.

Co-authored-by: Claude (Anthropic claude-opus-4-8) <[email protected]>
Add `04498_pcap_input_format.sh` covering the `PCAP` format against four small
capture fixtures (classic `pcap` and `pcapng`): an HTTP/TCP packet, a DHCP/UDP
exchange, ICMP echo packets, and a TLS session. The test checks the schema,
decoded L2-L4 fields, the protocol chain, subset-of-columns reads, and the
`length(raw) == capture_length` / `original_length >= capture_length` /
`substring(raw, capture_length - payload_length + 1) == payload` invariants.

Tagged `no-fasttest` because the format requires libtins/libpcap, which are not
built in fasttest (`ENABLE_LIBRARIES=0`).

The fixtures are sample captures from the Wireshark test suite
(https://github.com/wireshark/wireshark/tree/master/test/captures); their
provenance is recorded in `data_pcap/README.md`.

Co-authored-by: Claude (Anthropic claude-opus-4-8) <[email protected]>
@CLAassistant

CLAassistant commented Jul 3, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

The `PCAP` input format only reads capture files and never calls
`pcap_compile`, so the BPF filter compiler (`gencode.c` and its bison/flex
grammar/scanner) was dead code that existed only to satisfy the linker. Drop it
from the build entirely. This also removes the checked-in bison output
`grammar.c`, whose GPL-licensed header is incompatible with ClickHouse's Apache
2.0 licensing.

The read path (`savefile.c`, `sf-pcap.c`, `sf-pcapng.c`, `pcap.c`, `optimize.c`)
does not depend on `gencode.c`; it only needs `pcap_freecode` and the BPF
interpreter in `bpf_filter.c`. A new `compile-stub.c` provides minimal
`pcap_compile` / `pcap_compile_nopcap` stubs that return `PCAP_ERROR`, plus the
genuine grammar-independent `pcap_freecode`, so the static archive links
cleanly.

Verified: the full `clickhouse` binary links, and `04498_pcap_input_format`
produces output identical to its reference (classic `pcap` and `pcapng` HTTP,
DHCP, ICMP, and TLS fixtures decode correctly).

Co-authored-by: Claude (Anthropic claude-opus-4-8) <[email protected]>
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [52ac581]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy) FAIL
Check Submodules FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED

AI Review

Summary

This PR adds a new PCAP input format backed by bundled libpcap/libtins, plus docs and stateless tests. The shape is reasonable, but the current implementation still has merge-blocking correctness and repository-hygiene issues: it silently drops packets it cannot dissect, mixes outer and inner protocol layers on encapsulated traffic, and adds GPL-2.0 Wireshark fixtures to the tree.

Missing context / blind spots
  • ⚠️ I did not have a local build artifact to execute the new format, and the visible CI run stopped after Check Submodules, so I could not validate the runtime behavior on non-Linux builds. A successful build/test matrix would close that gap.
Findings
❌ Blockers
  • [tests/queries/0_stateless/data_pcap/README.md:16] The PR still commits Wireshark-derived GPL-2.0 packet captures into the repository. Even though they are data fixtures, they ship in every source distribution and create a license provenance problem for the tree itself. Replace them with self-authored or otherwise license-compatible captures before merge.
  • [src/Processors/Formats/Impl/PCAPBlockInputFormat.cpp:332] The format promises one row per packet, but undecodable packets are silently skipped with continue. That undercounts count(), makes number stop matching the packet index in the capture, and gives the caller no signal that data disappeared. Emit a raw-only row with NULL decoded fields or throw an exception instead of dropping packets.
  • [src/Processors/Formats/Impl/PCAPBlockInputFormat.cpp:450-460] find_pdu<TCP> / find_pdu<UDP> recurse through the whole encapsulation chain, while the address fields come from the first IP header found earlier. On tunneled packets (GRE, IP-in-IP, VXLAN, etc.) that produces rows that mix outer addresses with inner transport metadata and can even report ip_protocol = 'TCP' for an outer GRE packet. The scalar IP/transport fields need to come from one consistent layer.
⚠️ Majors
  • [src/Processors/Formats/Impl/PCAPBlockInputFormat.cpp:191] The non-local fallback buffers the whole stream with copyData(..., nullptr), so canceling the query cannot stop the copy and large remote captures continue being pulled into RAM until EOF. Add cancellation-aware buffering (onCancel + is_stopped) or explicitly reject non-seekable inputs instead of silently slurping them.
  • [src/Processors/Formats/Impl/PCAPBlockInputFormat.cpp:110-116] eth_type and ip_protocol use empty string as the "layer absent" sentinel even though neighboring layer-specific fields are nullable and the docs say such columns are Nullable. That gives the format two different missing-value conventions and makes IS NULL predicates wrong for non-IP or non-Ethernet packets. Make them Nullable(LowCardinality(String)) or document/test the empty-string contract explicitly.
💡 Nits
  • [contrib/CMakeLists.txt:177-179], [contrib/libpcap-cmake/linux/config.h:1-15], [src/Processors/Formats/Impl/PCAPBlockInputFormat.cpp:194] ENABLE_PCAP is wired on for every library-enabled build, but the bundled libpcap config is explicitly Linux/glibc-specific and the fallback path uses fmemopen, which is also non-portable. CI should catch that class of build break, so I am not blocking review on it here, but the feature needs Linux-only gating or a portable non-local input path.
Tests
  • ⚠️ Add a focused capture with a malformed or unsupported top-level frame and assert that the reader either emits a raw-only row or throws. The current tests only cover packets that libtins dissects cleanly.
  • ⚠️ Add a tunneled capture (GRE, IP-in-IP, or VXLAN) and assert that the scalar IP and transport columns come from a single encapsulation layer consistently.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    • Replace the GPL-2.0 fixtures with license-compatible captures.
    • Stop silently dropping undecodable packets.
    • Make the scalar IP/transport columns follow one encapsulation layer consistently.
    • Fix or narrow the non-local input behavior around buffering/cancellation and missing-value semantics.

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR. labels Jul 3, 2026
The style check rejects `Tcp` because abbreviations such as `TCP` must be
in all caps. Rename `formatTcpFlags` to `formatTCPFlags`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109361&sha=74c448c7a58747b922b788b06a155ac2e31616bc&name_0=PR&name_1=Style%20check

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 10, 2026
@alexey-milovidov
alexey-milovidov requested a review from a team as a code owner August 2, 2026 00:33
# Conflicts:
#	docs/en/interfaces/formats.md
@alexey-milovidov alexey-milovidov added the pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard label Aug 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #115453 because the source fork is no longer available, so its branch cannot be updated. The replacement preserves the signed original commits, incorporates current master, and retains credit to @remogeissbuehler. Thank you for the contribution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors manual approve Manual approve required to run CI pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants