use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use crate::ber::{Cursor, Encoder, Tag, Tlv};
use crate::common::{DecodeReason, Error, Limits, Result};
use crate::proto::data::tag;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Component {
pub name: Option<String>,
pub type_spec: TypeSpec,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TypeSpec {
Named {
domain: Option<String>,
item: String,
},
Array {
packed: bool,
elements: u32,
element_type: Box<TypeSpec>,
},
Structure {
packed: bool,
components: Vec<Component>,
},
Boolean,
BitString(i32),
Integer(u8),
Unsigned(u8),
FloatingPoint {
format_width: u8,
exponent_width: u8,
},
OctetString(i32),
VisibleString(i32),
GeneralizedTime,
BinaryTime(bool),
Bcd(u8),
MmsString(i32),
UtcTime,
Other(u32),
}
const FLOATING_POINT: u32 = 7;
impl TypeSpec {
pub fn parse(t: &Tlv<'_>, limits: &Limits) -> Result<TypeSpec> {
TypeSpec::parse_depth(t, limits, 0)
}
fn parse_depth(t: &Tlv<'_>, limits: &Limits, depth: usize) -> Result<TypeSpec> {
if depth > limits.max_depth {
return Err(Error::LimitExceeded { limit: "max_depth", value: depth });
}
if t.tag.class != crate::ber::Class::Context {
return Err(Error::decode(DecodeReason::UnexpectedTag, t.offset));
}
Ok(match t.tag.number {
0 => {
let name = super::ObjectName::parse(&t.children().next_required()?)?;
match name {
super::ObjectName::DomainSpecific { domain, item } => TypeSpec::Named { domain: Some(String::from(domain)), item: String::from(item) },
super::ObjectName::VmdSpecific(n) | super::ObjectName::AaSpecific(n) => TypeSpec::Named { domain: None, item: String::from(n) },
}
}
1 => {
let mut c = t.children();
let packed = c.next_if_tag(Tag::context(0))?.map(|t| t.boolean()).transpose()?.unwrap_or(false);
let elements = c.next_tag(Tag::context(1))?.unsigned_lenient_u32()?;
let element_type = TypeSpec::parse_depth(&c.next_tag(Tag::context_constructed(2))?.children().next_required()?, limits, depth + 1)?;
TypeSpec::Array { packed, elements, element_type: Box::new(element_type) }
}
2 => {
let mut c = t.children();
let packed = c.next_if_tag(Tag::context(0))?.map(|t| t.boolean()).transpose()?.unwrap_or(false);
let list = c.next_tag(Tag::context_constructed(1))?;
let mut components = Vec::new();
for item in list.children() {
if components.len() >= limits.max_dataset_members {
return Err(Error::LimitExceeded { limit: "max_dataset_members", value: components.len() + 1 });
}
let mut m = item?.expect(Tag::universal(crate::ber::universal::SEQUENCE, true))?.children();
let name = m.next_if_tag(Tag::context(0))?.map(|t| t.visible_string()).transpose()?.map(String::from);
let type_spec = TypeSpec::parse_depth(&m.next_tag(Tag::context_constructed(1))?.children().next_required()?, limits, depth + 1)?;
components.push(Component { name, type_spec });
}
TypeSpec::Structure { packed, components }
}
tag::BOOLEAN => TypeSpec::Boolean,
tag::BIT_STRING => TypeSpec::BitString(t.integer_i32()?),
tag::INTEGER => TypeSpec::Integer(width(t)?),
tag::UNSIGNED => TypeSpec::Unsigned(width(t)?),
FLOATING_POINT => {
let mut c = t.children();
let format_width = width(&next_width(&mut c, 0)?)?;
let exponent_width = width(&next_width(&mut c, 1)?)?;
TypeSpec::FloatingPoint { format_width, exponent_width }
}
tag::OCTET_STRING => TypeSpec::OctetString(t.integer_i32()?),
tag::VISIBLE_STRING => TypeSpec::VisibleString(t.integer_i32()?),
tag::GENERALIZED_TIME => TypeSpec::GeneralizedTime,
tag::BINARY_TIME => TypeSpec::BinaryTime(t.boolean()?),
tag::BCD => TypeSpec::Bcd(width(t)?),
tag::MMS_STRING => TypeSpec::MmsString(t.integer_i32()?),
tag::UTC_TIME => TypeSpec::UtcTime,
other => TypeSpec::Other(other),
})
}
pub fn write(&self, e: &mut Encoder) -> Result<()> {
match self {
TypeSpec::Named { domain, item } => {
e.constructed(Tag::context_constructed(0), |e| match domain {
Some(d) => super::ObjectName::DomainSpecific { domain: d, item }.write(e),
None => super::ObjectName::VmdSpecific(item).write(e),
})?;
}
TypeSpec::Array { packed, elements, element_type } => {
e.constructed(Tag::context_constructed(1), |e| {
if *packed {
e.boolean(Tag::context(0), true)?;
}
e.unsigned(Tag::context(1), u64::from(*elements))?;
e.constructed(Tag::context_constructed(2), |e| element_type.write(e))?;
Ok(())
})?;
}
TypeSpec::Structure { packed, components } => {
e.constructed(Tag::context_constructed(2), |e| {
if *packed {
e.boolean(Tag::context(0), true)?;
}
e.constructed(Tag::context_constructed(1), |e| {
for c in components {
e.constructed(Tag::universal(crate::ber::universal::SEQUENCE, true), |e| {
if let Some(n) = &c.name {
e.visible_string(Tag::context(0), n)?;
}
e.constructed(Tag::context_constructed(1), |e| c.type_spec.write(e))?;
Ok(())
})?;
}
Ok(())
})?;
Ok(())
})?;
}
TypeSpec::Boolean => {
e.primitive(Tag::context(tag::BOOLEAN), &[])?;
}
TypeSpec::BitString(n) => {
e.integer(Tag::context(tag::BIT_STRING), i64::from(*n))?;
}
TypeSpec::Integer(w) => {
e.unsigned(Tag::context(tag::INTEGER), u64::from(*w))?;
}
TypeSpec::Unsigned(w) => {
e.unsigned(Tag::context(tag::UNSIGNED), u64::from(*w))?;
}
TypeSpec::FloatingPoint { format_width, exponent_width } => {
e.constructed(Tag::context_constructed(FLOATING_POINT), |e| {
e.unsigned(Tag::universal(crate::ber::universal::INTEGER, false), u64::from(*format_width))?;
e.unsigned(Tag::universal(crate::ber::universal::INTEGER, false), u64::from(*exponent_width))?;
Ok(())
})?;
}
TypeSpec::OctetString(n) => {
e.integer(Tag::context(tag::OCTET_STRING), i64::from(*n))?;
}
TypeSpec::VisibleString(n) => {
e.integer(Tag::context(tag::VISIBLE_STRING), i64::from(*n))?;
}
TypeSpec::GeneralizedTime => {
e.primitive(Tag::context(tag::GENERALIZED_TIME), &[])?;
}
TypeSpec::BinaryTime(dated) => {
e.boolean(Tag::context(tag::BINARY_TIME), *dated)?;
}
TypeSpec::Bcd(n) => {
e.unsigned(Tag::context(tag::BCD), u64::from(*n))?;
}
TypeSpec::MmsString(n) => {
e.integer(Tag::context(tag::MMS_STRING), i64::from(*n))?;
}
TypeSpec::UtcTime => {
e.primitive(Tag::context(tag::UTC_TIME), &[])?;
}
TypeSpec::Other(n) => {
e.primitive(Tag::context(*n), &[])?;
}
}
Ok(())
}
pub fn component(&self, name: &str) -> Option<&TypeSpec> {
match self {
TypeSpec::Structure { components, .. } => components.iter().find(|c| c.name.as_deref() == Some(name)).map(|c| &c.type_spec),
_ => None,
}
}
pub fn component_names(&self) -> Vec<&str> {
match self {
TypeSpec::Structure { components, .. } => components.iter().filter_map(|c| c.name.as_deref()).collect(),
_ => Vec::new(),
}
}
}
fn next_width<'a>(c: &mut Cursor<'a>, tag: u32) -> Result<Tlv<'a>> {
let t = c.next_required()?;
if t.tag == Tag::universal(crate::ber::universal::INTEGER, false) || t.tag == Tag::context(tag) {
Ok(t)
} else {
Err(Error::decode(DecodeReason::UnexpectedTag, t.offset))
}
}
fn width(t: &Tlv<'_>) -> Result<u8> {
u8::try_from(t.unsigned_lenient_u32()?).map_err(|_| Error::decode(DecodeReason::BadValue, t.value_offset))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ber::Cursor;
fn round_trip(spec: &TypeSpec) -> TypeSpec {
let mut e = Encoder::new();
spec.write(&mut e).unwrap();
let bytes = e.into_vec();
let back = TypeSpec::parse(&Cursor::new(&bytes).next_required().unwrap(), &Limits::DEFAULT).unwrap();
assert_eq!(&back, spec);
back
}
#[test]
fn a_floating_point_type_is_the_octets_the_field_writes() {
const VENDOR: &[u8] = &[
0xa2, 0x31, 0xa1, 0x2f, 0x30, 0x1a, 0x80, 0x03, b'm', b'a', b'g', 0xa1, 0x13, 0xa2, 0x11, 0xa1, 0x0f, 0x30, 0x0d, 0x80, 0x01, b'f', 0xa1, 0x08,
0xa7, 0x06, 0x02, 0x01, 0x20, 0x02, 0x01, 0x08, 0x30, 0x08, 0x80, 0x01, b'q', 0xa1, 0x03, 0x84, 0x01, 0xf3, 0x30, 0x07, 0x80, 0x01, b't', 0xa1,
0x02, 0x91, 0x00,
];
let spec = TypeSpec::parse(&Cursor::new(VENDOR).next_required().unwrap(), &Limits::DEFAULT).expect("the field's octets decode");
assert_eq!(spec.component_names(), ["mag", "q", "t"]);
assert_eq!(spec.component("mag").and_then(|m| m.component("f")), Some(&TypeSpec::FloatingPoint { format_width: 32, exponent_width: 8 }));
let mut e = Encoder::new();
spec.write(&mut e).unwrap();
assert_eq!(e.into_vec(), VENDOR);
}
#[test]
fn the_older_context_tagged_widths_are_still_accepted() {
const LEGACY: &[u8] = &[0xa7, 0x06, 0x80, 0x01, 0x40, 0x81, 0x01, 0x0b];
let spec = TypeSpec::parse(&Cursor::new(LEGACY).next_required().unwrap(), &Limits::DEFAULT).expect("decode");
assert_eq!(spec, TypeSpec::FloatingPoint { format_width: 64, exponent_width: 11 });
assert!(TypeSpec::parse(&Cursor::new(&[0xa7, 0x06, 0x83, 0x01, 0x40, 0x81, 0x01, 0x0b]).next_required().unwrap(), &Limits::DEFAULT).is_err());
}
#[test]
fn the_shape_of_an_oper_is_what_a_client_needs_before_it_writes_one() {
let oper = TypeSpec::Structure {
packed: false,
components: alloc::vec![
Component { name: Some(String::from("ctlVal")), type_spec: TypeSpec::BitString(2) },
Component {
name: Some(String::from("origin")),
type_spec: TypeSpec::Structure {
packed: false,
components: alloc::vec![
Component { name: Some(String::from("orCat")), type_spec: TypeSpec::Integer(8) },
Component { name: Some(String::from("orIdent")), type_spec: TypeSpec::OctetString(-64) },
],
},
},
Component { name: Some(String::from("ctlNum")), type_spec: TypeSpec::Unsigned(8) },
Component { name: Some(String::from("T")), type_spec: TypeSpec::UtcTime },
Component { name: Some(String::from("Test")), type_spec: TypeSpec::Boolean },
Component { name: Some(String::from("Check")), type_spec: TypeSpec::BitString(2) },
],
};
let back = round_trip(&oper);
assert_eq!(back.component_names(), ["ctlVal", "origin", "ctlNum", "T", "Test", "Check"]);
assert_eq!(back.component("Check"), Some(&TypeSpec::BitString(2)));
assert_eq!(back.component("origin").and_then(|o| o.component("orIdent")), Some(&TypeSpec::OctetString(-64)));
}
#[test]
fn every_simple_type_round_trips() {
for spec in [
TypeSpec::Boolean,
TypeSpec::BitString(13),
TypeSpec::Integer(32),
TypeSpec::Unsigned(16),
TypeSpec::FloatingPoint { format_width: 32, exponent_width: 8 },
TypeSpec::OctetString(-8),
TypeSpec::VisibleString(129),
TypeSpec::GeneralizedTime,
TypeSpec::BinaryTime(true),
TypeSpec::Bcd(4),
TypeSpec::MmsString(-255),
TypeSpec::UtcTime,
TypeSpec::Named { domain: Some(String::from("LD0")), item: String::from("MyType") },
TypeSpec::Named { domain: None, item: String::from("Global") },
TypeSpec::Array { packed: false, elements: 4, element_type: Box::new(TypeSpec::Boolean) },
] {
round_trip(&spec);
}
}
#[test]
fn a_type_nested_deeper_than_the_limit_is_refused_rather_than_recursed() {
let deep =
(0..40).fold(TypeSpec::Boolean, |t, _| TypeSpec::Structure { packed: false, components: alloc::vec![Component { name: None, type_spec: t }] });
let mut e = Encoder::new();
deep.write(&mut e).unwrap();
let bytes = e.into_vec();
assert!(matches!(
TypeSpec::parse(&Cursor::new(&bytes).next_required().unwrap(), &Limits::DEFAULT),
Err(Error::LimitExceeded { limit: "max_depth", .. })
));
}
}