Skip to content

Add PCAP input format for reading packet captures - #115453

Open
alexey-milovidov wants to merge 109 commits into
masterfrom
continue-pr-109361-pcap-input-format
Open

alexey-milovidov wants to merge 109 commits into
masterfrom
continue-pr-109361-pcap-input-format

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Adds the PCAP input format with its libpcap/libtins dependencies, documentation, and stateless coverage. This supersedes the deleted-fork PR while preserving the signed original commits and updating it through current master.

Related: #109361

Changelog category:

  • New Feature

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

Add the PCAP input format for reading packet capture files.


Workflow [PR]
Sync PR [sync-upstream/pr/115453]

remogeissbuehler and others added 23 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]>
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]>
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]>
# Conflicts:
#	docs/en/interfaces/formats.md
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e3734a3]

Summary: ✅


AI Review

⚠️ Review sessions stopped as a cybersecurity risk

The model provider stopped these review sessions as a possible cybersecurity risk:

  • attempt 1: gpt-6.1-sol

This summary comes from a session with gpt-5.4. A session is typically stopped when it reaches a memory-safety finding, and the finding is lost with it, so this review can miss a real defect. Please review the change in detail, and run the review internally with a model that has cyber access.

Summary

This PR adds the PCAP input format with vendored libpcap/libtins, fixed-schema docs, and focused stateless coverage across the edge cases raised during the earlier review rounds. I reread the current diff, the parser/build glue, and every existing review thread, and I do not see any remaining correctness, safety, compatibility, or contract gaps that warrant a new ❌ Blockers or ⚠️ Majors finding.

Missing context / blind spots
  • The full CI build matrix is still running; this review covers the current code, the PR discussion, and the already-green style/docs/fast-test checks.
Final Verdict

Status: ✅ Approve
The current implementation looks ready to merge from a code-review perspective.

@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 Aug 19, 2026
Comment thread contrib/libpcap-cmake/linux/config.h Resolved
@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 20, 2026
alexey-milovidov and others added 2 commits November 8, 2026 21:15
`findCutIPHeader` took the protocol of the cut raw tail from `carriedProtocol`,
which does not know `Tins::PPI`, so a raw IP packet (`LINKTYPE_RAW`,
`LINKTYPE_IPV4`, `LINKTYPE_IPV6`) behind a PPI header whose IP header was cut by
the snapshot length lost `ip_version`, the addresses and `ip_protocol`. The link
type named by the PPI header is now interpreted like in `dissectPPI`, sharing
the raw IP version logic with `outerLayerType` via `rawIPLayerType`. Adds the
`truncated_ppi_raw_ip.pcap` fixture.

Addresses review: #115453

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115453&sha=0e5c318dd9263a090b9e7821880538335c5cb957&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20AsyncInsert%2C%20s3%20storage%2C%20parallel) (05325_iceberg_mixed_format_top_k_dynamic_filtering: an <Error> FILE_ALREADY_EXISTS from DB::Iceberg::writeMetadataFile via IcebergStorageSink::initializeMetadata lands in stderr, 1/146 reruns) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is unrelated to the PCAP format. The test_storage_kafka/test_multi_consumer_quota.py TSan failures are fixed on master by #129623, which is now merged into this branch.

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator

Fixed on master by #125026 (mine, merged 2026-11-08 14:11 UTC). A parallel insert that loses the race for v3.metadata.json in IcebergStorageSink::initializeMetadata hits a conditional-write conflict (FILE_ALREADY_EXISTS), and Iceberg::writeMetadataFile now logs that at Debug instead of Error. The failing job ran on 2026-11-07 04:40 UTC, and 0e5c318d does not contain the merge commit cfd94299. CIDB shows no failure of this test anywhere since the merge.

alexey-milovidov and others added 3 commits November 10, 2026 01:02
…sion-header cuts and jumbograms in `PCAP`

- An IEEE 802.3 frame behind 802.1Q tags was handed to `libtins`, whose `Dot1Q`
  takes the length after the tag for an EtherType and keeps the LLC data raw.
  `dissectVlanTaggedDot3` now dissects the LLC (and `SNAP`) data after the tags,
  sharing `appendLLC` with the untagged path, and the fallback for cut frames
  keeps the `SNAP` header after the tags as well.
- Bump `libtins`: an IPv6 extension header with only its first byte captured
  threw `malformed_packet`, discarding the complete headers before it, and the
  Jumbo Payload option value was read from the packet stream instead of the
  options, so a jumbogram's transport header was read 4 bytes too far.
- Test: a Routing header cut after one byte, the `SNAP` IEEE 802.3 frame behind
  a VLAN tag (full and cut inside IPv4), and a 65606-byte UDP jumbogram.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thanks: master merged in 76a778f includes #125026, so the 05325_iceberg_mixed_format_top_k_dynamic_filtering noise should be gone.

