# mozillazg/ptcpdump architecture

> Architecture diagram of the GitHub repository mozillazg/ptcpdump, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-18). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/mozillazg/ptcpdump
- Repository: https://github.com/mozillazg/ptcpdump

## Overview

1. **What this repo is**
   ptcpdump is a Linux-only, Go-based tcpdump-compatible CLI. Its core architecture is a packet-capture pipeline built on eBPF, with optional enrichment from host, process, container, and Kubernetes metadata. The repo is split between Go control-plane code and C eBPF data-plane code.

2. **Top-level control plane**
   `main.go` and the `cmd/` package form the CLI surface. This is where flags like `-i`, `-r`, `-w`, `--backend`, `--pid`, `--container-id`, `--pod-name`, `--netns`, and the `-- command [args]` mode are interpreted. The command layer dispatches into live capture, reading saved files, listing interfaces, version/prog info, and related subcommands.

3. **Capture pipeline**
   The live-capture path is centered in `internal/capturer/` and the `bpf/` package. At startup, the CLI selects a backend and attaches the corresponding eBPF program(s) to interfaces, cgroups, sockets, or tracing hooks. Captured packets and related events are then pushed back into Go through the BPF event bridge and processed asynchronously.

4. **eBPF data plane**
   The `bpf/` directory contains the C sources, headers, and generated Go bindings/bytecode blobs for multiple architectures (`amd64`, `arm64`, `arm`) and backend variants. The repository embeds prebuilt `.o` artifacts and uses kernel BTF/CO-RE support where available. This is the low-level layer that actually observes packets and emits metadata needed by the Go side.

5. **Backend boundary**
   The repo supports four capture backends: `tc`, `cgroup-skb`, `socket-filter`, and `tp-btf`. They share the same downstream Go pipeline, but differ in where packets are observed and what metadata is available. This boundary matters architecturally because backend choice changes namespace visibility, L2 access, and kernel requirements, but not the CLI/output model.

6. **Event and consumer model**
   `internal/event/`, `bpf/event.go`, and `internal/consumer/` define the event flow between kernel and user space. Packet events are distinct from process-exec/exit/keylog/net events, and consumers update state caches or side effects as those events arrive. This is the mechanism that lets ptcpdump correlate a packet with the process, thread, parent process, container, or pod that produced it.

7. **Metadata enrichment**
   `internal/metadata/` is the main enrichment subsystem. It resolves process identity, network namespace, device identity, container membership, and Kubernetes pod context by combining kernel-visible IDs with host-side lookups. Container support is split across Docker, containerd, and generic CRI paths, with a `multiple.go` layer to try multiple runtimes. This is the major boundary between packet capture and human-readable context.

8. **Process and namespace correlation**
   `internal/metadata/process.go`, `internal/metadata/netns.go`, `internal/metadata/net.go`, and the `internal/utils/` helpers support mapping kernel observations back to host processes and namespaces. The README’s `--pid`, `--pname`, `--uid`, `--follow-forks`, and `--netns` flags are implemented through this correlation layer rather than by packet parsing alone.

9. **Packet parsing and read mode**
   `internal/parser/` handles decoding of saved captures, including pcap and pcapng. This powers `-r/--read-file` and also supports replaying previously captured traffic with the same formatting and filtering behavior. In other words, reading files and live capture converge into the same presentation pipeline after the parsing stage.

10. **Output and persistence**
    `internal/writer/` contains the sinks: stdout formatting, raw pcap, pcapng, keylog output, and rotation support. The output subsystem is separate from capture so the same packet stream can be printed, saved, rotated, or piped to downstream tools. PcapNG is the richer format because it can carry embedded metadata and is Wireshark-ready.

11. **Filter model**
    Filtering is not only tcpdump-style `pcap-filter(7)` expressions. ptcpdump also adds higher-level filters for process/container/pod identity, and some of those are enforced through runtime metadata matching rather than kernel packet matching. The README’s emphasis on kernel-space BPF filtering shows that the system intentionally splits filters between data-plane reduction and user-space correlation.

