use pnet_base::MacAddr;
use pnet_packet::ethernet::EtherType;
use crate::protocols::craft;
use crate::protocols::error::{PacketError, Result};
use crate::protocols::sizes::ETH_HDR_LEN;
pub const VLAN_TAG_LEN: usize = 4;
pub const MAX_VLAN_TAGS: usize = 2;
const MAX_PAYLOAD_LEN: u16 = 1500;
const VLAN_TPIDS: [u16; 3] = [0x8100, 0x88A8, 0x9100];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct VlanTag {
pub protocol: u16,
pub id: u16,
pub priority: u8,
pub drop_eligible: bool,
}
impl VlanTag {
fn read(protocol: u16, tci: [u8; 2]) -> Self {
let tci = u16::from_be_bytes(tci);
Self {
protocol,
id: tci & 0x0FFF,
priority: (tci >> 13) as u8,
drop_eligible: tci & 0x1000 != 0,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Frame<'a> {
bytes: &'a [u8],
payload: &'a [u8],
ethertype: EtherType,
tags: [VlanTag; MAX_VLAN_TAGS],
depth: usize,
}
impl<'a> Frame<'a> {
pub fn destination(&self) -> MacAddr {
Self::mac_at(self.bytes, 0)
}
pub fn source(&self) -> MacAddr {
Self::mac_at(self.bytes, 6)
}
pub fn ethertype(&self) -> EtherType {
self.ethertype
}
pub fn vlans(&self) -> &[VlanTag] {
&self.tags[..self.depth]
}
pub fn payload(&self) -> &'a [u8] {
self.payload
}
pub fn bytes(&self) -> &'a [u8] {
self.bytes
}
pub fn payload_length(&self) -> Option<usize> {
(self.ethertype.0 <= MAX_PAYLOAD_LEN).then_some(usize::from(self.ethertype.0))
}
pub fn payload_as_claimed(&self) -> Option<&'a [u8]> {
match self.payload_length() {
Some(length) => self.payload.get(..length),
None => Some(self.payload),
}
}
fn mac_at(bytes: &[u8], offset: usize) -> MacAddr {
MacAddr::new(
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
bytes[offset + 4],
bytes[offset + 5],
)
}
}
pub fn build_header(src_mac: MacAddr, dst_mac: MacAddr, et: EtherType) -> Vec<u8> {
craft::Ethernet::new(src_mac, dst_mac)
.with_ethertype(et)
.header_bytes()
}
pub fn parse(frame_bytes: &'_ [u8]) -> Result<Frame<'_>> {
let short_of = |needed| PacketError::truncated("an Ethernet frame", needed, frame_bytes.len());
let mut ethertype = u16::from_be_bytes([
*frame_bytes.get(12).ok_or_else(|| short_of(ETH_HDR_LEN))?,
*frame_bytes.get(13).ok_or_else(|| short_of(ETH_HDR_LEN))?,
]);
let mut payload_offset = ETH_HDR_LEN;
let mut tags = [VlanTag {
protocol: 0,
id: 0,
priority: 0,
drop_eligible: false,
}; MAX_VLAN_TAGS];
let mut depth = 0;
while depth < MAX_VLAN_TAGS && VLAN_TPIDS.contains(ðertype) {
let through_tag = payload_offset + VLAN_TAG_LEN;
let tci = [
*frame_bytes
.get(payload_offset)
.ok_or_else(|| short_of(through_tag))?,
*frame_bytes
.get(payload_offset + 1)
.ok_or_else(|| short_of(through_tag))?,
];
let inner = u16::from_be_bytes([
*frame_bytes
.get(payload_offset + 2)
.ok_or_else(|| short_of(through_tag))?,
*frame_bytes
.get(payload_offset + 3)
.ok_or_else(|| short_of(through_tag))?,
]);
tags[depth] = VlanTag::read(ethertype, tci);
depth += 1;
payload_offset += VLAN_TAG_LEN;
ethertype = inner;
}
Ok(Frame {
bytes: frame_bytes,
payload: frame_bytes
.get(payload_offset..)
.ok_or_else(|| short_of(payload_offset))?,
ethertype: EtherType(ethertype),
tags,
depth,
})
}
#[cfg(test)]
mod tests {
use super::*;
use pnet_packet::ethernet::EtherTypes;
const DST: MacAddr = MacAddr(0x02, 0, 0, 0, 0, 1);
const SRC: MacAddr = MacAddr(0x02, 0, 0, 0, 0, 2);
fn frame_with(tags: &[(u16, u16)], ethertype: u16, payload: &[u8]) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.extend_from_slice(&[DST.0, DST.1, DST.2, DST.3, DST.4, DST.5]);
bytes.extend_from_slice(&[SRC.0, SRC.1, SRC.2, SRC.3, SRC.4, SRC.5]);
for (protocol, tci) in tags {
bytes.extend_from_slice(&protocol.to_be_bytes());
bytes.extend_from_slice(&tci.to_be_bytes());
}
bytes.extend_from_slice(ðertype.to_be_bytes());
bytes.extend_from_slice(payload);
bytes
}
#[test]
fn a_tagged_frame_reports_what_is_behind_the_tag() {
let bytes = frame_with(&[(0x8100, 0x0064)], EtherTypes::Ipv4.0, &[0xAB; 20]);
let frame = parse(&bytes).expect("a tagged frame parses");
assert_eq!(frame.ethertype(), EtherTypes::Ipv4);
assert_eq!(frame.payload(), &[0xAB; 20]);
assert_eq!(frame.source(), SRC, "a tag does not move the addresses");
assert_eq!(frame.destination(), DST);
}
#[test]
fn the_tag_itself_is_kept() {
let tci = (3 << 13) | 0x1000 | 100;
let bytes = frame_with(&[(0x8100, tci)], EtherTypes::Ipv6.0, &[]);
let frame = parse(&bytes).expect("a tagged frame parses");
assert_eq!(
frame.vlans(),
&[VlanTag {
protocol: 0x8100,
id: 100,
priority: 3,
drop_eligible: true,
}]
);
}
#[test]
fn a_stacked_tag_is_walked_to_the_protocol_behind_both() {
let bytes = frame_with(
&[(0x88A8, 0x0FA0), (0x8100, 0x0064)],
EtherTypes::Arp.0,
&[0xCD; 28],
);
let frame = parse(&bytes).expect("a QinQ frame parses");
assert_eq!(frame.ethertype(), EtherTypes::Arp);
assert_eq!(frame.payload(), &[0xCD; 28]);
assert_eq!(
frame.vlans().iter().map(|tag| tag.id).collect::<Vec<_>>(),
vec![4000, 100],
"outermost first"
);
}
#[test]
fn a_frame_of_nothing_but_tags_terminates_and_is_declined() {
let tags: Vec<(u16, u16)> = std::iter::repeat_n((0x8100, 1), 40).collect();
let bytes = frame_with(&tags, 0x8100, &[0u8; 8]);
let frame = parse(&bytes).expect("it parses rather than hanging");
assert_eq!(frame.vlans().len(), MAX_VLAN_TAGS, "the walk stopped");
assert_eq!(
frame.ethertype(),
EtherType(0x8100),
"and reports a tag protocol as the ethertype, which every reader declines"
);
}
#[test]
fn a_frame_ending_inside_a_tag_is_refused_rather_than_read_past() {
let bytes = frame_with(&[(0x8100, 0x0064)], EtherTypes::Ipv4.0, &[]);
for cut in ETH_HDR_LEN..bytes.len() {
let refused = parse(&bytes[..cut]);
let Err(PacketError::Truncated { needed, got, .. }) = refused else {
panic!("a frame cut to {cut} bytes claims a tag it does not carry: {refused:?}");
};
assert_eq!(got, cut);
assert!(
needed > got,
"a {got}-byte frame was refused for needing only {needed}"
);
}
assert!(parse(&bytes).is_ok(), "the whole frame still parses");
}
#[test]
fn an_untagged_frame_reads_as_it_always_did() {
let bytes = frame_with(&[], EtherTypes::Ipv4.0, &[0x11; 20]);
let frame = parse(&bytes).expect("an untagged frame parses");
assert_eq!(frame.ethertype(), EtherTypes::Ipv4);
assert_eq!(frame.payload(), &[0x11; 20]);
assert!(frame.vlans().is_empty());
}
}