Metadata-Version: 2.3
Name: zelos-packet
Version: 0.1.0
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Rust
Classifier: License :: Other/Proprietary License
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Requires-Dist: zelos-sdk >=0.0.12a1
Summary: Rust-first packet capture and decode for the Zelos ecosystem. Live capture through a bundled libpcap helper process, with pcap/pcapng offline decode.
Author-email: Zelos Cloud <info@zeloscloud.io>
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# zelos-packet

Rust-first packet capture and decode for the Zelos ecosystem: live capture
through a bundled helper process (`AF_PACKET` on Linux, `/dev/bpf` on macOS,
Npcap on Windows), plus pcap/pcapng offline decode, emitting packet and
capture-statistics events into a Zelos trace.

On Linux and macOS the helper links libpcap **statically**, so the wheel has no
runtime dependency on a system `libpcap`; the extension module links none at
all. On Windows the helper delay-loads the user's own Npcap. Live capture
needs a one-time grant, or on Windows the Npcap install (below); offline decode
needs none.

```bash
pip install zelos-packet
```

## Offline

```python
import zelos_packet, zelos_sdk

with zelos_sdk.TraceWriter("capture.trz"):
    d = zelos_packet.PacketDecoder("dump")
    d.convert_file("dump.pcap")     # or d.decode_stream(raw_bytes)
    # rows land at Packet.dump/packets.<field>
```

`convert_file(path, realtime=True)` replays at the capture's own pace, shifted so the first packet lands at now.
Both read gzip or zstd compressed captures directly, detected by magic bytes, decompressed as a stream. A compressed file that stops decoding part-way (cut short, corrupt) keeps every packet before the damage, then raises `CaptureTruncatedError`.

## Live

```python
# The helper streams to this agent; rows are read back from there, never from
# a local TraceWriter. Defaults to $ZELOS_AGENT_URL, else localhost:2300.
cap = zelos_packet.PacketCapture("en0", snaplen=128, agent_url="http://localhost:2300")
cap.start()                        # rows land at Packet.en0/packets.<field>
print(cap.stats().kernel_drops, cap.metrics().emit_stall_ms)
cap.stop()
```

