use alloc::vec::Vec;
use crate::common::{DecodeReason, Error, Result};
pub const CR: u8 = 0xE0;
pub const CC: u8 = 0xD0;
pub const DR: u8 = 0x80;
pub const DC: u8 = 0xC0;
pub const DT: u8 = 0xF0;
pub const ER: u8 = 0x70;
pub const EOT: u8 = 0x80;
pub const PARAM_TPDU_SIZE: u8 = 0xC0;
pub const PARAM_SRC_TSAP: u8 = 0xC1;
pub const PARAM_DST_TSAP: u8 = 0xC2;
pub const TPDU_SIZE_MIN_EXP: u8 = 7;
pub const TPDU_SIZE_MAX_EXP: u8 = 13;
pub const fn tpdu_size(exp: u8) -> usize {
let e = if exp < TPDU_SIZE_MIN_EXP {
TPDU_SIZE_MIN_EXP
} else if exp > TPDU_SIZE_MAX_EXP {
TPDU_SIZE_MAX_EXP
} else {
exp
};
1usize << e
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Tsel(pub Vec<u8>);
impl Tsel {
pub fn new(bytes: impl Into<Vec<u8>>) -> Tsel {
Tsel(bytes.into())
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Tpdu<'a> {
ConnectionRequest(Connect),
ConnectionConfirm(Connect),
DisconnectRequest {
dst_ref: u16,
src_ref: u16,
reason: u8,
},
Data {
eot: bool,
payload: &'a [u8],
},
Other {
code: u8,
body: &'a [u8],
},
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Connect {
pub dst_ref: u16,
pub src_ref: u16,
pub class_options: u8,
pub tpdu_size_exp: Option<u8>,
pub src_tsel: Option<Tsel>,
pub dst_tsel: Option<Tsel>,
}
impl Connect {
pub fn request(src_ref: u16, src_tsel: Tsel, dst_tsel: Tsel, tpdu_size_exp: u8) -> Connect {
Connect {
dst_ref: 0,
src_ref,
class_options: 0,
tpdu_size_exp: Some(tpdu_size_exp.clamp(TPDU_SIZE_MIN_EXP, TPDU_SIZE_MAX_EXP)),
src_tsel: Some(src_tsel),
dst_tsel: Some(dst_tsel),
}
}
pub fn max_data(&self) -> usize {
tpdu_size(self.tpdu_size_exp.unwrap_or(TPDU_SIZE_MIN_EXP)).saturating_sub(3)
}
fn parse(body: &[u8]) -> Result<Connect> {
let (Some(&a), Some(&b), Some(&c), Some(&d), Some(&class)) = (body.first(), body.get(1), body.get(2), body.get(3), body.get(4)) else {
return Err(Error::decode(DecodeReason::Truncated, 0));
};
let mut out = Connect { dst_ref: u16::from_be_bytes([a, b]), src_ref: u16::from_be_bytes([c, d]), class_options: class, ..Connect::default() };
let mut rest = body.get(5..).unwrap_or(&[]);
while let Some((&code, tail)) = rest.split_first() {
let (&len, tail) = tail.split_first().ok_or(Error::decode(DecodeReason::Truncated, 0))?;
let value = tail.get(..usize::from(len)).ok_or(Error::decode(DecodeReason::Truncated, 0))?;
match code {
PARAM_TPDU_SIZE => out.tpdu_size_exp = value.first().copied(),
PARAM_SRC_TSAP => out.src_tsel = Some(Tsel::new(value)),
PARAM_DST_TSAP => out.dst_tsel = Some(Tsel::new(value)),
_ => {}
}
rest = tail.get(usize::from(len)..).unwrap_or(&[]);
}
Ok(out)
}
fn write(&self, code: u8, out: &mut Vec<u8>) -> Result<()> {
let start = out.len();
out.push(0); out.push(code);
out.extend_from_slice(&self.dst_ref.to_be_bytes());
out.extend_from_slice(&self.src_ref.to_be_bytes());
out.push(self.class_options);
if let Some(exp) = self.tpdu_size_exp {
out.extend_from_slice(&[PARAM_TPDU_SIZE, 1, exp]);
}
for (param, tsel) in [(PARAM_SRC_TSAP, &self.src_tsel), (PARAM_DST_TSAP, &self.dst_tsel)] {
if let Some(t) = tsel {
let len = u8::try_from(t.0.len()).map_err(|_| Error::Encode("transport selector too long"))?;
out.push(param);
out.push(len);
out.extend_from_slice(&t.0);
}
}
let li = out.len() - start - 1;
let li = u8::try_from(li).map_err(|_| Error::Encode("COTP header too long"))?;
match out.get_mut(start) {
Some(slot) => *slot = li,
None => return Err(Error::Encode("COTP header")),
}
Ok(())
}
}
impl<'a> Tpdu<'a> {
pub fn parse(tpdu: &'a [u8]) -> Result<Tpdu<'a>> {
let (&li, rest) = tpdu.split_first().ok_or(Error::decode(DecodeReason::Truncated, 0))?;
let header = rest.get(..usize::from(li)).ok_or(Error::decode(DecodeReason::Truncated, 1))?;
let payload = rest.get(usize::from(li)..).unwrap_or(&[]);
let (&code, body) = header.split_first().ok_or(Error::decode(DecodeReason::Truncated, 1))?;
Ok(match code {
CR => Tpdu::ConnectionRequest(Connect::parse(body)?),
CC => Tpdu::ConnectionConfirm(Connect::parse(body)?),
DR => {
let (Some(&a), Some(&b), Some(&c), Some(&d), Some(&reason)) = (body.first(), body.get(1), body.get(2), body.get(3), body.get(4)) else {
return Err(Error::decode(DecodeReason::Truncated, 1));
};
Tpdu::DisconnectRequest { dst_ref: u16::from_be_bytes([a, b]), src_ref: u16::from_be_bytes([c, d]), reason }
}
DT => {
let &nr_eot = body.first().ok_or(Error::decode(DecodeReason::Truncated, 1))?;
Tpdu::Data { eot: nr_eot & EOT != 0, payload }
}
_ => Tpdu::Other { code, body },
})
}
pub fn write(&self, out: &mut Vec<u8>) -> Result<()> {
match self {
Tpdu::ConnectionRequest(c) => c.write(CR, out),
Tpdu::ConnectionConfirm(c) => c.write(CC, out),
Tpdu::DisconnectRequest { dst_ref, src_ref, reason } => {
out.push(6);
out.push(DR);
out.extend_from_slice(&dst_ref.to_be_bytes());
out.extend_from_slice(&src_ref.to_be_bytes());
out.push(*reason);
Ok(())
}
Tpdu::Data { eot, payload } => {
out.extend_from_slice(&[2, DT, if *eot { EOT } else { 0 }]);
out.extend_from_slice(payload);
Ok(())
}
Tpdu::Other { code, body } => {
let li = u8::try_from(body.len() + 1).map_err(|_| Error::Encode("COTP header too long"))?;
out.push(li);
out.push(*code);
out.extend_from_slice(body);
Ok(())
}
}
}
}
#[derive(Debug)]
pub struct Reassembler {
parts: Vec<u8>,
limit: usize,
}
impl Reassembler {
pub fn new(limit: usize) -> Reassembler {
Reassembler { parts: Vec::new(), limit }
}
pub fn buffered(&self) -> usize {
self.parts.len()
}
pub fn reset(&mut self) {
self.parts.clear();
}
pub fn push<'a>(&'a mut self, eot: bool, payload: &'a [u8]) -> Result<Option<&'a [u8]>> {
if self.parts.is_empty() && eot {
return Ok(Some(payload));
}
if self.parts.len().saturating_add(payload.len()) > self.limit {
return Err(Error::LimitExceeded { limit: "max_tsdu", value: self.parts.len() + payload.len() });
}
self.parts.extend_from_slice(payload);
if eot { Ok(Some(&self.parts)) } else { Ok(None) }
}
pub fn take(&mut self) {
self.parts.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_reference_connection_request_round_trips() {
let wire = [0x11u8, 0xE0, 0x00, 0x00, 0xB0, 0x01, 0x00, 0xC0, 0x01, 0x0A, 0xC1, 0x02, 0x00, 0x01, 0xC2, 0x02, 0x00, 0x02];
let Tpdu::ConnectionRequest(cr) = Tpdu::parse(&wire).unwrap() else { panic!("not a CR") };
assert_eq!((cr.dst_ref, cr.src_ref, cr.class_options), (0, 0xB001, 0));
assert_eq!(cr.tpdu_size_exp, Some(10));
assert_eq!(cr.max_data(), 1021);
assert_eq!(cr.src_tsel, Some(Tsel::new([0, 1])));
assert_eq!(cr.dst_tsel, Some(Tsel::new([0, 2])));
let mut out = Vec::new();
Tpdu::ConnectionRequest(cr).write(&mut out).unwrap();
assert_eq!(out, wire, "re-encoding must reproduce the captured octets");
}
#[test]
fn the_reference_connection_confirm_round_trips() {
let wire = [0x09u8, 0xD0, 0xB0, 0x01, 0x18, 0x02, 0x00, 0xC0, 0x01, 0x0A];
let Tpdu::ConnectionConfirm(cc) = Tpdu::parse(&wire).unwrap() else { panic!("not a CC") };
assert_eq!((cc.dst_ref, cc.src_ref, cc.tpdu_size_exp), (0xB001, 0x1802, Some(10)));
assert_eq!(cc.src_tsel, None);
let mut out = Vec::new();
Tpdu::ConnectionConfirm(cc).write(&mut out).unwrap();
assert_eq!(out, wire);
}
#[test]
fn data_tpdus_carry_the_end_of_transmission_bit() {
let wire = [0x02u8, 0xF0, 0x80, 0xAA, 0xBB];
assert_eq!(Tpdu::parse(&wire).unwrap(), Tpdu::Data { eot: true, payload: &[0xAA, 0xBB] });
let mut out = Vec::new();
Tpdu::Data { eot: true, payload: &[0xAA, 0xBB] }.write(&mut out).unwrap();
assert_eq!(out, wire);
assert_eq!(Tpdu::parse(&[0x02, 0xF0, 0x00, 0xAA]).unwrap(), Tpdu::Data { eot: false, payload: &[0xAA] });
}
#[test]
fn a_segmented_tsdu_is_reassembled_and_a_whole_one_is_not_copied() {
let mut r = Reassembler::new(64);
assert_eq!(r.push(true, &[1, 2, 3]).unwrap(), Some(&[1, 2, 3][..]));
assert_eq!(r.buffered(), 0, "a TSDU that fits one TPDU is handed straight back");
r.take();
assert_eq!(r.push(false, &[1, 2]).unwrap(), None);
assert_eq!(r.push(false, &[3]).unwrap(), None);
assert_eq!(r.push(true, &[4, 5]).unwrap(), Some(&[1, 2, 3, 4, 5][..]));
r.take();
assert_eq!(r.buffered(), 0);
}
#[test]
fn a_tsdu_that_never_ends_is_refused_rather_than_buffered() {
let mut r = Reassembler::new(8);
assert!(r.push(false, &[0; 8]).is_ok());
assert!(matches!(r.push(false, &[0; 8]), Err(Error::LimitExceeded { .. })));
r.reset();
assert_eq!(r.buffered(), 0);
}
#[test]
fn truncation_and_unknown_codes_are_errors_or_data_never_panics() {
for cut in 0..6 {
let _ = Tpdu::parse(&[0x11, 0xE0, 0, 0, 0xB0, 0x01][..cut]);
}
assert!(Tpdu::parse(&[]).is_err());
assert!(Tpdu::parse(&[0x05, 0xE0, 0x00]).is_err(), "the length indicator must fit");
assert!(matches!(Tpdu::parse(&[0x02, 0x70, 0x01]).unwrap(), Tpdu::Other { code: ER, .. }));
}
#[test]
fn a_disconnect_request_round_trips() {
let wire = [0x06u8, 0x80, 0x18, 0x02, 0xB0, 0x01, 0x00];
let dr = Tpdu::parse(&wire).unwrap();
assert_eq!(dr, Tpdu::DisconnectRequest { dst_ref: 0x1802, src_ref: 0xB001, reason: 0 });
let mut out = Vec::new();
dr.write(&mut out).unwrap();
assert_eq!(out, wire);
}
}