12. **Build and packaging boundaries**
    The repository is designed to ship as a mostly static binary. It bundles `libpcap` from `lib/libpcap`, precompiles eBPF objects, and supports Docker-based builds for both the Go binary and the BPF bytecode. Release and CI automation live in `.github/workflows/`, `.circleci/`, and `.goreleaser.yml`, which are important for reproducible native builds but not part of the runtime path.

13. **Test/integration coverage**
    `testdata/` contains sample captures and many shell-based end-to-end scenarios for Docker, containerd, Kubernetes, netns, NAT, TLS keylog, and output formatting. This reflects the repo’s main integration risks: backend-specific capture correctness, runtime metadata correctness, and stable output formatting across capture/read modes.

14. **Diagram-friendly mental model**
    A useful architecture diagram is: CLI and flags at the top; backend selection and BPF attachment in the middle; event ingestion plus metadata enrichment on the Go side; then parser/writer/output at the bottom. The main external dependencies that materially shape the design are the Linux kernel eBPF/BTF subsystem, container runtimes (Docker/containerd/CRI), and the bundled libpcap library.

Main entry points: [`cmd/root.go`](https://github.com/mozillazg/ptcpdump/blob/master/cmd/root.go) (Root cmd), [`internal/metadata/container.go`](https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/container.go) (Metadata), [`internal/capturer/capturer.go`](https://github.com/mozillazg/ptcpdump/blob/master/internal/capturer/capturer.go) (Capturer), [`internal/writer/writer.go`](https://github.com/mozillazg/ptcpdump/blob/master/internal/writer/writer.go) (Writer)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_cli["CLI"]
  node_main["main<br/>entrypoint<br/>[main.go]"]
  node_cmd_root["Root cmd<br/>cli<br/>[root.go]"]
  node_cmd_opts["Options<br/>cli flags<br/>[options.go]"]
  node_cmd_capture["Capture cmd<br/>live mode<br/>[capture.go]"]
  node_cmd_read["Read cmd<br/>replay mode<br/>[read.go]"]
  node_cmd_tools["Tool cmds<br/>aux commands<br/>[list.go]"]
end

subgraph group_capture["Capture"]
  node_capturer["Capturer<br/>pipeline<br/>[capturer.go]"]
  node_backend{{"Backend<br/>attach layer<br/>[backend.go]"}}
  node_event["Event bus<br/>async events<br/>[process.go]"]
end

subgraph group_kernel["eBPF"]
  node_bpf_bridge["BPF bridge<br/>event bridge<br/>[bpf.go]"]
  node_bpf_events["Kernel events<br/>event schema<br/>[event.go]"]
  node_bpf_prog["BPF prog<br/>c/eBPF<br/>[ptcpdump.c]"]
  node_bpf_variants["Variants<br/>arch/backend builds<br/>[bpf_x86_bpfel.go]"]
end

subgraph group_enrich["Enrichment"]
  node_consumer["Consumers<br/>state updaters<br/>[exec.go]"]
  node_metadata["Metadata<br/>enrichment<br/>[container.go]"]
  node_process["Process map<br/>correlation<br/>[process.go]"]
  node_netns["Netns map<br/>correlation<br/>[netns.go]"]
  node_container["Container map<br/>runtime lookup<br/>[multiple.go]"]
  node_k8s["K8s lookup<br/>pod context<br/>[cri.go]"]
end

subgraph group_io["I/O"]
  node_parser["Parser<br/>pcap decode<br/>[parser.go]"]
  node_writer["Writer<br/>output sink<br/>[writer.go]"]
  node_pcapng["PcapNG<br/>output format<br/>[pcapng.go]"]
  node_stdout["Stdout<br/>human output<br/>[stdout.go]"]
end

subgraph group_support["Support"]
  node_libpcap[("libpcap<br/>embedded lib")]
  node_btf["BTF utils<br/>kernel support<br/>[btf.go]"]
  node_host["Host utils<br/>system access<br/>[host.go]"]
end

node_main -->|"starts"| node_cmd_root
node_cmd_root -->|"parses"| node_cmd_opts
node_cmd_root -->|"live mode"| node_cmd_capture
node_cmd_root -->|"read mode"| node_cmd_read
node_cmd_root -->|"aux commands"| node_cmd_tools
node_cmd_capture -->|"selects"| node_backend
node_cmd_capture -->|"runs"| node_capturer
node_capturer -->|"loads"| node_bpf_bridge
node_bpf_bridge -->|"executes"| node_bpf_prog
node_bpf_bridge -->|"binds"| node_bpf_variants
node_bpf_prog -->|"emits"| node_bpf_events
node_bpf_events -->|"delivers"| node_event
node_event -->|"fan-out"| node_consumer
node_consumer -->|"updates"| node_metadata
node_metadata -->|"resolves"| node_process
node_metadata -->|"resolves"| node_netns
node_metadata -->|"resolves"| node_container
node_container -->|"extends"| node_k8s
node_cmd_read -->|"decodes"| node_parser
node_capturer -->|"streams"| node_writer
node_parser -->|"formats"| node_writer
node_writer -->|"prints"| node_stdout
node_writer -->|"writes"| node_pcapng
node_writer -->|"filters"| node_libpcap
node_capturer -->|"checks"| node_btf
node_metadata -->|"queries"| node_host
node_backend -->|"configures"| node_capturer

click node_main "https://github.com/mozillazg/ptcpdump/blob/master/main.go"
click node_cmd_root "https://github.com/mozillazg/ptcpdump/blob/master/cmd/root.go"
click node_cmd_opts "https://github.com/mozillazg/ptcpdump/blob/master/cmd/options.go"
click node_cmd_capture "https://github.com/mozillazg/ptcpdump/blob/master/cmd/capture.go"
click node_cmd_read "https://github.com/mozillazg/ptcpdump/blob/master/cmd/read.go"
click node_cmd_tools "https://github.com/mozillazg/ptcpdump/blob/master/cmd/list.go"
click node_capturer "https://github.com/mozillazg/ptcpdump/blob/master/internal/capturer/capturer.go"
click node_backend "https://github.com/mozillazg/ptcpdump/blob/master/internal/types/backend.go"
click node_bpf_bridge "https://github.com/mozillazg/ptcpdump/blob/master/bpf/bpf.go"
click node_bpf_events "https://github.com/mozillazg/ptcpdump/blob/master/bpf/event.go"
click node_bpf_prog "https://github.com/mozillazg/ptcpdump/blob/master/bpf/ptcpdump.c"
click node_bpf_variants "https://github.com/mozillazg/ptcpdump/blob/master/bpf/bpf_x86_bpfel.go"
click node_event "https://github.com/mozillazg/ptcpdump/blob/master/internal/event/process.go"
click node_consumer "https://github.com/mozillazg/ptcpdump/blob/master/internal/consumer/exec.go"
click node_metadata "https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/container.go"
click node_process "https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/process.go"
click node_netns "https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/netns.go"
click node_container "https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/container/multiple.go"
click node_k8s "https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/k8s/cri.go"
click node_parser "https://github.com/mozillazg/ptcpdump/blob/master/internal/parser/parser.go"
click node_writer "https://github.com/mozillazg/ptcpdump/blob/master/internal/writer/writer.go"
click node_pcapng "https://github.com/mozillazg/ptcpdump/blob/master/internal/writer/pcapng.go"
click node_stdout "https://github.com/mozillazg/ptcpdump/blob/master/internal/writer/stdout.go"
click node_libpcap "https://github.com/mozillazg/ptcpdump/tree/master/lib/libpcap"
click node_btf "https://github.com/mozillazg/ptcpdump/blob/master/internal/btf/btf.go"
click node_host "https://github.com/mozillazg/ptcpdump/blob/master/internal/host/host.go"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_cmd_root,node_cmd_opts,node_cmd_capture,node_cmd_read,node_cmd_tools toneBlue
class node_capturer,node_backend,node_event toneAmber
class node_bpf_bridge,node_bpf_events,node_bpf_prog,node_bpf_variants toneMint
class node_consumer,node_metadata,node_process,node_netns,node_container,node_k8s toneRose
class node_parser,node_writer,node_pcapng,node_stdout toneIndigo
class node_libpcap,node_btf,node_host toneTeal
```

## Components

### CLI

Command parsing, subcommands, and user-facing entry points

- [main](https://github.com/mozillazg/ptcpdump/blob/master/main.go): entrypoint · Program entry and CLI bootstrap · `main.go`
- [Root cmd](https://github.com/mozillazg/ptcpdump/blob/master/cmd/root.go): cli · Top-level command wiring and mode dispatch · `cmd/root.go`
- [Options](https://github.com/mozillazg/ptcpdump/blob/master/cmd/options.go): cli flags · Flag parsing and command configuration · `cmd/options.go`
- [Capture cmd](https://github.com/mozillazg/ptcpdump/blob/master/cmd/capture.go): live mode · Live capture execution and backend selection · `cmd/capture.go`
- [Read cmd](https://github.com/mozillazg/ptcpdump/blob/master/cmd/read.go): replay mode · Reads saved captures and routes them through formatting · `cmd/read.go`
- [Tool cmds](https://github.com/mozillazg/ptcpdump/blob/master/cmd/list.go): aux commands · Interface listing, version, BPF info, logging, and container helpers · `cmd/list.go`

### Capture

Live packet capture and backend attachment

- [Capturer](https://github.com/mozillazg/ptcpdump/blob/master/internal/capturer/capturer.go): pipeline · Orchestrates backend attachment and packet collection · `internal/capturer/capturer.go`
- [Backend](https://github.com/mozillazg/ptcpdump/blob/master/internal/types/backend.go): attach layer · Selects and configures tc, cgroup-skb, socket-filter, or tp-btf capture path · `internal/types/backend.go`
- [Event bus](https://github.com/mozillazg/ptcpdump/blob/master/internal/event/process.go): async events · User-space event dispatch for packet, exec, exit, and net events · `internal/event/process.go`

### eBPF

Kernel-space program variants and generated artifacts

- [BPF bridge](https://github.com/mozillazg/ptcpdump/blob/master/bpf/bpf.go): event bridge · Go-side bridge to BPF programs and generated bindings · `bpf/bpf.go`
- [Kernel events](https://github.com/mozillazg/ptcpdump/blob/master/bpf/event.go): event schema · Packet and auxiliary event definitions shared with user space · `bpf/event.go`
- [BPF prog](https://github.com/mozillazg/ptcpdump/blob/master/bpf/ptcpdump.c): c/eBPF · Core packet-observation programs and helper code · `bpf/ptcpdump.c`
- [Variants](https://github.com/mozillazg/ptcpdump/blob/master/bpf/bpf_x86_bpfel.go): arch/backend builds · Prebuilt program blobs and per-architecture/generated wrappers · `bpf/bpf_x86_bpfel.go`

### Enrichment

Process, container, netns, and Kubernetes correlation

- [Consumers](https://github.com/mozillazg/ptcpdump/blob/master/internal/consumer/exec.go): state updaters · Consumes exec/exit/keylog/net events and updates local state · `internal/consumer/exec.go`
- [Metadata](https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/container.go): enrichment · Resolves human-readable packet context from kernel-visible identifiers · `internal/metadata/container.go`
- [Process map](https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/process.go): correlation · Maps packets to processes, users, forks, and parents · `internal/metadata/process.go`
- [Netns map](https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/netns.go): correlation · Maps traffic to network namespaces and device context · `internal/metadata/netns.go`
- [Container map](https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/container/multiple.go): runtime lookup · Container and runtime identity resolution across Docker, containerd, and CRI · `internal/metadata/container/multiple.go`
- [K8s lookup](https://github.com/mozillazg/ptcpdump/blob/master/internal/metadata/k8s/cri.go): pod context · Kubernetes pod and CRI metadata resolution · `internal/metadata/k8s/cri.go`

### I/O

Parsing, formatting, and output sinks

- [Parser](https://github.com/mozillazg/ptcpdump/blob/master/internal/parser/parser.go): pcap decode · Decodes saved captures in pcap and pcapng formats · `internal/parser/parser.go`
- [Writer](https://github.com/mozillazg/ptcpdump/blob/master/internal/writer/writer.go): output sink · Routes packet streams to stdout, files, rotation, and keylog sinks · `internal/writer/writer.go`
- [PcapNG](https://github.com/mozillazg/ptcpdump/blob/master/internal/writer/pcapng.go): output format · Rich capture format with metadata-friendly output · `internal/writer/pcapng.go`
- [Stdout](https://github.com/mozillazg/ptcpdump/blob/master/internal/writer/stdout.go): human output · Tcpdump-style terminal formatting · `internal/writer/stdout.go`

### Support

Shared helpers and runtime support

- [libpcap](https://github.com/mozillazg/ptcpdump/tree/master/lib/libpcap): embedded lib · Bundled packet capture library and filter support · `lib/libpcap`
- [BTF utils](https://github.com/mozillazg/ptcpdump/blob/master/internal/btf/btf.go): kernel support · BTF/CO-RE detection and helpers · `internal/btf/btf.go`
- [Host utils](https://github.com/mozillazg/ptcpdump/blob/master/internal/host/host.go): system access · Host and namespace helper functions · `internal/host/host.go`

## Connections

- main → Root cmd: starts · Bootstraps the CLI and hands off to root command handling
- Root cmd → Options: parses · Loads flags and run configuration
- Root cmd → Capture cmd: live mode · Dispatches to live capture execution
- Root cmd → Read cmd: read mode · Dispatches to saved-capture replay
- Root cmd → Tool cmds: aux commands · Handles listing, versioning, and other utility commands
- Capture cmd → Backend: selects · Chooses the observation backend and attach target
- Capture cmd → Capturer: runs · Starts the live capture pipeline
- Capturer → BPF bridge: loads · Loads and attaches generated BPF artifacts
- BPF bridge → BPF prog: executes · Runs the kernel-space packet observation logic
- BPF bridge → Variants: binds · Uses architecture and backend-specific program variants
- BPF prog → Kernel events: emits · Produces packet and auxiliary events for user space
- Kernel events → Event bus: delivers · Events are consumed asynchronously in Go
- Event bus → Consumers: fan-out · Dispatches exec, exit, keylog, and net event consumers
- Consumers → Metadata: updates · Maintains state used for later enrichment
- Metadata → Process map: resolves · Correlates packets to process identity
- Metadata → Netns map: resolves · Correlates packets to namespaces and devices
- Metadata → Container map: resolves · Adds container/runtime identity
- Container map → K8s lookup: extends · Derives pod context through CRI and Kubernetes metadata
- Read cmd → Parser: decodes · Reads pcap/pcapng files into the shared pipeline
- Capturer → Writer: streams · Sends captured packets to output sinks
- Parser → Writer: formats · Feeds replayed packets into the same presentation/output layer
- Writer → Stdout: prints · Human-readable tcpdump-style output
- Writer → PcapNG: writes · Produces richer capture files and metadata-aware output
- Writer → libpcap: filters · Uses bundled libpcap support for capture/filter semantics
- Capturer → BTF utils: checks · Detects BTF/CO-RE capability for supported backends
- Metadata → Host utils: queries · Uses host-side lookups and namespace helpers
- Backend → Capturer: configures · Backend choice shapes attachment and kernel visibility
