Getting started
This chapter shows how to use the crate. The rest of the book shows how it is built.
Reference version:
packet_parser13.3.0. Every code snippet marked tested below is included verbatim from the book'sexamples/crate, which compiles and runs against that exact version (cd examples && cargo test). Older versions differ: seeMIGRATION-13.md,MIGRATION-12.mdandMIGRATION-11.mdin the crate repository.
Installation
[dependencies]
packet_parser = "13.3.0"
hex = "0.4" # only for the examples below, to decode hex dumps
Parse one packet
parse is the entry point. It takes two things:
- the LINKTYPE of the capture: the value stored in the PCAP/PCAPNG file (
LinkType::ETHERNET,LinkType::LINUX_SLL, ...); - exactly one packet, without any PCAP record header.
use packet_parser::{LinkType, parse}; fn main() -> Result<(), Box<dyn std::error::Error>> { let raw = hex::decode( "feaa81e86d1efeaa818ec864080045500034000000003d06206b36e6700d\ ac140a0201bbc1087d7f02aa4e2b998e80100081748300000101080a9373\ c9c207ef14e3", )?; // Always pass the LINKTYPE the capture declares. let flow = parse(LinkType::ETHERNET, &raw)?; println!("L2: {}", flow.data_link); if let Some(internet) = &flow.internet { println!("L3: {} {:?} -> {:?}", internet.protocol_name, internet.source, internet.destination); } if let Some(transport) = &flow.transport { println!("L4: {:?} {:?} -> {:?}", transport.protocol, transport.source_port, transport.destination_port); } if let Some(application) = &flow.application { println!("L7: {}", application.protocol); } Ok(()) }
Output:
L2:
Destination MAC: fe:aa:81:e8:6d:1e,
Source MAC: fe:aa:81:8e:c8:64,
Ethertype: IPv4,
VLAN: None,
Payload Length: 52
L3: IPv4 Some(54.230.112.13) -> Some(172.20.10.2)
L4: Tcp Some(443) -> Some(49416)
No L7 line: this segment is a pure ACK with an empty payload, so there is nothing to classify and application stays None.
The same frame, as the book's example crate checks it (tested):
#![allow(unused)] fn main() { #[test] fn parse_a_valid_ethernet_frame() -> Result<(), Box<dyn std::error::Error>> { let raw = hex::decode(ETHERNET_IPV4_TCP_ACK_HEX)?; // Always pass the LINKTYPE the capture declares. let flow = parse(LinkType::ETHERNET, &raw)?; let internet = flow.internet.as_ref().expect("IPv4 announced by the EtherType"); assert_eq!(internet.protocol_name, "IPv4"); assert_eq!(internet.source.unwrap().to_string(), "54.230.112.13"); assert_eq!(internet.destination.unwrap().to_string(), "172.20.10.2"); let transport = flow.transport.as_ref().expect("TCP announced by the IP header"); assert_eq!(transport.source_port, Some(443)); assert_eq!(transport.destination_port, Some(49416)); // A pure ACK: the payload is empty, so there is nothing to classify. assert!(flow.application.is_none()); assert!(flow.corrupted.is_none()); Ok(()) } }
Never guess the LINKTYPE
parse is fail-closed on the link layer: the LINKTYPE comes from the caller and is never guessed from the bytes. Check it up front to reject a whole capture before reading a single packet:
#![allow(unused)] fn main() { use packet_parser::{LinkType, is_supported, parse}; let link_type = LinkType::ETHERNET; if !is_supported(link_type) { return Err(format!("unsupported LINKTYPE {}", link_type).into()); } let flow = parse(link_type, packet_bytes)?; }
| LINKTYPE | Value | Decoder status |
|---|---|---|
| BSD loopback (NULL) | 0 | Supported: four address-family bytes, then the IP packet (11.2.0) |
| Ethernet | 1 | Supported (802.1Q and 802.1ad/QinQ tags included) |
| RAW IP | 101 | Supported for IPv4 and IPv6 |
| Native IEEE 802.11 | 105 | Modelled for CAPWAP inner flows; top-level decoder not yet supported |
| Linux SLL v1 | 113 | Supported |
| Bluetooth H4 with pseudo-header | 201 | Identified, explicitly unsupported |
| IPv4 raw | 228 | Supported |
| IPv6 raw | 229 | Supported |
| IEEE 802.3br mPacket | 274 | Supported for express mPackets (SMD-E); preemptible fragments are refused |
| Linux SLL v2 | 276 | Supported |
| Any other value | Preserved as-is | ParseError::UnsupportedLinkType |
PacketFlow::try_from(&[u8]) and DataLink::try_from(&[u8]) still exist. They take a bare byte slice and assume Ethernet. Feeding them a Linux any capture (LINKTYPE_LINUX_SLL) does not fail: the 16 cooked-header bytes are read as MAC addresses and an EtherType, and you get Ok with fabricated addresses. Use them only when the capture is known to be Ethernet.
Reading the outcome
Only the link layer can fail the parse. Above it, three outcomes are distinct and must not be confused:
flow.internet / transport | flow.corrupted | Meaning |
|---|---|---|
Some(..) | None | The layer was recognized and decoded. |
None | None | The protocol is not supported (e.g. the experimental EtherType 0x88B5), nothing above it can be reached. |
None | Some(..) | The layer was recognized (by its EtherType or IP protocol number) but its bytes are invalid. CorruptedLayer::layer says which one, error says why: since 13.0.0 the decoder's error, typed. |
Some(..) | Some(..) | Semantic anomaly: the header is readable but no conforming stack emits it (TCP SYN+FIN, reserved bits set). The layer is kept so its ports remain available for flow correlation; nothing is parsed above it. |
The four shapes side by side, on the frames of the tests below (the anomaly is a TCP segment with SYN and FIN both set), and the Err only the link layer returns. A dark row is None: the difference between not supported and corrupted is only the corrupted row.
A recognized layer with invalid bytes (tested):
#![allow(unused)] fn main() { #[test] fn a_recognized_but_invalid_upper_layer_is_reported_not_fatal() { let raw = hex::decode(ETHERNET_IPV4_TCP_ACK_HEX).unwrap(); // Cut 6 bytes into the IPv4 header: the EtherType still says IPv4, // so the layer is recognized, but its bytes are invalid. let flow = parse(LinkType::ETHERNET, &raw[..20]).unwrap(); assert!(flow.data_link.as_ethernet().is_some()); // kept assert!(flow.internet.is_none()); let corrupted = flow.corrupted.expect("recognized layer with invalid bytes"); assert_eq!(corrupted.layer, CorruptedLayerKind::Internet); // Since 13.0.0 `error` is the decoder's error, typed: a `match` // sorts the causes. Its `Display` is the text of 12.x. assert!(matches!( corrupted.error, CorruptedLayerError::Internet(InternetError::Ipv4Error(Ipv4Error::InvalidLength { expected: 20, actual: 6, })) )); assert_eq!( corrupted.error.to_string(), "IPv4 error: Invalid IPv4 packet length: expected at least 20 bytes, got 6 bytes" ); } }
An unsupported protocol above the link layer, which is not corruption (tested):
#![allow(unused)] fn main() { #[test] fn an_unsupported_upper_layer_leaves_the_layer_none_without_corruption() { // Synthetic frame: two MAC addresses, EtherType 0x88B5 (the IEEE 802 // local experimental EtherType, decoded by no one) and a few payload // bytes. let mut raw = hex::decode("0180c200000e001122334455").unwrap(); raw.extend_from_slice(&[0x88, 0xb5, 0x02, 0x07, 0x04, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55]); let flow = parse(LinkType::ETHERNET, &raw).unwrap(); // Not supported is not the same as corrupt: nothing above the link // layer could be reached, and nothing is reported as invalid. assert!(flow.internet.is_none()); assert!(flow.transport.is_none()); assert!(flow.application.is_none()); assert!(flow.corrupted.is_none()); } }
And the two link-layer failures, the only ones that return Err (tested):
#![allow(unused)] fn main() { #[test] fn an_unsupported_linktype_is_refused_before_reading_bytes() { let raw = hex::decode(ETHERNET_IPV4_TCP_ACK_HEX).unwrap(); let bluetooth = LinkType::BLUETOOTH_HCI_H4_WITH_PHDR; assert!(!is_supported(bluetooth)); assert!(matches!( parse(bluetooth, &raw), Err(ParseError::UnsupportedLinkType(LinkType(201))) )); } }
#![allow(unused)] fn main() { #[test] fn a_truncated_link_header_fails_the_parse() { let raw = hex::decode(ETHERNET_IPV4_TCP_ACK_HEX).unwrap(); // Only the link layer can fail the parse: 10 bytes cannot hold the // 14-byte Ethernet header. let error = parse(LinkType::ETHERNET, &raw[..10]).unwrap_err(); assert_eq!( error.to_string(), "Invalid link layer: LINKTYPE 1 packet is truncated: required bytes 14, actual bytes 10" ); } }
Main API
| Need | API |
|---|---|
| Check whether a link decoder exists | is_supported(LinkType) |
| Parse a packet (canonical) | parse(LinkType, &[u8]) |
| Parse with caller-declared ports ("Decode As") | parse_with(LinkType, &[u8], &ParseConfig) |
| Parse Ethernet, compat shortcut (assumes Ethernet) | PacketFlow::try_from(&[u8]) |
| Parse only Ethernet/VLAN (assumes Ethernet) | DataLink::try_from(&[u8]) |
| Parse only L3 | Internet::try_from_network_parts(NetworkProtocol, &[u8]) |
| Parse only L4 | Transport::try_from_parts(Option<TransportProtocol>, &[u8]) |
| Parse one application protocol in detail | packet_parser::parse::application::protocols::<proto>::XxxPacket::try_from(&[u8]) |
| Detach the result from the original buffer | flow.to_owned_flow() |
| Iterate over encapsulated flows | flow.flatten() |
| Verify a checksum (opt-in) | packet_parser::checksum::verify_{ipv4_header,tcp,udp}_checksum |
| Measure the time spent per layer | parse_timed(...) with the parse_timing feature |
"Decode As": an FTP server on port 2121
Some protocols are only detected when the port and the content agree (see the application chapter). ParseConfig lets the caller declare extra ports, for the 30 protocols of DecodeAsProtocol (the list); since 12.1.0, DecodeAsProtocol::ALL is that list, for a caller that offers the choice. The port never replaces the content check: it only gives the probe its chance before the rest of the table.
#![allow(unused)] fn main() { use packet_parser::{DecodeAsProtocol, LinkType, ParseConfig, parse_with}; let config = ParseConfig::new().decode_as(2121, DecodeAsProtocol::Ftp); let flow = parse_with(LinkType::ETHERNET, &raw, &config)?; }
Owned flows and serialization
PacketFlow<'a> borrows the input buffer: it cannot outlive it. To store a flow, send it across threads or keep it after the capture buffer is reused, convert it with to_owned_flow(). The conversion is lossy on purpose: the owned form drops the payloads and the per-layer details, and keeps the flow identity (addresses, protocols, ports).
What PacketFlowOwned keeps, layer by layer:
| Field | Owned type | Kept |
|---|---|---|
data_link | LinkLayerOwned | the LINKTYPE, the NetworkProtocol, and the fields of the format's view: MACs, EtherType and VLAN stack for Ethernet, the cooked-header fields for SLL and SLL2, the 802.11 addresses |
internet | InternetOwned | both addresses, their IpType, the protocol name as a String |
transport | TransportOwned | both ports, the protocol as its display name ("TCP"), not the typed TransportProtocol |
application | ApplicationOwned | the label, as a String |
inner, corrupted | Box<PacketFlowOwned>, CorruptedLayer | both, inner converted recursively |
Dropped: every payload, every details, Internet::payload_protocol, and the PPPoE session of an Ethernet frame (DataLink::pppoe, since 11.6.0). Every owned type derives PartialEq, Eq and Hash over what it keeps, which makes PacketFlowOwned usable as the key of a flow table. That key is coarser than the borrowed identity: without the session, two PPPoE sessions that agree on everything else are one owned flow (PPPoE session).
PacketFlow and PacketFlowOwned both implement serde::Serialize and produce the same JSON text: since 11.7.0 (#193), the borrowed model writes its members in the order of the owned one, so the two strings are equal byte for byte. Before that, the keys and the values were already the same, but the borrowed model wrote protocol_transport before the ports and ethertype after the VLAN tags. The link layer is nested and tagged, the upper layers are flattened, payloads and details are not serialized.
{
"data_link": {
"link_type": 1,
"network_protocol": { "kind": "ipv4" },
"link_kind": "ethernet",
"link_details": {
"destination_mac": "fe:aa:81:e8:6d:1e",
"source_mac": "fe:aa:81:8e:c8:64",
"ethertype": "IPv4"
}
},
"source_ip": "54.230.112.13",
"ip_source_type": "Public",
"destination_ip": "172.20.10.2",
"ip_destination_type": "Private",
"protocol_internet": "IPv4",
"source_port": 443,
"destination_port": 49416,
"protocol_transport": "TCP"
}
The owned form is what you keep once the capture buffer is gone, and its text is the borrowed one (tested):
#![allow(unused)] fn main() { #[test] fn owned_flows_serialize_like_borrowed_ones() -> Result<(), Box<dyn std::error::Error>> { let raw = hex::decode(ETHERNET_IPV4_TCP_ACK_HEX)?; let flow = parse(LinkType::ETHERNET, &raw)?; let borrowed_json = serde_json::to_string(&flow)?; // The owned form outlives the buffer; it drops payloads and details. let owned = flow.to_owned_flow(); drop(raw); // Since 11.7.0, both models write the same text, members in the same order. let owned_json = serde_json::to_string(&owned)?; assert_eq!(owned_json, borrowed_json); let json: serde_json::Value = serde_json::from_str(&owned_json)?; assert_eq!(json["data_link"]["link_type"], 1); assert_eq!(json["data_link"]["link_kind"], "ethernet"); assert_eq!(json["source_ip"], "54.230.112.13"); assert_eq!(json["protocol_transport"], "TCP"); assert_eq!(json["destination_port"], 49416); Ok(()) } }
Timing (benchmarks)
parse_timed runs the exact same pipeline as parse and reports the nanoseconds spent in each layer. The API is always there; without the parse_timing feature nothing is measured and ParseTiming stays zeroed, so enabling the feature anywhere in a dependency graph never changes a signature.
#![allow(unused)] fn main() { use packet_parser::{LinkType, parse_timed, timing::ParseTiming}; let mut timing = ParseTiming::default(); let flow = parse_timed(LinkType::ETHERNET, &raw, &mut timing)?; println!("L2={}ns L3={}ns L4={}ns L7={}ns total={}ns", timing.l2_ns, timing.l3_ns, timing.l4_ns, timing.l7_ns, timing.total_ns); }
cargo test --features parse_timing
What each counter covers (see the engine):
l2_ns: the link decoder. Choosing it (decoder_for) is not counted.l3_nsandl4_ns: the internet and transport stages.l7_ns: tunnel detection, the dispatch table and STP, and the whole parse of every inner flow: on a VXLAN packet, the inner Ethernet, IP and TCP are counted in the outerl7_ns. It stays at 0 for an anomalous TCP segment, which leaves before L7.total_ns: the whole call.
Measuring does not change the path: the pipeline is written once, over a TimingSink that does nothing for parse and reads the clock for parse_timed. parse_timed takes no ParseConfig, so a timed parse has no Decode As ports.
Known limitations
The parser is stateless: it sees one packet at a time, reassembles nothing, verifies no checksum and decrypts nothing. The application layer is a label, not a decode. The Limits page lists what follows from each of these, and what the crate exposes to detect it; the Protocols page lists every label. A protocol the crate does not decode can still be named by a parser of the caller (Custom parsers and rules).