#![allow(clippy::indexing_slicing)]
use alloc::vec::Vec;
use crate::common::{DecodeReason, Error, Result};
pub use crate::common::MacAddr;
pub const ETHERTYPE_GOOSE: u16 = 0x88B8;
pub const ETHERTYPE_GSE_MGMT: u16 = 0x88B9;
pub const ETHERTYPE_SV: u16 = 0x88BA;
pub const ETHERTYPE_VLAN: u16 = 0x8100;
pub const RESERVED1_SIMULATION: u16 = 0x8000;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct VlanTag {
pub priority: u8,
pub dei: bool,
pub id: u16,
}
impl VlanTag {
pub const DEFAULT: VlanTag = VlanTag { priority: 4, dei: false, id: 0 };
const fn tci(self) -> u16 {
((self.priority as u16 & 7) << 13) | ((self.dei as u16) << 12) | (self.id & 0x0FFF)
}
const fn from_tci(tci: u16) -> VlanTag {
VlanTag { priority: (tci >> 13) as u8, dei: tci & 0x1000 != 0, id: tci & 0x0FFF }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Frame<'a> {
pub dst: MacAddr,
pub src: MacAddr,
pub vlan: Option<VlanTag>,
pub ethertype: u16,
pub appid: u16,
pub length: u16,
pub reserved1: u16,
pub reserved2: u16,
pub apdu: &'a [u8],
pub apdu_offset: usize,
}
impl<'a> Frame<'a> {
pub fn parse(frame: &'a [u8]) -> Result<Frame<'a>> {
let err = |off| Error::decode(DecodeReason::NotProcessBusFrame, off);
if frame.len() < 14 {
return Err(err(0));
}
let mut dst = [0u8; 6];
let mut src = [0u8; 6];
dst.copy_from_slice(&frame[0..6]);
src.copy_from_slice(&frame[6..12]);
let mut pos = 12;
let mut ethertype = u16::from_be_bytes([frame[12], frame[13]]);
let mut vlan = None;
if ethertype == ETHERTYPE_VLAN {
let tci = frame.get(14..16).ok_or(err(14))?;
vlan = Some(VlanTag::from_tci(u16::from_be_bytes([tci[0], tci[1]])));
let et = frame.get(16..18).ok_or(err(16))?;
ethertype = u16::from_be_bytes([et[0], et[1]]);
pos = 16;
}
if ethertype != ETHERTYPE_GOOSE && ethertype != ETHERTYPE_SV && ethertype != ETHERTYPE_GSE_MGMT {
return Err(err(pos));
}
pos += 2;
let hdr = frame.get(pos..pos + 8).ok_or(err(pos))?;
let appid = u16::from_be_bytes([hdr[0], hdr[1]]);
let length = u16::from_be_bytes([hdr[2], hdr[3]]);
let reserved1 = u16::from_be_bytes([hdr[4], hdr[5]]);
let reserved2 = u16::from_be_bytes([hdr[6], hdr[7]]);
if length < 8 {
return Err(Error::decode(DecodeReason::BadLength, pos + 2));
}
let apdu_offset = pos + 8;
let apdu = frame.get(apdu_offset..pos + usize::from(length)).ok_or(Error::decode(DecodeReason::Truncated, apdu_offset))?;
Ok(Frame { dst: MacAddr(dst), src: MacAddr(src), vlan, ethertype, appid, length, reserved1, reserved2, apdu, apdu_offset })
}
pub const fn simulation(&self) -> bool {
self.reserved1 & RESERVED1_SIMULATION != 0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FrameAddress {
pub dst: MacAddr,
pub ethertype: u16,
pub appid: u16,
}
impl FrameAddress {
pub fn peek(frame: &[u8]) -> Option<FrameAddress> {
let mut dst = [0u8; 6];
dst.copy_from_slice(frame.get(0..6)?);
let mut pos = 12;
let mut ethertype = u16::from_be_bytes([*frame.get(12)?, *frame.get(13)?]);
if ethertype == ETHERTYPE_VLAN {
ethertype = u16::from_be_bytes([*frame.get(16)?, *frame.get(17)?]);
pos = 16;
}
if ethertype != ETHERTYPE_GOOSE && ethertype != ETHERTYPE_SV && ethertype != ETHERTYPE_GSE_MGMT {
return None;
}
let appid = u16::from_be_bytes([*frame.get(pos + 2)?, *frame.get(pos + 3)?]);
Some(FrameAddress { dst: MacAddr(dst), ethertype, appid })
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FrameHeader {
pub dst: MacAddr,
pub src: MacAddr,
pub vlan: Option<VlanTag>,
pub ethertype: u16,
pub appid: u16,
pub reserved1: u16,
pub reserved2: u16,
}
impl FrameHeader {
#[allow(clippy::len_without_is_empty)]
pub const fn len(&self) -> usize {
(if self.vlan.is_some() { 18 } else { 14 }) + 8
}
pub fn write(&self, apdu: &[u8], out: &mut [u8]) -> Result<usize> {
let total = self.len() + apdu.len();
if out.len() < total || apdu.len() + 8 > usize::from(u16::MAX) {
return Err(Error::Encode("frame buffer too small or APDU too large"));
}
out[0..6].copy_from_slice(&self.dst.0);
out[6..12].copy_from_slice(&self.src.0);
let mut pos = 12;
if let Some(v) = self.vlan {
out[12..14].copy_from_slice(ÐERTYPE_VLAN.to_be_bytes());
out[14..16].copy_from_slice(&v.tci().to_be_bytes());
pos = 16;
}
out[pos..pos + 2].copy_from_slice(&self.ethertype.to_be_bytes());
out[pos + 2..pos + 4].copy_from_slice(&self.appid.to_be_bytes());
out[pos + 4..pos + 6].copy_from_slice(&((apdu.len() + 8) as u16).to_be_bytes());
out[pos + 6..pos + 8].copy_from_slice(&self.reserved1.to_be_bytes());
out[pos + 8..pos + 10].copy_from_slice(&self.reserved2.to_be_bytes());
out[pos + 10..pos + 10 + apdu.len()].copy_from_slice(apdu);
Ok(total)
}
pub fn to_frame(&self, apdu: &[u8]) -> Result<Vec<u8>> {
let mut v = alloc::vec![0u8; self.len() + apdu.len()];
self.write(apdu, &mut v)?;
Ok(v)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn header_round_trip_with_vlan() {
let h = FrameHeader {
dst: MacAddr::GOOSE_BASE,
src: MacAddr([2, 0, 0, 0, 0, 1]),
vlan: Some(VlanTag { priority: 4, dei: false, id: 1 }),
ethertype: ETHERTYPE_GOOSE,
appid: 0x0003,
reserved1: RESERVED1_SIMULATION,
reserved2: 0,
};
let apdu = [0x61, 0x02, 0x80, 0x00];
let frame = h.to_frame(&apdu).unwrap();
assert_eq!(frame.len(), 18 + 8 + 4);
let p = Frame::parse(&frame).unwrap();
assert_eq!(p.vlan, h.vlan);
assert_eq!(p.appid, 3);
assert_eq!(p.length, 12);
assert!(p.simulation());
assert_eq!(p.apdu, &apdu);
assert_eq!(p.apdu_offset, 26);
assert!(p.dst.is_goose_multicast());
assert!(!p.dst.is_sv_multicast());
}
#[test]
fn rejects_non_process_bus() {
let mut f = [0u8; 60];
f[12] = 0x08;
assert!(Frame::parse(&f).is_err());
assert!(Frame::parse(&f[..10]).is_err());
let h = FrameHeader { dst: MacAddr::SV_BASE, src: MacAddr::default(), vlan: None, ethertype: ETHERTYPE_SV, appid: 0x4000, reserved1: 0, reserved2: 0 };
let mut frame = h.to_frame(&[0x60, 0x00]).unwrap();
frame[16] = 0xFF; assert!(Frame::parse(&frame).is_err());
}
#[test]
fn the_address_is_readable_even_when_the_frame_is_not() {
let h = FrameHeader {
dst: MacAddr::GOOSE_BASE,
src: MacAddr::default(),
vlan: Some(VlanTag::DEFAULT),
ethertype: ETHERTYPE_GOOSE,
appid: 0x0007,
reserved1: 0,
reserved2: 0,
};
let frame = h.to_frame(&[0x61, 0x02, 0x80, 0x00]).unwrap();
let want = FrameAddress { dst: MacAddr::GOOSE_BASE, ethertype: ETHERTYPE_GOOSE, appid: 7 };
assert_eq!(FrameAddress::peek(&frame), Some(want));
assert!(Frame::parse(&frame[..24]).is_err());
assert_eq!(FrameAddress::peek(&frame[..24]), Some(want));
assert_eq!(FrameAddress::peek(&[0u8; 60]), None);
assert_eq!(FrameAddress::peek(&frame[..8]), None);
}
#[test]
fn mac_parse_display() {
let m = MacAddr::parse("01-0c-cd-04-01-ff").unwrap();
assert!(m.is_sv_multicast());
assert_eq!(alloc::format!("{m}"), "01-0C-CD-04-01-FF");
assert!(MacAddr::parse("01-0c-cd").is_err());
}
}