use bitflags::bitflags;
use super::ids::{ExchangeId, GroupId, NodeId, ProtocolId, SessionId, VendorId};
use crate::bytes::Cursor;
use crate::error::{Error, ErrorCode, Result, bail};
pub const MESSAGE_FORMAT_VERSION: u8 = 0;
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MessageFlags: u8 {
const SOURCE_PRESENT = 0b0000_0100;
const DSIZ_0 = 0b0000_0001;
const DSIZ_1 = 0b0000_0010;
const VERSION = 0b1111_0000;
}
}
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SecurityFlags: u8 {
const PRIVACY = 0b1000_0000;
const CONTROL = 0b0100_0000;
const MESSAGE_EXTENSIONS = 0b0010_0000;
const SESSION_TYPE_0 = 0b0000_0001;
const SESSION_TYPE_1 = 0b0000_0010;
}
}
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExchangeFlags: u8 {
const INITIATOR = 0b0000_0001;
const ACKNOWLEDGEMENT = 0b0000_0010;
const RELIABILITY = 0b0000_0100;
const SECURED_EXTENSIONS = 0b0000_1000;
const VENDOR = 0b0001_0000;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum SessionType {
#[default]
Unicast,
Group,
}
impl SessionType {
const fn bits(self) -> u8 {
match self {
Self::Unicast => 0,
Self::Group => 1,
}
}
const fn from_bits(bits: u8) -> Result<Self> {
match bits & 0b11 {
0 => Ok(Self::Unicast),
1 => Ok(Self::Group),
_ => Err(Error::new(ErrorCode::MessageReserved)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Destination {
#[default]
None,
Node(NodeId),
Group(GroupId),
}
impl Destination {
const fn dsiz(self) -> u8 {
match self {
Self::None => 0,
Self::Node(_) => 1,
Self::Group(_) => 2,
}
}
const fn encoded_len(self) -> usize {
match self {
Self::None => 0,
Self::Node(_) => 8,
Self::Group(_) => 2,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MessageHeader {
pub session_id: SessionId,
pub session_type: SessionType,
pub privacy: bool,
pub control: bool,
pub message_counter: u32,
pub source: Option<NodeId>,
pub destination: Destination,
}
impl Default for MessageHeader {
fn default() -> Self {
Self {
session_id: SessionId::UNSECURED,
session_type: SessionType::Unicast,
privacy: false,
control: false,
message_counter: 0,
source: None,
destination: Destination::None,
}
}
}
impl MessageHeader {
#[must_use]
pub const fn is_unsecured(&self) -> bool {
matches!(self.session_type, SessionType::Unicast) && self.session_id.0 == 0
}
#[must_use]
pub const fn encoded_len(&self) -> usize {
const BASE: usize = 8;
let src = if self.source.is_some() { 8 } else { 0 };
BASE.saturating_add(src)
.saturating_add(self.destination.encoded_len())
}
pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
let mut w = Cursor::writer(out);
let mut flags = MessageFlags::from_bits_retain(MESSAGE_FORMAT_VERSION << 4);
if self.source.is_some() {
flags |= MessageFlags::SOURCE_PRESENT;
}
flags = MessageFlags::from_bits_retain(flags.bits() | self.destination.dsiz());
w.u8(flags.bits())?;
w.u16(self.session_id.0)?;
let mut security = SecurityFlags::from_bits_retain(self.session_type.bits());
if self.privacy {
security |= SecurityFlags::PRIVACY;
}
if self.control {
security |= SecurityFlags::CONTROL;
}
w.u8(security.bits())?;
w.u32(self.message_counter)?;
if let Some(source) = self.source {
w.u64(source.0)?;
}
match self.destination {
Destination::None => {}
Destination::Node(n) => w.u64(n.0)?,
Destination::Group(g) => w.u16(g.0)?,
}
Ok(w.position())
}
pub fn decode(buf: &[u8]) -> Result<(Self, &[u8])> {
let mut r = Cursor::reader(buf, ErrorCode::MessageTruncated);
let flags = MessageFlags::from_bits_retain(r.read_u8()?);
let version = (flags.bits() & MessageFlags::VERSION.bits()) >> 4;
if version != MESSAGE_FORMAT_VERSION {
bail!(UnsupportedVersion)
}
let session_id = SessionId(r.read_u16()?);
let security = SecurityFlags::from_bits_retain(r.read_u8()?);
let session_type = SessionType::from_bits(security.bits())?;
let message_counter = r.read_u32()?;
let source = if flags.contains(MessageFlags::SOURCE_PRESENT) {
Some(NodeId(r.read_u64()?))
} else {
None
};
let dsiz = flags.bits() & 0b11;
let destination = match dsiz {
0 => Destination::None,
1 => Destination::Node(NodeId(r.read_u64()?)),
2 => Destination::Group(GroupId(r.read_u16()?)),
_ => bail!(MessageReserved),
};
if security.contains(SecurityFlags::MESSAGE_EXTENSIONS) {
let len = usize::from(r.read_u16()?);
r.skip(len)?;
}
let header = Self {
session_id,
session_type,
privacy: security.contains(SecurityFlags::PRIVACY),
control: security.contains(SecurityFlags::CONTROL),
message_counter,
source,
destination,
};
Ok((header, r.rest()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProtocolHeader {
pub initiator: bool,
pub acknowledged_counter: Option<u32>,
pub reliability: bool,
pub exchange_id: ExchangeId,
pub protocol: ProtocolId,
pub opcode: u8,
}
impl Default for ProtocolHeader {
fn default() -> Self {
Self {
initiator: false,
acknowledged_counter: None,
reliability: false,
exchange_id: ExchangeId(0),
protocol: ProtocolId::SECURE_CHANNEL,
opcode: 0,
}
}
}
impl ProtocolHeader {
#[must_use]
pub const fn encoded_len(&self) -> usize {
const BASE: usize = 6;
let vendor = if self.protocol.is_common() { 0 } else { 2 };
let ack = if self.acknowledged_counter.is_some() {
4
} else {
0
};
BASE.saturating_add(vendor).saturating_add(ack)
}
pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
let mut w = Cursor::writer(out);
let mut flags = ExchangeFlags::empty();
if self.initiator {
flags |= ExchangeFlags::INITIATOR;
}
if self.acknowledged_counter.is_some() {
flags |= ExchangeFlags::ACKNOWLEDGEMENT;
}
if self.reliability {
flags |= ExchangeFlags::RELIABILITY;
}
if !self.protocol.is_common() {
flags |= ExchangeFlags::VENDOR;
}
w.u8(flags.bits())?;
w.u8(self.opcode)?;
w.u16(self.exchange_id.0)?;
if !self.protocol.is_common() {
w.u16(self.protocol.vendor.0)?;
}
w.u16(self.protocol.id)?;
if let Some(ack) = self.acknowledged_counter {
w.u32(ack)?;
}
Ok(w.position())
}
pub fn decode(buf: &[u8]) -> Result<(Self, &[u8])> {
let mut r = Cursor::reader(buf, ErrorCode::MessageTruncated);
let flags = ExchangeFlags::from_bits_retain(r.read_u8()?);
let opcode = r.read_u8()?;
let exchange_id = ExchangeId(r.read_u16()?);
let vendor = if flags.contains(ExchangeFlags::VENDOR) {
VendorId(r.read_u16()?)
} else {
VendorId::COMMON
};
let protocol = ProtocolId {
vendor,
id: r.read_u16()?,
};
let acknowledged_counter = if flags.contains(ExchangeFlags::ACKNOWLEDGEMENT) {
Some(r.read_u32()?)
} else {
None
};
if flags.contains(ExchangeFlags::SECURED_EXTENSIONS) {
let len = usize::from(r.read_u16()?);
r.skip(len)?;
}
let header = Self {
initiator: flags.contains(ExchangeFlags::INITIATOR),
acknowledged_counter,
reliability: flags.contains(ExchangeFlags::RELIABILITY),
exchange_id,
protocol,
opcode,
};
Ok((header, r.rest()))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn round_trip(header: &MessageHeader) {
let mut buf = [0u8; 64];
let n = header.encode(&mut buf).expect("encode");
assert_eq!(n, header.encoded_len(), "encoded_len disagrees with encode");
let (decoded, rest) = MessageHeader::decode(&buf[..n]).expect("decode");
assert_eq!(&decoded, header);
assert!(rest.is_empty());
}
#[test]
fn message_header_round_trips() {
round_trip(&MessageHeader::default());
round_trip(&MessageHeader {
session_id: SessionId(0x1234),
session_type: SessionType::Unicast,
message_counter: 0xDEAD_BEEF,
source: Some(NodeId(0x0102_0304_0506_0708)),
destination: Destination::Node(NodeId(1)),
..MessageHeader::default()
});
round_trip(&MessageHeader {
session_id: SessionId(5),
session_type: SessionType::Group,
destination: Destination::Group(GroupId(0x4242)),
control: true,
privacy: true,
..MessageHeader::default()
});
}
#[test]
fn the_wire_layout_is_little_endian_and_in_order() {
let header = MessageHeader {
session_id: SessionId(0x1234),
message_counter: 0x0A0B_0C0D,
source: Some(NodeId(0x1122_3344_5566_7788)),
destination: Destination::Group(GroupId(0xABCD)),
..MessageHeader::default()
};
let mut buf = [0u8; 64];
let n = header.encode(&mut buf).expect("encode");
assert_eq!(
&buf[..n],
&[
0x06, 0x34, 0x12, 0x00, 0x0D, 0x0C, 0x0B, 0x0A, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0xCD, 0xAB,
]
);
}
#[test]
fn a_reserved_version_is_dropped() {
let buf = [0x10, 0, 0, 0, 0, 0, 0, 0];
assert_eq!(
MessageHeader::decode(&buf).unwrap_err().code(),
ErrorCode::UnsupportedVersion
);
}
#[test]
fn a_reserved_dsiz_is_dropped() {
let buf = [0x03, 0, 0, 0, 0, 0, 0, 0];
assert_eq!(
MessageHeader::decode(&buf).unwrap_err().code(),
ErrorCode::MessageReserved
);
}
#[test]
fn a_reserved_session_type_is_dropped() {
let buf = [0x00, 0, 0, 0x02, 0, 0, 0, 0];
assert_eq!(
MessageHeader::decode(&buf).unwrap_err().code(),
ErrorCode::MessageReserved
);
}
#[test]
fn truncation_at_every_length_is_an_error_not_a_panic() {
let header = MessageHeader {
source: Some(NodeId(7)),
destination: Destination::Node(NodeId(8)),
..MessageHeader::default()
};
let mut buf = [0u8; 64];
let n = header.encode(&mut buf).expect("encode");
for cut in 0..n {
assert!(
MessageHeader::decode(&buf[..cut]).is_err(),
"a {cut}-octet header should not decode"
);
}
}
#[test]
fn a_too_small_buffer_is_an_error() {
let header = MessageHeader {
source: Some(NodeId(7)),
..MessageHeader::default()
};
let mut buf = [0u8; 4];
assert!(header.encode(&mut buf).is_err());
}
#[test]
fn message_extensions_are_skipped() {
let buf = [
0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0xAA, 0xBB, 0xCC, 0x99, ];
let (header, rest) = MessageHeader::decode(&buf).expect("decode");
assert_eq!(header.message_counter, 0);
assert_eq!(rest, &[0x99]);
}
#[test]
fn a_lying_extension_length_is_an_error() {
let buf = [0x00, 0, 0, 0x20, 0, 0, 0, 0, 0xFF, 0xFF, 0xAA];
assert_eq!(
MessageHeader::decode(&buf).unwrap_err().code(),
ErrorCode::MessageTruncated
);
}
fn protocol_round_trip(header: &ProtocolHeader) {
let mut buf = [0u8; 32];
let n = header.encode(&mut buf).expect("encode");
assert_eq!(n, header.encoded_len(), "encoded_len disagrees with encode");
let (decoded, rest) = ProtocolHeader::decode(&buf[..n]).expect("decode");
assert_eq!(&decoded, header);
assert!(rest.is_empty());
}
#[test]
fn protocol_header_round_trips() {
protocol_round_trip(&ProtocolHeader::default());
protocol_round_trip(&ProtocolHeader {
initiator: true,
reliability: true,
acknowledged_counter: Some(0x1234_5678),
exchange_id: ExchangeId(0xBEEF),
protocol: ProtocolId::INTERACTION_MODEL,
opcode: 0x02,
});
protocol_round_trip(&ProtocolHeader {
protocol: ProtocolId {
vendor: VendorId::TEST_1,
id: 0x0042,
},
..ProtocolHeader::default()
});
}
#[test]
fn a_vendor_protocol_carries_its_vendor_id() {
let common = ProtocolHeader::default();
let vendor = ProtocolHeader {
protocol: ProtocolId {
vendor: VendorId::TEST_1,
id: 1,
},
..ProtocolHeader::default()
};
assert_eq!(
vendor.encoded_len(),
common.encoded_len() + 2,
"the V flag adds exactly the Protocol Vendor ID field"
);
}
#[test]
fn payload_follows_the_protocol_header() {
let header = ProtocolHeader {
exchange_id: ExchangeId(1),
protocol: ProtocolId::INTERACTION_MODEL,
opcode: 5,
..ProtocolHeader::default()
};
let mut buf = [0u8; 32];
let n = header.encode(&mut buf).expect("encode");
buf[n] = 0xAB;
let (decoded, payload) = ProtocolHeader::decode(&buf[..=n]).expect("decode");
assert_eq!(decoded.opcode, 5);
assert_eq!(payload, &[0xAB]);
}
#[test]
fn protocol_truncation_is_an_error_not_a_panic() {
let header = ProtocolHeader {
acknowledged_counter: Some(1),
protocol: ProtocolId {
vendor: VendorId::TEST_1,
id: 1,
},
..ProtocolHeader::default()
};
let mut buf = [0u8; 32];
let n = header.encode(&mut buf).expect("encode");
for cut in 0..n {
assert!(ProtocolHeader::decode(&buf[..cut]).is_err(), "cut {cut}");
}
}
}