This push also addresses the three review blockers (tagged IEEE 802.3 frames, a one-byte IPv6 extension-header cut, IPv6 jumbograms; libtins bumped to fork commit 3883414) with new fixtures, and fixes the arm_tidy cppcoreguidelines-init-variables error in findCutIPHeader. I ran 04498_pcap_input_format and clang-tidy locally and both pass.

alexey-milovidov and others added 2 commits November 11, 2026 02:14
…D_CONTAINERS`

The style check now requires `std` containers in `src` to use a memory-tracking
alternative or be marked explicitly. The lookup table is a process-wide immutable
static, so mark it, and replace `std::call_once` with a plain function-local static
initializer, which is already thread-safe.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115453&sha=76a778fe15180b7ed839c66bb24455751f346335&name_0=PR&name_1=Style%20check
Related: #115453

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (c43326b, clean) and fixed the Style check failure (7c40c64): the new rule for std containers in src flagged the static column lookup table in PCAPBlockInputFormat.cpp. It is now marked with STYLE_CHECK_ALLOW_STD_CONTAINERS, and std::call_once was replaced by a plain function-local static initializer. The translation unit builds locally.

nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 16, 2026
`vectorSimilarityIndexValidator` checked `hnsw_max_connections_per_layer` (M)
and `hnsw_candidate_list_size_for_construction` (ef_construction) only through
usearch's `index_config_t::validate()`, which requires M >= 2 and has no upper
bound. Usearch gives every graph node 2 * M level-0 neighbour slots and
allocates + zeroes them for each added vector (`node_make_`), so M = 2994230
costs 22.84 MiB per indexed row. That memory comes from usearch's mmap-backed
tape allocator and the build loop makes no throwing tracked allocation, so
building such an index never hits `max_server_memory_usage`: the kernel OOM
killer kills the server first. The AST fuzzer reaches it by mutating these two
arguments to `rand() % 2^22 + 1` (`QueryFuzzer::fuzzIndexDeclaration`), seen as
`OOM in dmesg` with invoking thread `VectorSimIndex` on PR ClickHouse#118399 (1f3ca7f)
and PR ClickHouse#115453 (9dca955).

Reject M > 512 and ef_construction > 3200 when an index is defined. These are
Lucene's limits (`Lucene99HnswVectorsFormat.MAXIMUM_MAX_CONN = 512`,
`MAXIMUM_BEAM_WIDTH = 3200`); at M = 512 a node costs ~4 KiB, and every in-tree
test and doc example stays far below (max M 200, max ef_construction 512).

The check is skipped on ATTACH, like the `bloom_filter` validation, so a table
created before this change still loads and its index can be dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 20, 2026 16:24
`master` was bumped to 26.12 after the 26.11 branch cut, so the new
`input_format_pcap_max_block_size` and `input_format_pcap_prefer_block_bytes`
settings now appear first in 26.12.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (147a386, clean merge, the PR scope is unchanged) and moved the history entries of input_format_pcap_max_block_size and input_format_pcap_prefer_block_bytes from 26.11 to 26.12 (e1f763f), since master is now 26.12 after the 26.11 branch cut. The generated settings docs were updated to match.

@stresshouse

stresshouse Bot commented Nov 20, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 28 queries analysed

no significant changes detected. K_source=4 K_base=19 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 451a2b12-808a-4ad0-806a-16b27a307a28
  • MIRAI run: 1e73c768-0875-4854-96e8-b512bfac506d
  • PR check IDs:
    • clickbench_525299_1795200920
    • clickbench_525305_1795200920
    • tpch_adapted_1_official_525342_1795200920
    • tpch_adapted_1_official_525362_1795200920

alexey-milovidov and others added 3 commits November 24, 2026 02:26
The embedded documentation of the `PCAP` format used `:::note` / `:::info`
admonitions. The reference pages are generated from these descriptions as is,
so use the `<Note>` and `<Info>` components instead, as the generated
`docs/reference/formats/PCAP.mdx` already does.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115453&sha=e1f763fa0deab4f521a9d7c997ac4f52964646f1&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
#115453

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The local-file fast path of `PCAPBlockInputFormat` passed
`file_in->getFileName()` to `libpcap`, which opened the path again instead of
reading the already opened `ReadBuffer`. The caller has validated and opened
that file (`file` resolves the path inside `user_files_path`), so reopening by
name could read a different file if a symlink or a rename changed what the name
refers to in between.

Remove the fast path: the capture is now always read through the `FILE *`
backed by the input buffer (`fopencookie`), which was already the path for
every other kind of input.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

This branch was successfully deployed

1 active deployment
staging - docs — e3734a31 Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). 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