`filter=` takes a libpcap expression applied in the kernel, AND-ed with the [self-traffic exclusion](#self-traffic-exclusion) and never replacing it: `filter="ether proto 0x88b8 or (vlan and ether proto 0x88b8)"` keeps GOOSE and drops Sampled Values before a frame is copied out.

```bash
sudo "$(command -v python3)" -m zelos_packet install-helper   # once per machine
python3 -m zelos_packet status                                # would capture work now?
```

Then pick the group up. **Linux** stamps a session's group set at login
(`initgroups`), so log out and back in. **macOS** resolves membership per
process, so a fresh terminal is enough. Either way, anything already running
(this shell, a running Zelos app) keeps the group set it started with.

| Platform | What `install-helper` does | What the group grants |
| --- | --- | --- |
| Linux | Installs the helper to a root-owned path with `cap_net_raw=ep` (never `CAP_NET_ADMIN`) and creates/joins `zelos-packet` | The ability to *run a capture*. The helper opens the socket, drops every capability, verifies the drop from `/proc/self/status`, and only then reads. It never hands out the socket, so **not** frame injection. |
| macOS | Installs a ChmodBPF-style boot daemon putting `/dev/bpf*` in `access_bpf` | Capture **and sending** arbitrary frames — a bpf device is opened read-write and capture needs the write side, exactly as for Wireshark. |
| Windows | Nothing to install: prints the Npcap prerequisite and exits 3. `status` reads the Npcap state (present, driver running, version, Admin-only mode). | Npcap's driver holds the privilege (the dumpcap model); every local user can capture unless Npcap was installed in Admin-only mode. |

`zelos_packet.permission_remediation()` returns the same text a failed open
raises inside `CapturePermissionError`.

### Windows: Npcap

Live capture on Windows needs [Npcap](https://npcap.com) installed by you, with
the default options. The wheel ships nothing of it: the helper links the free
Npcap SDK's import library and loads `%SystemRoot%\System32\Npcap\wpcap.dll`
by full path at run time (a WinPcap left on `PATH` by another tool is never
picked up). Opening a pcap file does not need Npcap.

| | |
| --- | --- |
| License | Npcap's free edition allows five installs per organization; more needs an Npcap OEM license. Nothing of Npcap is redistributed here. |
| Version | **1.82 or newer** keeps 802.1Q VLAN tags on captured frames. Older Npcap strips them: `status` warns, GOOSE decode (`goose=True`) refuses. |
| Interface names | `\Device\NPF_{GUID}`, with `InterfaceInfo.description` carrying `"Ethernet 5 (Intel(R) Ethernet Controller I225-V)"`; pass the name. |
| Timestamps | `host_hiprec`, synced to the system clock; reported as `tstamp_type` on the helper's `started` line. |
| Intel NICs | For tagged frames (GOOSE on a VLAN), set the adapter's *Priority & VLAN* to **Disabled** in Device Manager, or the driver strips the tag before Npcap sees it. |
| Wi-Fi | Promiscuous mode is refused by Wi-Fi adapters on Windows; capture them with the default `promiscuous=False`. |
| Admin-only | An Npcap installed with *Restrict to Administrators* needs the agent to run elevated, or a reinstall without that option. |

### One capture path: the helper

`zelos-packet-helper` runs every live capture on both platforms. It opens the
handle, drops every capability it holds, and streams decoded rows straight to
an agent; `PacketCapture` supervises that process and nothing else. No packet
enters the calling process, so capture privilege never lands on the interpreter
and no capture-capable descriptor is handed out.

- **`source=` is a hard error.** Rows are produced behind the helper's own SDK
  connection, so nothing would reach a source passed here. Use `agent_url=`.
- **An agent must be reachable** for rows to land anywhere. A local
  `TraceWriter` sees nothing.
- **Constructing is not starting.** `PacketCapture(...)` validates the
  interface name, resolves the agent exclusion, and locates a runnable helper,
  so a typo, an unresolvable agent host, or a missing helper raises *there*.
  The *permission* verdict comes from `start()`, where the helper opens the
  handle. (zelos-can starts from its constructor; this does not.)

## Catalog layout

Every capture writes into ONE trace source, `Packet`, and is told apart by its
own event-name prefix, so a field is addressed `Packet.en0/packets.src_ip`:

```
Packet
├── en0                      # the capture's `name`; defaults to the interface
│   ├── packets              # zelos.packet.v1 — one row per frame
│   ├── stats                # zelos.packet.stats.v1 — one row per interval
│   ├── someip               # one row per SOME/IP message (SD included)
│   ├── someip_sd            # one row per SOME/IP-SD entry
│   ├── doip                 # one row per DoIP message
│   ├── pdu                  # one row per SoAd PDU (ARXML PDU sockets)
│   ├── goose                # with goose=: one row per GOOSE frame
│   ├── slac                 # with v2g=: one row per HomePlug AV MME
│   ├── sdp                  # with v2g=: one row per SDP message
│   ├── v2gtp                # with v2g=: one row per V2GTP message
│   ├── <Message>            # with v2g=: one row per decoded message (CurrentDemandReq, DC_ChargeLoopReq, ...)
│   └── can
│       └── <iface>          # zelos.can.frame.v1 — one row per SocketCAN frame
└── <LD>/<LN>/GO/<gcb>       # with goose=: one event per GOOSE control block
SOMEIP                       # with arxml=: ARXML-decoded SOME/IP payloads
└── <Service>/<Element>      # one event per event, method, field
PDU                          # with arxml=: ARXML-decoded SoAd PDUs
└── <PDU>                    # one event per SoAd signal PDU, by short-name
```

The automotive rows appear only for traffic on the ports given, all off by
default: SOME/IP-SD on `someip_sd_port` (customarily 30490), DoIP on
`doip_port` (customarily 13400), SOME/IP on the ports SD offers, the ARXML
names, or `someip_ports` lists. The `pkt` row of such a packet reads
`SOME/IP`, `SOME/IP-SD` or `DoIP` in `proto`; with nothing given, `pkt` rows
are as before.

| Topic | Behavior |
| --- | --- |
| Messages | several per datagram or TCP segment, walked by Length; a TCP direction's bytes carry over between segments, a sequence gap resyncs |
| SOME/IP-TP | segments are rows; the reassembled original is one more row (TP flag cleared, `tp_offset` null); ascending order only, a gap drops the message, 1 MiB cap |
| `instance_id` | from SD offers (endpoint) and acks (multicast), and ARXML provided instances; null when unknown |
| `arxml=` | R19-11 / R4.2 SOME/IP service interface deployments; payloads per PRS SOME/IP serialization; one event per method and field with `message_type`, `session_id`, `client_id`, `return_code`, `instance_id` (fields add `method_id`) |
| Leaves | nested members join with `_`; fixed arrays up to 16 flatten to `name_<i>`; longer and dynamic arrays are a bytes column plus `name_count`; unions add `name_selector` |
| SoAd PDUs | PDUs behind a SoAd header on an ARXML PDU socket decode through the CAN PDU pipeline into `PDU/<PDU>`, e.g. `PDU/DemoPdu`: `header_id`, `src_ip`, `src_port`, `dst_ip`, `dst_port`, the signals, then `e2e_status` (E2E profiles 1, 2, 4, 5, 6, 7, 11, 22) and `secoc` (`unverified`); contained and dynamic PDUs as `<PDU>/<PDU>`; two SoAd PDUs with one short-name are a load error; `pdu_signal_rows`, `pdu_decode_errors` |
| Not decoded | a payload that does not fit its type (counted in `someip_malformed`); ids the ARXML lacks (`someip_unknown`, warned once); labels on a float-typed PDU signal |

Pass `name=` to override the prefix; it goes through `sanitize_name()`, which
collapses catalog separators (`.`, `:`, `@`, `/`) to `_`, so a VLAN device
`eth0.100` lands at `Packet.eth0_100/packets`.

Two captures may share one source as long as their names differ. Event
registration is **strict-create**: a second capture registering a name already
on that source raises rather than merging, which keeps two captures from
silently interleaving into one table. GOOSE control block events carry no
`name` prefix, so two decoders on one source that see the same control block
collide: give each its own source.

### GOOSE

`goose=True` decodes IEC 61850-8-1 GOOSE (EtherType 0x88B8, tagged or not).
`pkt` rows of 0x88B8, 0x88B9 and 0x88BA read `GOOSE`, `GSE` and `SV` in
`proto` either way, where they read `Ethernet` before. HSR-tagged frames
(0x892F) are out of scope. GOOSE is multicast: a live capture needs
`promiscuous=True` unless the interface already receives the publishers'
groups.

| Topic | Behavior |
| --- | --- |
| `goose` rows | one per frame: `frame_no`, `iface`, `appid`, `length`, `reserved1`, `reserved2`, `s_bit`, the PDU fields under their IEC 61850-8-1 names (`gocbRef`, `timeAllowedtoLive`, `datSet`, `goID`, `t`, `t_quality`, `stNum`, `sqNum`, `simulation`, `confRev`, `ndsCom`, `numDatSetEntries`), `src_mac`, `dst_mac`, `vlan_id`, `vlan_pcp`, and `malformed` (why the frame did not decode) |
| Events | one per control block on the capture's source, beside its rows and not `name`-prefixed: its gocbRef `LD/LN$GO$gcb` as `LD/LN/GO/gcb`, each segment sanitized, so `FULLLD0/LLN0$GO$dcdc` is `Packet.FULLLD0/LLN0/GO/dcdc`. A gocbRef that does not parse lands at `_unresolved/GO/<gocbRef>` (`$`, `.`, `/` as `_`), an empty one at `_unresolved/GO/<goID>`, else `_unresolved/GO/appid_<APPID>`; two that sanitize alike take `_2`, `_3`. Fields: the header fields (`goID` among them), `src_mac`, `vlan_id`, the members, then `stnum_gap`, `sqnum_gap`, `tal_expired`, at the frame's capture time |
| Members | positional `d00`, `d01`, ...; with `scl=` (SCD, CID, ICD, IID) the FCDA reference relative to the control block's LD, `LD0/GGIO1.Ind1.stVal` as `GGIO1_Ind1_stVal` in an LD0 control block and `LD0_GGIO1_Ind1_stVal` in another LD's, matched by gocbRef, else by destination MAC and APPID; structures and arrays flatten by position, `d02_0`, `d02_1` |
| Types | boolean, integer (`i64`), unsigned (`u64`), floating-point (`f32`, `f64`), utc-time (`i64` ns), bit-string up to 32 bits (`u32`, first bit most significant), strings; the rest as bytes |
| Flags | `stnum_gap`: stNum neither repeated nor +1 (2^32-1 wraps to 1); `sqnum_gap`: sqNum not +1 within a stNum, or not 0 on a new one; `tal_expired`: later than the previous frame's timeAllowedtoLive. Per frame, no timers |
| Control blocks | `goose_control_blocks()`: one dict per control block, last frame's header, `members`, `frames`, `state_changes`, `last_seen_ns`, `alive` (within timeAllowedtoLive); a capture's refreshes each `stats_interval` |
| Not decoded | a malformed PDU (row only, `goose_malformed`); members whose types or count differ from the event's first frame (header kept, members null, `goose_schema_changes`); control blocks past 16384 member columns in all (rows and counters, no event) |

### SocketCAN

Records of link type 227 (`LINKTYPE_CAN_SOCKETCAN`, as libpcap writes a
SocketCAN interface) decode into `can/<iface>` rows, one event per interface (its pcapng name,
else its index), the `zelos.can.frame.v1` schema
the CAN extension emits: `arbitration_id`, `is_extended`, `is_fd`, `is_rx`
(always null), `dlc` (bytes), `data`, `is_remote_frame`. No signal decode;
DBC decode is zelos-can's. File replay and `decode_frame` are tested; a live capture of a
SocketCAN interface is not.

| Topic | Behavior |
| --- | --- |
| `pkt` rows | `proto` `CAN`, `CAN FD` or `CAN error`; `info` the id, length and RTR/BRS/ESI, or the error class |
| CAN FD | the FDF flag, a length over 8, or a 72-byte record |
| Not decoded | error frames (`pkt` row only, as the CAN extension drops them); CAN XL (`proto` `CAN XL`); a bad length or truncated payload (`info` says which) |

### V2G

`v2g=True` decodes an ISO 15118 / DIN 70121 charging link: SLAC, SDP,
V2GTP, and the EXI messages (SupportedAppProtocol, DIN 70121, ISO 15118-2,
ISO 15118-20 common, AC and DC).
A tap or bridge on the link sees
third-party unicast: a live capture needs `promiscuous=True`.

A session under TLS decodes when the endpoint discloses its session secrets,
as test systems do: either in the capture itself (nothing to configure) or
in a key log file given as `tls_keylog="keys.log"`
(`PacketDecoder`, `PacketCapture`). Without them it stays opaque.

| Topic | Behavior |
| --- | --- |
| `slac` rows | one per HomePlug AV MME (EtherType 0x88E1, tagged or not): `frame_no`, `iface`, `mmv`, `mmtype`, `name` (`CM_SLAC_PARM.REQ`), `src_mac`, `dst_mac`, then per type: `run_id` (PARM, START_ATTEN_CHAR.IND, ATTEN_CHAR.IND / .RSP, MATCH), `num_sounds` (PARM.CNF, START_ATTEN_CHAR.IND, ATTEN_CHAR.IND), `num_groups` and `atten_min` / `atten_max` / `atten_mean` in dB (ATTEN_CHAR.IND), `ev_mac` / `evse_mac` (MATCH), `nid` (MATCH.CNF), and `malformed` (body shorter than its type needs). The NMK is never recorded |
| `sdp` rows | one per SDP request or response on UDP 15118: `frame_no`, `iface`, `kind` (`request`, `response`), `secc_ip`, `secc_port`, `security` (`tls`, `none`), `transport` (`tcp`, `udp`), `src_ip`, `src_port`, `malformed` (body shorter than its kind needs); `kind`, `security`, `transport` are wire codes with value tables |
| `v2gtp` rows | one per V2GTP message: `frame_no` (the segment that completed it), `iface`, `flow_id`, `direction` (`EVCC->SECC`, `SECC->EVCC`; null when neither the SYN nor an SDP response was seen), `payload_type`, `length`, `exi` (the whole payload), `protocol` (`SAP`, `DIN 70121`, `ISO 15118-2`, `ISO 15118-20`, or the negotiated namespace when unsupported), `message` (body element; the root element for ISO 15118-20, `DC_ChargeLoopReq`; `SupportedAppProtocolReq`/`Res` for SAP), `session_id` (hex), `decode_error` (why not decoded) |
| Grammar | per TCP connection from the SupportedAppProtocol handshake (`urn:iso:15118:2:2010:MsgDef` reads as DIN). Without it (capture started mid-session) DIN and ISO-2 are tried, last success first, and a result counts only as a `V2G_Message` with a SessionID (`v2g_grammar_inferred`). Other namespaces stay raw (`v2g_undecoded`) |
| `<Message>` events | one per message type, named as the standard names it: the body element for DIN 70121 / ISO 15118-2 (`CurrentDemandReq`), the root element for ISO 15118-20 (`DC_ChargeLoopReq`, `ScheduleExchangeReq`). A message several protocols have (`SessionSetupReq`, `AuthorizationRes`, `ServiceDiscoveryRes`, `ServiceDetailReq`, `PowerDeliveryReq`, `SessionStopReq`, `CertificateInstallationRes`, ...) is ONE event for all of them: `protocol` says which sent the row, and a field a protocol lacks is null. Every event starts `frame_no`, `iface`, `session_id`, `protocol`, the header's `FaultCode` and `FaultMsg` (its Notification; DIN / ISO-2), `Signature` (whether it carries one) and `TimeStamp` (ISO 15118-20, as sent: stacks differ between seconds and microseconds), then the message's fields under their XSD names (`EVSEPresentVoltage`, `EVRESSSOC`, `RCD`, `eMAID`, ...). Enumerations are codes with value tables; lists (`PaymentOption`, `EnergyTransferMode`, SAP `ProtocolNamespace`, `SupportedServiceIDs`, `EnergyTransferServiceList`, `VASList`, `AuthorizationServices`, `PrioritizedEMAIDs`) are comma separated |
| Per-protocol columns | where protocols define an element of one name differently, each keeps its own column, in every event: `ResponseCode` is DIN's table, `ResponseCode_iso2` ISO-2's (they diverge from 20), `ResponseCode_iso20` ISO 15118-20's; `EVSENotification`, `ChargeProgress` and `ChargingSession` are DIN / ISO-2's tables, `EVSENotification_iso20`, `ChargeProgress_iso20` and `ChargingSession_iso20` ISO 15118-20's (other codes); `MeterReading` is DIN's PhysicalValue, `MeterReading_iso2` ISO-2's count of Wh; `EVCCID` is DIN / ISO-2's MAC address in hex, `EVCCID_iso20` ISO 15118-20's identifier as text. Each is null under the other protocols. The rest are shared: `EVSEProcessing` (one table), `ServiceID`, `Id`, `NotificationMaxDelay` (s), the `*_len` and `num_*` of a name; `GenChallenge` and `EVSEID` are text where the protocol sends text and hex where it sends bytes |
| DIN / ISO-2 values | PhysicalValues are floats scaled by their Multiplier and converted from their Unit to the column's (`h`/`m` to `s`; null when the Unit is of another quantity, as DIN's `VA` and `W/s` always are; an absent DIN Unit reads as the column's), unit in the column metadata. A field only one of the two has is null under the other (`ContractID` DIN, `eMAID` ISO-2) |
| ISO 15118-20 values | a RationalNumber is a float, Value x 10^Exponent. The wire carries no unit; by the quantity an element's name states, voltages are marked V, currents A, charge, discharge and active powers W, energy requests and capacity Wh, SOC %, meter readings Wh / varh. Reactive power, frequency, times and delays, power ramp and asymmetry have none; `NotificationMaxDelay` is the column DIN / ISO-2 share, in s. A control mode's elements are columns of the message, per phase as `_L2` / `_L3`, null when another mode was sent; `ControlMode` says which, named as the mode element sent (`Scheduled_DC_CLReqControlMode`, `BPT_Dynamic_AC_CLResControlMode`, `Dynamic_SEReqControlMode`), `EnergyTransferMode` likewise for ChargeParameterDiscovery (`DC_CPDReqEnergyTransferMode`, `BPT_DC_CPDReqEnergyTransferMode`), `AuthorizationMode` for Authorization (`EIM_AReqAuthorizationMode`, `PnC_AReqAuthorizationMode`). Discharge limits keep the sign sent. `Receipt` says whether one came, its costs are not recorded |
| ISO 15118-20 | the grammar is per message, from the V2GTP payload type: common messages (0x8002), AC (0x8003), DC (0x8004), so a capture started mid-session decodes. Each message has a `v2gtp` row and a `<Message>` row. ACDP, WPT, AC DER and the side streams (0x8005, 0x8006, 0x8010, 0x8011, 0x8101 to 0x8104) are framed and stay raw (`v2g_undecoded`), as does a document that is not a message; wireless SDP (0x9002, 0x9003) has no `sdp` row. A session under TLS, as the standard requires, decodes with its secrets disclosed (TLS, below); without them: `slac` and `sdp` rows and `v2g_tls_connections` only |
| Certificates, keys, schedules | never recorded. `*_len` columns give a certificate's, signature's, encrypted private key's or DH value's size in bytes (`contract_certificate_len`, `encrypted_private_key_len`, `x448_encrypted_private_key_len`, `meter_signature_len`, ...); `num_*` columns count list entries (`num_contract_sub_certificates`, `num_root_certificate_ids`, `num_sa_schedule_tuples`, `num_profile_entries`, `num_parameter_sets`, `num_schedule_tuples`, `num_price_rule_stacks`), 0 when the message leaves the list out, null under a protocol whose message has no such list. Also not recorded: a meter reading's signature (DIN, ISO-2), the SessionID a metering message repeats in its body, a receipt's costs and time anchor and a price schedule's header (ISO 15118-20), and the services of a ServiceList. ChargeParameterDiscoveryRes `SAScheduleTupleID` is the first tuple's |
| `v2g_decoded`, `v2g_undecoded` | per V2GTP message; they sum to `v2g_messages` |
| TCP | a direction is V2G from the first segment that starts with a V2GTP header; retransmitted bytes are dropped (`v2g_tcp_retransmissions`), also when seen again after the direction's FIN; no reordering: a sequence gap drops the held partial message (`v2g_tcp_gaps`). A direction first seen mid-message (its first segment lost, the capture started later, or evicted) is skipped up to the next segment that starts a message; to or from an SDP-learned SECC each skipped segment counts in `v2g_tcp_gaps` (a sequence jump) or `v2g_framing_errors`. 1024 directions, closed ones included until their connection's next SYN or RST, least recently used evicted (`v2g_streams_evicted`) |
| Not decoded | a bad V2GTP header drops the buffered bytes to the segment's end (`v2g_framing_errors`), as do bytes to or from an SDP-learned SECC that begin neither a V2GTP message nor a TLS record; payloads past 64 KiB (`v2g_oversize`); TLS sessions whose secrets are not disclosed |
| `v2g_tls_connections` | per connection whose first bytes to an SDP-learned SECC are a TLS record header |
| TLS | a connection to an SDP-learned SECC that opens with TLS is decrypted once its secrets are known and decoded like a cleartext one: the same rows, `frame_no` and time those of the segment that completed the message, whether the secrets came before or after it. TLS 1.3: `TLS_AES_256_GCM_SHA384`, `TLS_AES_128_GCM_SHA256`, `TLS_CHACHA20_POLY1305_SHA256`, with HelloRetryRequest, KeyUpdate, mutual authentication and resumption. TLS 1.2: ECDHE or ECDH key exchange with AES-128-CBC-SHA256, AES-256-CBC-SHA384 (MAC-then-encrypt or encrypt-then-MAC), AES-GCM or ChaCha20-Poly1305. A record becomes rows only when its tag or MAC verifies under the disclosed secret |
| TLS secrets | NSS key log lines: `CLIENT_RANDOM` (TLS 1.2); `CLIENT_HANDSHAKE_TRAFFIC_SECRET`, `SERVER_HANDSHAKE_TRAFFIC_SECRET`, `CLIENT_TRAFFIC_SECRET_0`, `SERVER_TRAFFIC_SECRET_0` (TLS 1.3, all four). Two sources, used together, the file's secret taking the place of an in-band one for the same session and label (else the first seen stays; a connection already opened with a secret keeps it): in band, a UDP datagram in the capture that holds such lines and nothing else, on any port, as charging test systems and stacks with TLS key logging switched on send them, picked up whenever `v2g` is on; and `tls_keylog=<path>` (implies `v2g`), a key log file as TLS libraries write it (`SSLKEYLOGFILE`). `PacketDecoder` reads the file when constructed; `PacketCapture` follows it as it grows (it may not exist yet; another file put in its place, or one cut shorter, is read from its start), read by the helper as the capturing user after it has dropped its capture privilege. Malformed lines are skipped |
| TLS limits | the endpoint has to disclose the secrets: a production charger or vehicle does not, and a server private key is no substitute. A TLS session to a SECC not learned from an SDP response is not tried. The capture has to hold the handshake from the ClientHello: started later, a connection counts in `v2g_tls_no_handshake`; with the ClientHello's segment lost, in `v2g_tcp_gaps`. Secrets may come after the traffic: a connection's records wait for them, up to 256 KiB (`v2g_tls_buffer_overflow`), 32 TLS connections at a time; of a long key log the newest 4096 sessions are kept. Decryption of a connection ends for good at a lost segment (`v2g_tcp_gaps`), at a record that does not verify (`v2g_tls_auth_failures`: a wrong or stale secret; it is not tried again with another) or at something not handled (`v2g_tls_unsupported`: TLS 1.1 or older, another cipher suite, TLS 1.2 renegotiation). 0-RTT early data is skipped |
| TLS secrets, handling | used in memory to derive keys: never logged, never in a decoded row, counter or error message. The `packets` rows are the capture as captured: with frame bytes stored (`log_frames`, the default), a `frame` holds an in-band disclosure datagram like any other packet, up to `stored_frame_bytes` |
| `v2g_tls_*` | per connection: `v2g_tls_decrypted` (a record verified), `v2g_tls_no_secret` (a secret it needs is not disclosed; falls again when it arrives late), `v2g_tls_no_handshake`, `v2g_tls_unsupported`, `v2g_tls_auth_failures`, `v2g_tls_buffer_overflow`; `v2g_tls_secrets_seen` counts distinct secrets taken from key log lines, in band or from the file |
| `v2g_framing_errors` | per segment whose buffered bytes were dropped on a bad V2GTP header |

## API

| Symbol | Purpose |
| --- | --- |
| `PacketDecoder(...)` | Bring-your-own-bytes: `decode_frame`, `decode_stream`, `convert_file`, `push_stats`, `register_schemas`, `metrics`, `flush` |
| `PacketCapture(...)` | Live handle: `start`, `stop`, `stats`, `metrics`, `interface`, `link_type`, `is_active`, `error`; also a context manager |
| `list_interfaces()` | `InterfaceInfo` per NIC — name, index, up/running/loopback, addresses, MAC, and on Windows a `description` for the `\Device\NPF_{GUID}` name |
| `permission_remediation()` | Copy-pasteable privilege fix for this platform |
| `capture_supported()` | False outside Linux/macOS/Windows; offline decode still works |
| `sanitize_name(name)` | The event-prefix rule, shared with the packet extension |
| `CapturePermissionError` | `PermissionError` subclass, message embeds the remediation |
| `InterfaceNotFoundError` | `ValueError` subclass for an unknown interface name |

## The `frame` column

`frame` is the source of truth every decoded column is checked against, so both
entry points populate it by default (`log_frames=True`), clipped to
`stored_frame_bytes=256` bytes. `stored_frame_bytes=None` stores every captured
byte; `log_frames=False` drops the column.

| Knob | Applies to | Effect |
| --- | --- | --- |
| `snaplen` | live capture only | Bytes the **kernel** copies out. Uncaptured bytes are dissected by nobody; the shortfall shows up as `orig_len > cap_len` with `truncated` set. |
| `stored_frame_bytes` | live + offline | Bytes **stored** in `frame`. Dissection always reads the full captured bytes, so this changes storage and nothing else. |

`orig_len` / `cap_len` / `truncated` describe capture truncation only. Storage
truncation is `len(frame) < cap_len`; the frozen schema has no column for it.

## Drop policy

**While the sink is consuming, userspace blocks rather than dropping.** Every
emit is the SDK's normal send path, never `try_send`, so a full router channel
stops the read loop, the kernel ring fills, and the kernel drops where it can be
counted.

| `kernel_drops` | `decode_stall_ms` | Meaning |
| --- | --- | --- |
| 0 | high | Trace store is backpressuring |
| climbing | ~0 | Line-rate overload; the read loop is the bottleneck |

`Metrics.emit_stall_ms` is the sink-only slice of `decode_stall_ms`; the
difference is dissection cost.

**Where that guarantee stops.** Backpressure only exists while something is
pulling. If the helper's gRPC publish stream to the agent breaks, the router's
publisher subscription goes away while decode keeps running: rows are produced
and discarded, and **`kernel_drops` stays flat** because the kernel handed them
over successfully. So `kernel_drops == 0` means "the kernel lost nothing", not
"the trace is complete". What does move is `Metrics.emit_errors` /
`Metrics.flush_errors`, and at stop time `CaptureStats.tail_abandoned`
(non-zero = rows the publisher held never reached the agent) and
`CaptureStats.kernel_stats_errors` (non-zero = `kernel_packets` / `kernel_drops`
are a stale reading, not totals). Check those before treating a capture as
complete. There is no counter for rows dropped into a dead subscription mid-run.

## Self-traffic exclusion

When the agent streams over the interface being captured, every emitted row
makes more captured bytes. At a large snaplen that loop does not converge.

**On by default for `PacketCapture`, derived from `agent_url`.** With neither
`exclude_agent_addrs` nor `exclude_agent_port` passed, both come from the URL
the capture streams to (`agent_url`, else `$ZELOS_AGENT_URL`, else
`$ZELOS_TRACE_FORWARD_URL`, else `http://localhost:2300`), resolving a host name
to **every** address it has — so the `localhost` default excludes `127.0.0.1`
and `::1` both. `PacketDecoder` takes no default at all: it is handed bytes that
already exist, so there is no loop to close and dropping rows out of a
user-supplied file would be silent data loss.

| You want | Pass |
| --- | --- |
| A different endpoint | `exclude_agent_addrs=[...]` **and** `exclude_agent_port=...` — no resolution happens |
| The agent's traffic captured | `exclude_agent_addrs=[]` |
| Nothing else | (nothing) |

Either argument alone is an error; the empty list is the one address list a port
may be absent from. A host that does not resolve is a **construction error**,
not a fallback to capturing unfiltered.

A **live** capture compiles the exclusion with `pcap_compile` and installs it
with `pcap_setfilter` on the helper's handle, so the kernel rejects excluded
traffic before a packet is copied out. If `pcap_compile` cannot express it for
the link type, the capture fails to open rather than running unfiltered. Offline
decode has no kernel in the path; its userspace `AgentFilter` matches on ports
only, but it is still applied — a pcap being converted loses its agent-endpoint
rows unless you pass `exclude_agent_addrs=[]`.

The expression is not recorded in the trace. It is logged at capture start
(`ZELOS_PACKET_LOG=zelos_packet_helper=debug`, "compiling the agent filter"), which is the only
place to read back what was installed — worth capturing alongside a trace you
intend to analyze, because of the three gaps below.

**It drops more than the agent port.** Closing the IPv4 fragment hole
statelessly costs precision, on **any port**, for the agent addresses only:

| Traffic to/from an agent address | Kept? |
| --- | --- |
| IPv4 first fragment (offset 0) | kept, unless on the agent port |
| IPv4 continuation fragment (offset > 0) | **dropped**, any port |
| IPv6 with any extension header — Fragment, Hop-by-Hop, Routing, Destination Options, **ESP (50) or AH (51)** | **dropped**, any port |

So fragmented UDP telemetry to an agent address on port 9999 keeps each
datagram's *first* fragment and loses every continuation, and an agent address
reached over IPsec transport mode contributes no packets at all. The idiomatic
`not (host X and port Y)` *accepts* continuation fragments, and those are what
the feedback loop is made of; statelessly, rejecting on the address alone is the
only correct answer. There is no counter for it either — `pcap_stats`'s
`ps_recv` counts packets that already passed the kernel filter, so excluded
traffic appears in no column. To see what was excluded, capture with
`exclude_agent_addrs=[]` on an interface the agent does not stream over.

**Tunnels defeat it.** Both the kernel program and the userspace backstop read
the **outer** IP header, so agent traffic inside WireGuard, any other VPN, VXLAN
or GRE carries its addresses in the inner header and is re-admitted. Capture the
tunnel interface (`wg0`, `utun0`, …) instead, where the agent's addresses *are*
the outer ones.

**Three or more stacked VLAN tags defeat it.** libpcap's `host` / `port`
primitives do not look past a VLAN tag, so the expression is repeated under
`vlan` and `vlan and vlan` — untagged, single-tagged and QinQ. Under a third tag
the address test reads the wrong offset, does not match, and the enclosing
`not (…)` therefore **accepts** the frame. The arms stop there because each one
multiplies the compiled program, and the worst case already sits close to BSD's
512-instruction `BPF_MAXINSNS` ceiling.

## Development

```bash
just develop     # uv sync + maturin develop
just test        # cargo test (all three crates) + pytest + check-static
just lint        # cargo clippy -D warnings
just stub_gen    # regenerate py/zelos_packet/_native.pyi
```

Live-capture tests are opt-in (`ZELOS_PACKET_TEST_LIVE=1`, optionally
`ZELOS_PACKET_TEST_IFACE=<name>`) and need a `zelos-agent` binary, since rows are
read back out of a real agent. Supervision and the permission verdict need no
privilege on any platform: `rs/supervisor.rs` and `test/test_helper_backend.py`
both drive a fake helper.

On Windows (git-bash), with the free Npcap SDK unzipped somewhere:

```bash
export LIBPCAP_LIBDIR='C:\path\to\npcap-sdk\Lib\x64'   # wpcap.lib; build.rs refuses without it
docker/manylinux/build-helper.sh "$PWD"                # stages py/zelos_packet/zelos-packet-helper.exe
maturin build --release                                # or `maturin develop --uv`
```

The Rust toolchain is pinned by the nix dev shell; there is deliberately no
`rust-toolchain` file. Release wheels come from the `api-py-zelos-packet`
workflow, or locally from `just build-linux-wheels`; both build the static
libpcap with `docker/manylinux/build-libpcap.sh` (the one place its version,
hash and configure flags live) and gate the artifact with
`docker/manylinux/check-wheel-static.sh`. A bare `maturin build` elsewhere does
neither. [RELEASE.md](RELEASE.md) has the release order.

