pub mod alternate;
pub mod association;
pub mod control;
pub mod file;
pub mod journal;
pub mod reject;
pub mod report;
pub mod typespec;
use alloc::vec::Vec;
pub use self::alternate::Path as AlternateAccess;
pub use self::alternate::Selector;
use crate::ber::{Class, Cursor, Encoder, Tag, Tlv, universal};
use crate::common::{DecodeReason, Error, Limits, Result};
use crate::proto::data::DataView;
use file::{DirectoryEntry, FileAttributes, FileName};
use journal::{AfterEntry, JournalEntry, RangeStart, RangeStop, TimeOfDay};
use reject::Reject;
use typespec::TypeSpec;
const TAG_IDENTIFIER: Tag = Tag::universal(universal::VISIBLE_STRING, false);
const TAG_INTEGER: Tag = Tag::universal(universal::INTEGER, false);
const TAG_SEQUENCE: Tag = Tag::universal(universal::SEQUENCE, true);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ObjectName<'a> {
VmdSpecific(&'a str),
DomainSpecific {
domain: &'a str,
item: &'a str,
},
AaSpecific(&'a str),
}
impl<'a> ObjectName<'a> {
pub fn parse(t: &Tlv<'a>) -> Result<ObjectName<'a>> {
if t.tag.class != Class::Context {
return Err(Error::decode(DecodeReason::UnexpectedTag, t.offset));
}
Ok(match t.tag.number {
0 => ObjectName::VmdSpecific(t.visible_string()?),
1 => {
let mut c = t.children();
let domain = c.next_tag(TAG_IDENTIFIER)?.visible_string()?;
let item = c.next_tag(TAG_IDENTIFIER)?.visible_string()?;
ObjectName::DomainSpecific { domain, item }
}
2 => ObjectName::AaSpecific(t.visible_string()?),
_ => return Err(Error::decode(DecodeReason::UnexpectedTag, t.offset)),
})
}
pub fn write(&self, e: &mut Encoder) -> Result<()> {
match self {
ObjectName::VmdSpecific(s) => {
e.visible_string(Tag::context(0), s)?;
}
ObjectName::DomainSpecific { domain, item } => {
e.constructed(Tag::context_constructed(1), |e| {
e.visible_string(TAG_IDENTIFIER, domain)?;
e.visible_string(TAG_IDENTIFIER, item)?;
Ok(())
})?;
}
ObjectName::AaSpecific(s) => {
e.visible_string(Tag::context(2), s)?;
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ServiceError {
pub class: u32,
pub code: i64,
pub additional: Option<i64>,
pub specific: Option<(u32, i64)>,
}
pub mod service_error {
pub const SERVICE_PREEMPT: u32 = 5;
pub const TIMEOUT: i64 = 1;
pub const FILE: u32 = 11;
pub const SERVICE: u32 = 4;
pub const PRIMITIVES_OUT_OF_SEQUENCE: i64 = 1;
}
impl ServiceError {
pub fn encode(tag: Tag, class: u32, code: i64) -> Result<Vec<u8>> {
let mut e = Encoder::new();
e.constructed(tag, |e| {
e.constructed(Tag::context_constructed(0), |e| {
e.integer(Tag::context(class), code)?;
Ok(())
})?;
Ok(())
})?;
Ok(e.into_vec())
}
pub fn encode_obtain_file(tag: Tag, class: u32, code: i64, side: i64) -> Result<Vec<u8>> {
let mut e = Encoder::new();
e.constructed(tag, |e| {
e.constructed(Tag::context_constructed(0), |e| {
e.integer(Tag::context(class), code)?;
Ok(())
})?;
e.constructed(Tag::context_constructed(3), |e| {
e.integer(Tag::context(0), side)?;
Ok(())
})?;
Ok(())
})?;
Ok(e.into_vec())
}
pub fn parse(t: &Tlv<'_>) -> Result<ServiceError> {
let mut out = ServiceError::default();
for field in t.children() {
let f = field?;
match (f.tag.class, f.tag.number) {
(Class::Context, 0) => {
let inner = f.children().next_required()?;
out.class = inner.tag.number;
out.code = inner.integer_i64().unwrap_or(0);
}
(Class::Context, 1) => out.additional = Some(f.integer_i64()?),
(Class::Context, 3) => {
if let Some(Ok(inner)) = f.children().next() {
out.specific = inner.integer_i64().ok().map(|v| (inner.tag.number, v));
}
}
_ => {}
}
}
Ok(out)
}
}
pub mod file_error {
pub const OTHER: i64 = 0;
pub const FILENAME_AMBIGUOUS: i64 = 1;
pub const FILE_BUSY: i64 = 2;
pub const FILENAME_SYNTAX_ERROR: i64 = 3;
pub const CONTENT_TYPE_INVALID: i64 = 4;
pub const POSITION_INVALID: i64 = 5;
pub const FILE_ACCESS_DENIED: i64 = 6;
pub const FILE_NON_EXISTENT: i64 = 7;
pub const DUPLICATE_FILENAME: i64 = 8;
pub const INSUFFICIENT_SPACE: i64 = 9;
}
pub mod obtain_file_error {
pub const SOURCE_FILE: i64 = 0;
pub const DESTINATION_FILE: i64 = 1;
}
pub mod object_class {
pub const NAMED_VARIABLE: i64 = 0;
pub const SCATTERED_ACCESS: i64 = 1;
pub const NAMED_VARIABLE_LIST: i64 = 2;
pub const NAMED_TYPE: i64 = 3;
pub const JOURNAL: i64 = 8;
pub const DOMAIN: i64 = 9;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ObjectScope<'a> {
VmdSpecific,
DomainSpecific(&'a str),
AaSpecific,
Other(Tlv<'a>),
}
impl<'a> ObjectScope<'a> {
pub fn parse(t: Tlv<'a>) -> Result<ObjectScope<'a>> {
if t.tag.class != Class::Context {
return Err(Error::decode(DecodeReason::UnexpectedTag, t.offset));
}
Ok(match t.tag.number {
0 => ObjectScope::VmdSpecific,
1 => ObjectScope::DomainSpecific(t.visible_string()?),
2 => ObjectScope::AaSpecific,
_ => ObjectScope::Other(t),
})
}
pub fn write(&self, e: &mut Encoder) -> Result<()> {
match self {
ObjectScope::VmdSpecific => {
e.primitive(Tag::context(0), &[])?;
}
ObjectScope::DomainSpecific(d) => {
e.visible_string(Tag::context(1), d)?;
}
ObjectScope::AaSpecific => {
e.primitive(Tag::context(2), &[])?;
}
ObjectScope::Other(t) => {
e.primitive(t.tag, t.value)?;
}
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum VariableSpecification<'a> {
Name(ObjectName<'a>),
Element {
name: ObjectName<'a>,
access: AlternateAccess<'a>,
},
Other(Tlv<'a>),
}
impl<'a> VariableSpecification<'a> {
pub const fn name(&self) -> Option<&ObjectName<'a>> {
match self {
VariableSpecification::Name(n) | VariableSpecification::Element { name: n, .. } => Some(n),
VariableSpecification::Other(_) => None,
}
}
pub const fn access(&self) -> Option<&AlternateAccess<'a>> {
match self {
VariableSpecification::Element { access, .. } => Some(access),
VariableSpecification::Name(_) | VariableSpecification::Other(_) => None,
}
}
pub fn of(name: ObjectName<'a>, access: AlternateAccess<'a>) -> VariableSpecification<'a> {
if access.is_empty() { VariableSpecification::Name(name) } else { VariableSpecification::Element { name, access } }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum VariableAccess<'a> {
ListOfVariable(Vec<VariableSpecification<'a>>),
VariableListName(ObjectName<'a>),
}
impl<'a> VariableAccess<'a> {
pub fn parse(t: &Tlv<'a>) -> Result<VariableAccess<'a>> {
match (t.tag.class, t.tag.number) {
(Class::Context, 0) => Ok(VariableAccess::ListOfVariable(parse_variable_list(t, &Limits::DEFAULT)?)),
(Class::Context, 1) => Ok(VariableAccess::VariableListName(ObjectName::parse(&t.children().next_required()?)?)),
_ => Err(Error::decode(DecodeReason::UnexpectedTag, t.offset)),
}
}
pub fn write(&self, e: &mut Encoder) -> Result<()> {
match self {
VariableAccess::ListOfVariable(items) => write_variable_list(items, Tag::context_constructed(0), e)?,
VariableAccess::VariableListName(n) => {
e.constructed(Tag::context_constructed(1), |e| n.write(e))?;
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccessResult<'a> {
Failure(i64),
Success(Tlv<'a>),
}
impl<'a> AccessResult<'a> {
pub fn value(&self) -> Option<DataView<'a>> {
match self {
AccessResult::Success(t) => DataView::from_tlv(*t).ok(),
AccessResult::Failure(_) => None,
}
}
fn parse(t: Tlv<'a>) -> Result<AccessResult<'a>> {
if t.tag == Tag::context(0) {
return Ok(AccessResult::Failure(t.integer_i64()?));
}
DataView::from_tlv(t)?;
Ok(AccessResult::Success(t))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WriteResult {
Failure(i64),
Success,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Initiate<'a> {
pub local_detail: Option<i64>,
pub max_serv_outstanding_calling: i64,
pub max_serv_outstanding_called: i64,
pub data_structure_nesting_level: Option<i64>,
pub version: i64,
pub parameter_cbb: (u8, &'a [u8]),
pub services_supported: (u8, &'a [u8]),
}
impl<'a> Initiate<'a> {
pub fn request(max_pdu: i64, outstanding: i64, parameter_cbb: (u8, &'a [u8]), services_supported: (u8, &'a [u8])) -> Initiate<'a> {
Initiate {
local_detail: Some(max_pdu),
max_serv_outstanding_calling: outstanding,
max_serv_outstanding_called: outstanding,
data_structure_nesting_level: Some(5),
version: 1,
parameter_cbb,
services_supported,
}
}
fn parse(t: &Tlv<'a>) -> Result<Initiate<'a>> {
let mut c = t.children();
let local_detail = c.next_if_tag(Tag::context(0))?.map(|t| t.integer_i64()).transpose()?;
let max_serv_outstanding_calling = c.next_tag(Tag::context(1))?.integer_i64()?;
let max_serv_outstanding_called = c.next_tag(Tag::context(2))?.integer_i64()?;
let data_structure_nesting_level = c.next_if_tag(Tag::context(3))?.map(|t| t.integer_i64()).transpose()?;
let detail = c.next_tag(Tag::context_constructed(4))?;
let mut d = detail.children();
let version = d.next_tag(Tag::context(0))?.integer_i64()?;
let parameter_cbb = d.next_tag(Tag::context(1))?.bit_string()?;
let services_supported = d.next_tag(Tag::context(2))?.bit_string()?;
Ok(Initiate {
local_detail,
max_serv_outstanding_calling,
max_serv_outstanding_called,
data_structure_nesting_level,
version,
parameter_cbb,
services_supported,
})
}
fn write(&self, tag: Tag, e: &mut Encoder) -> Result<()> {
e.constructed(tag, |e| {
if let Some(d) = self.local_detail {
e.integer(Tag::context(0), d)?;
}
e.integer(Tag::context(1), self.max_serv_outstanding_calling)?;
e.integer(Tag::context(2), self.max_serv_outstanding_called)?;
if let Some(n) = self.data_structure_nesting_level {
e.integer(Tag::context(3), n)?;
}
e.constructed(Tag::context_constructed(4), |e| {
e.integer(Tag::context(0), self.version)?;
e.bit_string(Tag::context(1), self.parameter_cbb.0, self.parameter_cbb.1)?;
e.bit_string(Tag::context(2), self.services_supported.0, self.services_supported.1)?;
Ok(())
})?;
Ok(())
})?;
Ok(())
}
}
pub mod delete_scope {
pub const SPECIFIC: i64 = 0;
pub const AA_SPECIFIC: i64 = 1;
pub const DOMAIN: i64 = 2;
pub const VMD: i64 = 3;
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ReadJournal<'a> {
pub name: Option<ObjectName<'a>>,
pub start: Option<RangeStart<'a>>,
pub stop: Option<RangeStop>,
pub variables: Vec<&'a str>,
pub after: Option<AfterEntry<'a>>,
}
impl<'a> ReadJournal<'a> {
pub fn by_time(name: ObjectName<'a>, from: TimeOfDay, to: Option<TimeOfDay>) -> ReadJournal<'a> {
ReadJournal { name: Some(name), start: Some(RangeStart::Time(from)), stop: to.map(RangeStop::Time), ..ReadJournal::default() }
}
pub fn after_entry(name: ObjectName<'a>, after: AfterEntry<'a>) -> ReadJournal<'a> {
ReadJournal { name: Some(name), after: Some(after), ..ReadJournal::default() }
}
fn parse(t: &Tlv<'a>) -> Result<ReadJournal<'a>> {
let mut c = t.children();
let name = match c.next_if_tag(Tag::context_constructed(0))? {
Some(n) => Some(ObjectName::parse(&n.children().next_required()?)?),
None => None,
};
let start = match c.next_if_tag(Tag::context_constructed(1))? {
Some(r) => {
let inner = r.children().next_required()?;
Some(match inner.tag.number {
0 => RangeStart::Time(TimeOfDay::from_octets(inner.value)?),
1 => RangeStart::Entry(inner.value),
_ => return Err(Error::decode(DecodeReason::UnexpectedTag, inner.offset)),
})
}
None => None,
};
let stop = match c.next_if_tag(Tag::context_constructed(2))? {
Some(r) => {
let inner = r.children().next_required()?;
Some(match inner.tag.number {
0 => RangeStop::Time(TimeOfDay::from_octets(inner.value)?),
1 => RangeStop::Count(inner.integer_i32()?),
_ => return Err(Error::decode(DecodeReason::UnexpectedTag, inner.offset)),
})
}
None => None,
};
let mut variables = Vec::new();
if let Some(list) = c.next_if_tag(Tag::context_constructed(4))? {
for v in list.children() {
variables.push(v?.visible_string()?);
}
}
let after = match c.next_if_tag(Tag::context_constructed(5))? {
Some(a) => {
let mut m = a.children();
let time = TimeOfDay::from_octets(m.next_tag(Tag::context(0))?.value)?;
let entry_id = m.next_tag(Tag::context(1))?.value;
Some(AfterEntry { time, entry_id })
}
None => None,
};
Ok(ReadJournal { name, start, stop, variables, after })
}
fn write(&self, e: &mut Encoder) -> Result<()> {
e.constructed(Tag::context_constructed(SERVICE_READ_JOURNAL), |e| {
if let Some(n) = &self.name {
e.constructed(Tag::context_constructed(0), |e| n.write(e))?;
}
if let Some(s) = &self.start {
e.constructed(Tag::context_constructed(1), |e| match s {
RangeStart::Time(t) => e.primitive(Tag::context(0), &t.to_octets()).map(|_| ()),
RangeStart::Entry(id) => e.primitive(Tag::context(1), id).map(|_| ()),
})?;
}
if let Some(s) = &self.stop {
e.constructed(Tag::context_constructed(2), |e| match s {
RangeStop::Time(t) => e.primitive(Tag::context(0), &t.to_octets()).map(|_| ()),
RangeStop::Count(n) => e.integer(Tag::context(1), i64::from(*n)).map(|_| ()),
})?;
}
if !self.variables.is_empty() {
e.constructed(Tag::context_constructed(4), |e| {
for v in &self.variables {
e.visible_string(TAG_VISIBLE_STRING, v)?;
}
Ok(())
})?;
}
if let Some(a) = &self.after {
e.constructed(Tag::context_constructed(5), |e| {
e.primitive(Tag::context(0), &a.time.to_octets())?;
e.primitive(Tag::context(1), a.entry_id)?;
Ok(())
})?;
}
Ok(())
})?;
Ok(())
}
}
const SERVICE_STATUS: u32 = 0;
const SERVICE_GET_VARIABLE_ACCESS_ATTRIBUTES: u32 = 6;
const SERVICE_GET_CAPABILITY_LIST: u32 = 71;
const SERVICE_DEFINE_NVL: u32 = 11;
const SERVICE_DELETE_NVL: u32 = 13;
const SERVICE_READ_JOURNAL: u32 = 65;
const SERVICE_OBTAIN_FILE: u32 = 46;
const SERVICE_FILE_OPEN: u32 = 72;
const SERVICE_FILE_READ: u32 = 73;
const SERVICE_FILE_CLOSE: u32 = 74;
const SERVICE_FILE_DELETE: u32 = 76;
const SERVICE_FILE_DIRECTORY: u32 = 77;
const TAG_VISIBLE_STRING: Tag = Tag::universal(universal::VISIBLE_STRING, false);
pub mod vmd_logical {
pub const STATE_CHANGES_ALLOWED: i64 = 0;
pub const NO_STATE_CHANGES_ALLOWED: i64 = 1;
pub const LIMITED_SERVICES_ALLOWED: i64 = 2;
pub const SUPPORT_SERVICES_ALLOWED: i64 = 3;
}
pub mod vmd_physical {
pub const OPERATIONAL: i64 = 0;
pub const PARTIALLY_OPERATIONAL: i64 = 1;
pub const INOPERABLE: i64 = 2;
pub const NEEDS_COMMISSIONING: i64 = 3;
}
#[derive(Clone, Debug, PartialEq)]
pub enum ConfirmedRequest<'a> {
Status {
extended_derivation: bool,
},
GetCapabilityList {
continue_after: Option<&'a str>,
},
GetNameList {
object_class: i64,
scope: ObjectScope<'a>,
continue_after: Option<&'a str>,
},
Identify,
Read {
specification_with_result: bool,
access: VariableAccess<'a>,
},
Write {
access: VariableAccess<'a>,
values: Vec<Tlv<'a>>,
},
GetNamedVariableListAttributes(ObjectName<'a>),
GetVariableAccessAttributes(ObjectName<'a>),
DefineNamedVariableList {
name: ObjectName<'a>,
variables: Vec<VariableSpecification<'a>>,
},
DeleteNamedVariableList {
scope: i64,
names: Vec<ObjectName<'a>>,
domain: Option<&'a str>,
},
ReadJournal(ReadJournal<'a>),
ObtainFile {
source_server: Option<&'a [u8]>,
source: FileName<'a>,
destination: FileName<'a>,
},
FileOpen {
name: FileName<'a>,
position: u32,
},
FileRead(i32),
FileClose(i32),
FileDelete(FileName<'a>),
FileDirectory {
specification: Option<FileName<'a>>,
continue_after: Option<FileName<'a>>,
},
Other(Tlv<'a>),
}
#[derive(Clone, Debug, PartialEq)]
pub enum ConfirmedResponse<'a> {
Status {
logical: i64,
physical: i64,
local_detail: Option<(u8, &'a [u8])>,
},
GetCapabilityList {
capabilities: Vec<&'a str>,
more_follows: bool,
},
GetNameList {
identifiers: Vec<&'a str>,
more_follows: bool,
},
Identify {
vendor: &'a str,
model: &'a str,
revision: &'a str,
},
Read {
access: Option<VariableAccess<'a>>,
results: Vec<AccessResult<'a>>,
},
Write(Vec<WriteResult>),
GetNamedVariableListAttributes {
deletable: bool,
variables: Vec<VariableSpecification<'a>>,
},
GetVariableAccessAttributes {
deletable: bool,
type_spec: TypeSpec,
},
DefineNamedVariableList,
DeleteNamedVariableList {
matched: u32,
deleted: u32,
},
ReadJournal {
entries: Vec<JournalEntry<'a>>,
more_follows: bool,
},
ObtainFile,
FileOpen {
frsm_id: i32,
attributes: FileAttributes<'a>,
},
FileRead {
data: &'a [u8],
more_follows: bool,
},
FileClose,
FileDelete,
FileDirectory {
entries: Vec<DirectoryEntry<'a>>,
more_follows: bool,
},
Other(Tlv<'a>),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Unconfirmed<'a> {
InformationReport {
access: VariableAccess<'a>,
results: Vec<AccessResult<'a>>,
},
Other(Tlv<'a>),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Mms<'a> {
ConfirmedRequest {
invoke_id: i64,
service: ConfirmedRequest<'a>,
},
ConfirmedResponse {
invoke_id: i64,
service: ConfirmedResponse<'a>,
},
ConfirmedError {
invoke_id: i64,
modifier_position: Option<u32>,
error: Tlv<'a>,
},
Unconfirmed(Unconfirmed<'a>),
Reject(Reject),
CancelRequest(i64),
CancelResponse(i64),
CancelError {
invoke_id: i64,
error: Tlv<'a>,
},
InitiateRequest(Initiate<'a>),
InitiateResponse(Initiate<'a>),
InitiateError(Tlv<'a>),
ConcludeRequest,
ConcludeResponse,
ConcludeError(Tlv<'a>),
Other(Tlv<'a>),
}
fn parse_access_results<'a>(t: &Tlv<'a>, limits: &Limits) -> Result<Vec<AccessResult<'a>>> {
let mut out = Vec::new();
for r in t.children() {
if out.len() >= limits.max_dataset_members {
return Err(Error::LimitExceeded { limit: "max_dataset_members", value: out.len() + 1 });
}
out.push(AccessResult::parse(r?)?);
}
Ok(out)
}
fn parse_variable_list<'a>(t: &Tlv<'a>, limits: &Limits) -> Result<Vec<VariableSpecification<'a>>> {
let mut out = Vec::new();
for item in t.children() {
if out.len() >= limits.max_dataset_members {
return Err(Error::LimitExceeded { limit: "max_dataset_members", value: out.len() + 1 });
}
let mut c = item?.expect(TAG_SEQUENCE)?.children();
let spec = c.next_required()?;
out.push(if spec.tag == Tag::context_constructed(0) {
let name = ObjectName::parse(&spec.children().next_required()?)?;
match alternate::next_alternate(&mut c)? {
Some(access) => VariableSpecification::Element { name, access },
None => VariableSpecification::Name(name),
}
} else {
VariableSpecification::Other(spec)
});
}
Ok(out)
}
fn write_variable_list(items: &[VariableSpecification<'_>], tag: Tag, e: &mut Encoder) -> Result<()> {
e.constructed(tag, |e| {
for item in items {
e.constructed(TAG_SEQUENCE, |e| match item {
VariableSpecification::Name(n) => e.constructed(Tag::context_constructed(0), |e| n.write(e)).map(|_| ()),
VariableSpecification::Element { name, access } => {
e.constructed(Tag::context_constructed(0), |e| name.write(e))?;
access.write(e)
}
VariableSpecification::Other(t) => e.primitive(t.tag, t.value).map(|_| ()),
})?;
}
Ok(())
})?;
Ok(())
}
fn write_access_results(results: &[AccessResult<'_>], tag: Tag, e: &mut Encoder) -> Result<()> {
e.constructed(tag, |e| {
for r in results {
match r {
AccessResult::Failure(code) => {
e.integer(Tag::context(0), *code)?;
}
AccessResult::Success(t) => {
e.primitive(t.tag, t.value)?;
}
}
}
Ok(())
})?;
Ok(())
}
impl<'a> ConfirmedRequest<'a> {
#[allow(clippy::too_many_lines)]
fn parse(t: Tlv<'a>, limits: &Limits) -> Result<ConfirmedRequest<'a>> {
if t.tag.class != Class::Context {
return Err(Error::decode(DecodeReason::UnexpectedTag, t.offset));
}
Ok(match t.tag.number {
1 => {
let mut c = t.children();
let object_class = c.next_tag(Tag::context_constructed(0))?.children().next_required()?.integer_i64()?;
let scope = ObjectScope::parse(c.next_tag(Tag::context_constructed(1))?.children().next_required()?)?;
let continue_after = c.next_if_tag(Tag::context(2))?.map(|t| t.visible_string()).transpose()?;
ConfirmedRequest::GetNameList { object_class, scope, continue_after }
}
SERVICE_STATUS => ConfirmedRequest::Status { extended_derivation: t.boolean()? },
2 => ConfirmedRequest::Identify,
SERVICE_GET_CAPABILITY_LIST => {
ConfirmedRequest::GetCapabilityList { continue_after: t.children().next_if_tag(TAG_VISIBLE_STRING)?.map(|s| s.visible_string()).transpose()? }
}
4 => {
let mut c = t.children();
let specification_with_result = c.next_if_tag(Tag::context(0))?.map(|t| t.boolean()).transpose()?.unwrap_or(false);
let access = VariableAccess::parse(&c.next_tag(Tag::context_constructed(1))?.children().next_required()?)?;
ConfirmedRequest::Read { specification_with_result, access }
}
5 => {
let mut c = t.children();
let access = VariableAccess::parse(&c.next_required()?)?;
let list = c.next_tag(Tag::context_constructed(0))?;
let mut values = Vec::new();
for v in list.children() {
if values.len() >= limits.max_dataset_members {
return Err(Error::LimitExceeded { limit: "max_dataset_members", value: values.len() + 1 });
}
let v = v?;
DataView::from_tlv(v)?;
values.push(v);
}
ConfirmedRequest::Write { access, values }
}
12 => ConfirmedRequest::GetNamedVariableListAttributes(ObjectName::parse(&t.children().next_required()?)?),
SERVICE_GET_VARIABLE_ACCESS_ATTRIBUTES => {
let name = t.children().next_tag(Tag::context_constructed(0))?;
ConfirmedRequest::GetVariableAccessAttributes(ObjectName::parse(&name.children().next_required()?)?)
}
SERVICE_DEFINE_NVL => {
let mut c = t.children();
let name = ObjectName::parse(&c.next_required()?)?;
let variables = parse_variable_list(&c.next_tag(Tag::context_constructed(0))?, limits)?;
ConfirmedRequest::DefineNamedVariableList { name, variables }
}
SERVICE_DELETE_NVL => {
let mut c = t.children();
let scope = c.next_if_tag(Tag::context(0))?.map(|t| t.integer_i64()).transpose()?.unwrap_or(delete_scope::SPECIFIC);
let mut names = Vec::new();
if let Some(list) = c.next_if_tag(Tag::context_constructed(1))? {
for n in list.children() {
if names.len() >= limits.max_list_items {
return Err(Error::LimitExceeded { limit: "max_list_items", value: names.len() + 1 });
}
names.push(ObjectName::parse(&n?)?);
}
}
let domain = c.next_if_tag(Tag::context(2))?.map(|t| t.visible_string()).transpose()?;
ConfirmedRequest::DeleteNamedVariableList { scope, names, domain }
}
SERVICE_READ_JOURNAL => ConfirmedRequest::ReadJournal(ReadJournal::parse(&t)?),
SERVICE_OBTAIN_FILE => {
let mut c = t.children();
let source_server = c.next_if_tag(Tag::context_constructed(0))?.map(|t| t.value);
let source = FileName::parse(&c.next_tag(Tag::context_constructed(1))?, limits)?;
let destination = FileName::parse(&c.next_tag(Tag::context_constructed(2))?, limits)?;
ConfirmedRequest::ObtainFile { source_server, source, destination }
}
SERVICE_FILE_OPEN => {
let mut c = t.children();
let name = FileName::parse(&c.next_tag(Tag::context_constructed(0))?, limits)?;
let position = c.next_tag(Tag::context(1))?.unsigned_lenient_u32()?;
ConfirmedRequest::FileOpen { name, position }
}
SERVICE_FILE_READ => ConfirmedRequest::FileRead(t.integer_i32()?),
SERVICE_FILE_CLOSE => ConfirmedRequest::FileClose(t.integer_i32()?),
SERVICE_FILE_DELETE => ConfirmedRequest::FileDelete(FileName::parse(&t, limits)?),
SERVICE_FILE_DIRECTORY => {
let mut c = t.children();
let specification = c.next_if_tag(Tag::context_constructed(0))?.map(|t| FileName::parse(&t, limits)).transpose()?;
let continue_after = c.next_if_tag(Tag::context_constructed(1))?.map(|t| FileName::parse(&t, limits)).transpose()?;
ConfirmedRequest::FileDirectory { specification, continue_after }
}
_ => ConfirmedRequest::Other(t),
})
}
#[allow(clippy::too_many_lines)]
fn write(&self, e: &mut Encoder) -> Result<()> {
match self {
ConfirmedRequest::GetNameList { object_class, scope, continue_after } => {
e.constructed(Tag::context_constructed(1), |e| {
e.constructed(Tag::context_constructed(0), |e| {
e.integer(Tag::context(0), *object_class)?;
Ok(())
})?;
e.constructed(Tag::context_constructed(1), |e| scope.write(e))?;
if let Some(after) = continue_after {
e.visible_string(Tag::context(2), after)?;
}
Ok(())
})?;
}
ConfirmedRequest::Status { extended_derivation } => {
e.boolean(Tag::context(SERVICE_STATUS), *extended_derivation)?;
}
ConfirmedRequest::GetCapabilityList { continue_after } => {
e.constructed(Tag::context_constructed(SERVICE_GET_CAPABILITY_LIST), |e| {
if let Some(after) = continue_after {
e.visible_string(TAG_VISIBLE_STRING, after)?;
}
Ok(())
})?;
}
ConfirmedRequest::Identify => {
e.primitive(Tag::context(2), &[])?;
}
ConfirmedRequest::Read { specification_with_result, access } => {
e.constructed(Tag::context_constructed(4), |e| {
if *specification_with_result {
e.boolean(Tag::context(0), true)?;
}
e.constructed(Tag::context_constructed(1), |e| access.write(e))?;
Ok(())
})?;
}
ConfirmedRequest::Write { access, values } => {
e.constructed(Tag::context_constructed(5), |e| {
access.write(e)?;
e.constructed(Tag::context_constructed(0), |e| {
for v in values {
e.primitive(v.tag, v.value)?;
}
Ok(())
})?;
Ok(())
})?;
}
ConfirmedRequest::GetNamedVariableListAttributes(name) => {
e.constructed(Tag::context_constructed(12), |e| name.write(e))?;
}
ConfirmedRequest::GetVariableAccessAttributes(name) => {
e.constructed(Tag::context_constructed(SERVICE_GET_VARIABLE_ACCESS_ATTRIBUTES), |e| {
e.constructed(Tag::context_constructed(0), |e| name.write(e))?;
Ok(())
})?;
}
ConfirmedRequest::DefineNamedVariableList { name, variables } => {
e.constructed(Tag::context_constructed(SERVICE_DEFINE_NVL), |e| {
name.write(e)?;
write_variable_list(variables, Tag::context_constructed(0), e)
})?;
}
ConfirmedRequest::DeleteNamedVariableList { scope, names, domain } => {
e.constructed(Tag::context_constructed(SERVICE_DELETE_NVL), |e| {
if *scope != delete_scope::SPECIFIC {
e.integer(Tag::context(0), *scope)?;
}
if !names.is_empty() {
e.constructed(Tag::context_constructed(1), |e| {
for n in names {
n.write(e)?;
}
Ok(())
})?;
}
if let Some(d) = domain {
e.visible_string(Tag::context(2), d)?;
}
Ok(())
})?;
}
ConfirmedRequest::ReadJournal(r) => r.write(e)?,
ConfirmedRequest::ObtainFile { source_server, source, destination } => {
e.constructed(Tag::context_constructed(SERVICE_OBTAIN_FILE), |e| {
if let Some(server) = source_server {
e.constructed(Tag::context_constructed(0), |e| {
e.raw(server);
Ok(())
})?;
}
e.constructed(Tag::context_constructed(1), |e| {
source.write_contents(e);
Ok(())
})?;
e.constructed(Tag::context_constructed(2), |e| {
destination.write_contents(e);
Ok(())
})?;
Ok(())
})?;
}
ConfirmedRequest::FileOpen { name, position } => {
e.constructed(Tag::context_constructed(SERVICE_FILE_OPEN), |e| {
e.constructed(Tag::context_constructed(0), |e| {
name.write_contents(e);
Ok(())
})?;
e.unsigned(Tag::context(1), u64::from(*position))?;
Ok(())
})?;
}
ConfirmedRequest::FileRead(id) => {
e.integer(Tag::context(SERVICE_FILE_READ), i64::from(*id))?;
}
ConfirmedRequest::FileClose(id) => {
e.integer(Tag::context(SERVICE_FILE_CLOSE), i64::from(*id))?;
}
ConfirmedRequest::FileDelete(name) => {
e.constructed(Tag::context_constructed(SERVICE_FILE_DELETE), |e| {
name.write_contents(e);
Ok(())
})?;
}
ConfirmedRequest::FileDirectory { specification, continue_after } => {
e.constructed(Tag::context_constructed(SERVICE_FILE_DIRECTORY), |e| {
if let Some(n) = specification {
e.constructed(Tag::context_constructed(0), |e| {
n.write_contents(e);
Ok(())
})?;
}
if let Some(n) = continue_after {
e.constructed(Tag::context_constructed(1), |e| {
n.write_contents(e);
Ok(())
})?;
}
Ok(())
})?;
}
ConfirmedRequest::Other(t) => {
e.primitive(t.tag, t.value)?;
}
}
Ok(())
}
}
impl<'a> ConfirmedResponse<'a> {
#[allow(clippy::too_many_lines)]
fn parse(t: Tlv<'a>, limits: &Limits) -> Result<ConfirmedResponse<'a>> {
if t.tag.class != Class::Context {
return Err(Error::decode(DecodeReason::UnexpectedTag, t.offset));
}
Ok(match t.tag.number {
SERVICE_STATUS => {
let mut c = t.children();
let logical = c.next_tag(Tag::context(0))?.integer_i64()?;
let physical = c.next_tag(Tag::context(1))?.integer_i64()?;
let local_detail = c.next_if_tag(Tag::context(2))?.map(|t| t.bit_string()).transpose()?;
ConfirmedResponse::Status { logical, physical, local_detail }
}
SERVICE_GET_CAPABILITY_LIST => {
let mut c = t.children();
let list = c.next_tag(Tag::context_constructed(0))?;
let mut capabilities = Vec::new();
for cap in list.children() {
if capabilities.len() >= limits.max_list_items {
return Err(Error::LimitExceeded { limit: "max_list_items", value: capabilities.len() + 1 });
}
capabilities.push(cap?.expect(TAG_VISIBLE_STRING)?.visible_string()?);
}
let more_follows = c.next_if_tag(Tag::context(1))?.map(|t| t.boolean()).transpose()?.unwrap_or(true);
ConfirmedResponse::GetCapabilityList { capabilities, more_follows }
}
1 => {
let mut c = t.children();
let list = c.next_tag(Tag::context_constructed(0))?;
let mut identifiers = Vec::new();
for id in list.children() {
if identifiers.len() >= limits.max_list_items {
return Err(Error::LimitExceeded { limit: "max_list_items", value: identifiers.len() + 1 });
}
identifiers.push(id?.expect(TAG_IDENTIFIER)?.visible_string()?);
}
let more_follows = c.next_if_tag(Tag::context(1))?.map(|t| t.boolean()).transpose()?.unwrap_or(true);
ConfirmedResponse::GetNameList { identifiers, more_follows }
}
2 => {
let mut c = t.children();
let vendor = c.next_tag(Tag::context(0))?.visible_string()?;
let model = c.next_tag(Tag::context(1))?.visible_string()?;
let revision = c.next_tag(Tag::context(2))?.visible_string()?;
ConfirmedResponse::Identify { vendor, model, revision }
}
4 => {
let mut c = t.children();
let access = match c.next_if_tag(Tag::context_constructed(0))? {
Some(a) => Some(VariableAccess::parse(&a.children().next_required()?)?),
None => None,
};
let results = parse_access_results(&c.next_tag(Tag::context_constructed(1))?, limits)?;
ConfirmedResponse::Read { access, results }
}
5 => {
let mut out = Vec::new();
for r in t.children() {
let r = r?;
out.push(match r.tag.number {
0 => WriteResult::Failure(r.integer_i64()?),
_ => WriteResult::Success,
});
}
ConfirmedResponse::Write(out)
}
12 => {
let mut c = t.children();
let deletable = c.next_if_tag(Tag::context(0))?.map(|t| t.boolean()).transpose()?.unwrap_or(false);
let variables = parse_variable_list(&c.next_tag(Tag::context_constructed(1))?, limits)?;
ConfirmedResponse::GetNamedVariableListAttributes { deletable, variables }
}
SERVICE_GET_VARIABLE_ACCESS_ATTRIBUTES => {
let mut c = t.children();
let deletable = c.next_if_tag(Tag::context(0))?.map(|t| t.boolean()).transpose()?.unwrap_or(false);
let _ = c.next_if_tag(Tag::context_constructed(1))?;
let type_spec = TypeSpec::parse(&c.next_tag(Tag::context_constructed(2))?.children().next_required()?, limits)?;
ConfirmedResponse::GetVariableAccessAttributes { deletable, type_spec }
}
SERVICE_DEFINE_NVL => ConfirmedResponse::DefineNamedVariableList,
SERVICE_DELETE_NVL => {
let mut c = t.children();
let matched = c.next_tag(Tag::context(0))?.unsigned_lenient_u32()?;
let deleted = c.next_tag(Tag::context(1))?.unsigned_lenient_u32()?;
ConfirmedResponse::DeleteNamedVariableList { matched, deleted }
}
SERVICE_READ_JOURNAL => {
let mut c = t.children();
let list = c.next_tag(Tag::context_constructed(0))?;
let mut entries = Vec::new();
for entry in list.children() {
if entries.len() >= limits.max_list_items {
return Err(Error::LimitExceeded { limit: "max_list_items", value: entries.len() + 1 });
}
entries.push(JournalEntry::parse(&entry?, limits)?);
}
let more_follows = c.next_if_tag(Tag::context(1))?.map(|t| t.boolean()).transpose()?.unwrap_or(false);
ConfirmedResponse::ReadJournal { entries, more_follows }
}
SERVICE_FILE_OPEN => {
let mut c = t.children();
let frsm_id = c.next_tag(Tag::context(0))?.integer_i32()?;
let attributes = FileAttributes::parse(&c.next_tag(Tag::context_constructed(1))?)?;
ConfirmedResponse::FileOpen { frsm_id, attributes }
}
SERVICE_FILE_READ => {
let mut c = t.children();
let data = c.next_tag(Tag::context(0))?.value;
let more_follows = c.next_if_tag(Tag::context(1))?.map(|t| t.boolean()).transpose()?.unwrap_or(true);
ConfirmedResponse::FileRead { data, more_follows }
}
SERVICE_FILE_CLOSE => ConfirmedResponse::FileClose,
SERVICE_OBTAIN_FILE => ConfirmedResponse::ObtainFile,
SERVICE_FILE_DELETE => ConfirmedResponse::FileDelete,
SERVICE_FILE_DIRECTORY => {
let mut c = t.children();
let list = c.next_tag(Tag::context_constructed(0))?;
let mut entries = Vec::new();
for entry in file::directory_entries(&list) {
if entries.len() >= limits.max_list_items {
return Err(Error::LimitExceeded { limit: "max_list_items", value: entries.len() + 1 });
}
entries.push(DirectoryEntry::parse(&entry?, limits)?);
}
let more_follows = c.next_if_tag(Tag::context(1))?.map(|t| t.boolean()).transpose()?.unwrap_or(false);
ConfirmedResponse::FileDirectory { entries, more_follows }
}
_ => ConfirmedResponse::Other(t),
})
}
#[allow(clippy::too_many_lines)]
fn write(&self, e: &mut Encoder) -> Result<()> {
match self {
ConfirmedResponse::GetNameList { identifiers, more_follows } => {
e.constructed(Tag::context_constructed(1), |e| {
e.constructed(Tag::context_constructed(0), |e| {
for id in identifiers {
e.visible_string(TAG_IDENTIFIER, id)?;
}
Ok(())
})?;
if !*more_follows {
e.boolean(Tag::context(1), false)?;
}
Ok(())
})?;
}
ConfirmedResponse::Status { logical, physical, local_detail } => {
e.constructed(Tag::context_constructed(SERVICE_STATUS), |e| {
e.integer(Tag::context(0), *logical)?;
e.integer(Tag::context(1), *physical)?;
if let Some((unused, bits)) = local_detail {
e.bit_string(Tag::context(2), *unused, bits)?;
}
Ok(())
})?;
}
ConfirmedResponse::GetCapabilityList { capabilities, more_follows } => {
e.constructed(Tag::context_constructed(SERVICE_GET_CAPABILITY_LIST), |e| {
e.constructed(Tag::context_constructed(0), |e| {
for c in capabilities {
e.visible_string(TAG_VISIBLE_STRING, c)?;
}
Ok(())
})?;
if !*more_follows {
e.boolean(Tag::context(1), false)?;
}
Ok(())
})?;
}
ConfirmedResponse::Identify { vendor, model, revision } => {
e.constructed(Tag::context_constructed(2), |e| {
e.visible_string(Tag::context(0), vendor)?;
e.visible_string(Tag::context(1), model)?;
e.visible_string(Tag::context(2), revision)?;
Ok(())
})?;
}
ConfirmedResponse::Read { access, results } => {
e.constructed(Tag::context_constructed(4), |e| {
if let Some(a) = access {
e.constructed(Tag::context_constructed(0), |e| a.write(e))?;
}
write_access_results(results, Tag::context_constructed(1), e)
})?;
}
ConfirmedResponse::Write(results) => {
e.constructed(Tag::context_constructed(5), |e| {
for r in results {
match r {
WriteResult::Failure(code) => {
e.integer(Tag::context(0), *code)?;
}
WriteResult::Success => {
e.primitive(Tag::context(1), &[])?;
}
}
}
Ok(())
})?;
}
ConfirmedResponse::GetNamedVariableListAttributes { deletable, variables } => {
e.constructed(Tag::context_constructed(12), |e| {
e.boolean(Tag::context(0), *deletable)?;
write_variable_list(variables, Tag::context_constructed(1), e)
})?;
}
ConfirmedResponse::GetVariableAccessAttributes { deletable, type_spec } => {
e.constructed(Tag::context_constructed(SERVICE_GET_VARIABLE_ACCESS_ATTRIBUTES), |e| {
e.boolean(Tag::context(0), *deletable)?;
e.constructed(Tag::context_constructed(2), |e| type_spec.write(e))?;
Ok(())
})?;
}
ConfirmedResponse::DefineNamedVariableList => {
e.primitive(Tag::context(SERVICE_DEFINE_NVL), &[])?;
}
ConfirmedResponse::DeleteNamedVariableList { matched, deleted } => {
e.constructed(Tag::context_constructed(SERVICE_DELETE_NVL), |e| {
e.unsigned(Tag::context(0), u64::from(*matched))?;
e.unsigned(Tag::context(1), u64::from(*deleted))?;
Ok(())
})?;
}
ConfirmedResponse::ReadJournal { entries, more_follows } => {
e.constructed(Tag::context_constructed(SERVICE_READ_JOURNAL), |e| {
e.constructed(Tag::context_constructed(0), |e| {
for entry in entries {
entry.write(e)?;
}
Ok(())
})?;
if *more_follows {
e.boolean(Tag::context(1), true)?;
}
Ok(())
})?;
}
ConfirmedResponse::FileOpen { frsm_id, attributes } => {
e.constructed(Tag::context_constructed(SERVICE_FILE_OPEN), |e| {
e.integer(Tag::context(0), i64::from(*frsm_id))?;
attributes.write(Tag::context_constructed(1), e)
})?;
}
ConfirmedResponse::FileRead { data, more_follows } => {
e.constructed(Tag::context_constructed(SERVICE_FILE_READ), |e| {
e.primitive(Tag::context(0), data)?;
if !*more_follows {
e.boolean(Tag::context(1), false)?;
}
Ok(())
})?;
}
ConfirmedResponse::FileClose => {
e.primitive(Tag::context(SERVICE_FILE_CLOSE), &[])?;
}
ConfirmedResponse::ObtainFile => {
e.primitive(Tag::context(SERVICE_OBTAIN_FILE), &[])?;
}
ConfirmedResponse::FileDelete => {
e.primitive(Tag::context(SERVICE_FILE_DELETE), &[])?;
}
ConfirmedResponse::FileDirectory { entries, more_follows } => {
e.constructed(Tag::context_constructed(SERVICE_FILE_DIRECTORY), |e| {
e.constructed(Tag::context_constructed(0), |e| {
e.constructed(TAG_SEQUENCE, |e| {
for entry in entries {
entry.write(e)?;
}
Ok(())
})?;
Ok(())
})?;
if *more_follows {
e.boolean(Tag::context(1), true)?;
}
Ok(())
})?;
}
ConfirmedResponse::Other(t) => {
e.primitive(t.tag, t.value)?;
}
}
Ok(())
}
}
fn invoke_id_of(t: &Tlv<'_>) -> Result<i64> {
let v = t.integer_i64()?;
if (0..=i64::from(u32::MAX)).contains(&v) { Ok(v) } else { Err(Error::decode(DecodeReason::BadValue, t.value_offset)) }
}
impl<'a> Mms<'a> {
pub fn peek_invoke_id(buf: &[u8]) -> Option<i64> {
let top = Cursor::new(buf).next_required().ok()?;
if top.tag.class != Class::Context || !matches!(top.tag.number, 0 | 1 | 2 | 5) {
return None;
}
let first = top.children().next()?.ok()?;
if first.tag != TAG_INTEGER && first.tag != Tag::context(0) {
return None;
}
first.integer_i64().ok()
}
pub fn parse(buf: &'a [u8], limits: &Limits) -> Result<Mms<'a>> {
let top = Cursor::new(buf).next_required()?;
if top.tag.class != Class::Context {
return Err(Error::decode(DecodeReason::UnexpectedTag, top.offset));
}
Ok(match top.tag.number {
0 => {
let mut c = top.children();
let invoke_id = invoke_id_of(&c.next_tag(TAG_INTEGER)?)?;
let mut next = c.next_required()?;
if next.tag == TAG_SEQUENCE {
next = c.next_required()?;
}
Mms::ConfirmedRequest { invoke_id, service: ConfirmedRequest::parse(next, limits)? }
}
1 => {
let mut c = top.children();
let invoke_id = invoke_id_of(&c.next_tag(TAG_INTEGER)?)?;
Mms::ConfirmedResponse { invoke_id, service: ConfirmedResponse::parse(c.next_required()?, limits)? }
}
2 => {
let mut c = top.children();
let invoke_id = invoke_id_of(&c.next_tag(Tag::context(0))?)?;
let modifier_position = c.next_if_tag(Tag::context(1))?.map(|t| t.unsigned_lenient_u32()).transpose()?;
let error = c.next_required()?;
Mms::ConfirmedError { invoke_id, modifier_position, error }
}
3 => {
let service = top.children().next_required()?;
Mms::Unconfirmed(if service.tag == Tag::context_constructed(0) {
let mut c = service.children();
let access = VariableAccess::parse(&c.next_required()?)?;
let results = parse_access_results(&c.next_tag(Tag::context_constructed(0))?, limits)?;
Unconfirmed::InformationReport { access, results }
} else {
Unconfirmed::Other(service)
})
}
4 => Mms::Reject(Reject::parse(&top)?),
5 => Mms::CancelRequest(invoke_id_of(&top)?),
6 => Mms::CancelResponse(invoke_id_of(&top)?),
7 => {
let mut c = top.children();
let invoke_id = invoke_id_of(&c.next_tag(Tag::context(0))?)?;
Mms::CancelError { invoke_id, error: c.next_required()? }
}
8 => Mms::InitiateRequest(Initiate::parse(&top)?),
9 => Mms::InitiateResponse(Initiate::parse(&top)?),
10 => Mms::InitiateError(top),
11 => Mms::ConcludeRequest,
12 => Mms::ConcludeResponse,
13 => Mms::ConcludeError(top),
_ => Mms::Other(top),
})
}
pub fn write(&self, out: &mut Encoder) -> Result<()> {
match self {
Mms::ConfirmedRequest { invoke_id, service } => {
out.constructed(Tag::context_constructed(0), |e| {
e.integer(TAG_INTEGER, *invoke_id)?;
service.write(e)
})?;
}
Mms::ConfirmedResponse { invoke_id, service } => {
out.constructed(Tag::context_constructed(1), |e| {
e.integer(TAG_INTEGER, *invoke_id)?;
service.write(e)
})?;
}
Mms::ConfirmedError { invoke_id, modifier_position, error } => {
out.constructed(Tag::context_constructed(2), |e| {
e.integer(Tag::context(0), *invoke_id)?;
if let Some(p) = modifier_position {
e.unsigned(Tag::context(1), u64::from(*p))?;
}
e.primitive(error.tag, error.value)?;
Ok(())
})?;
}
Mms::Unconfirmed(service) => {
out.constructed(Tag::context_constructed(3), |e| match service {
Unconfirmed::InformationReport { access, results } => e
.constructed(Tag::context_constructed(0), |e| {
access.write(e)?;
write_access_results(results, Tag::context_constructed(0), e)
})
.map(|_| ()),
Unconfirmed::Other(t) => e.primitive(t.tag, t.value).map(|_| ()),
})?;
}
Mms::CancelRequest(invoke_id) => {
out.unsigned(Tag::context(5), u64::try_from(*invoke_id).unwrap_or(0))?;
}
Mms::CancelResponse(invoke_id) => {
out.unsigned(Tag::context(6), u64::try_from(*invoke_id).unwrap_or(0))?;
}
Mms::CancelError { invoke_id, error } => {
out.constructed(Tag::context_constructed(7), |e| {
e.unsigned(Tag::context(0), u64::try_from(*invoke_id).unwrap_or(0))?;
e.primitive(error.tag, error.value)?;
Ok(())
})?;
}
Mms::InitiateRequest(i) => i.write(Tag::context_constructed(8), out)?,
Mms::InitiateResponse(i) => i.write(Tag::context_constructed(9), out)?,
Mms::ConcludeRequest => {
out.primitive(Tag::context(11), &[])?;
}
Mms::ConcludeResponse => {
out.primitive(Tag::context(12), &[])?;
}
Mms::Reject(r) => r.write(out)?,
Mms::InitiateError(t) | Mms::ConcludeError(t) | Mms::Other(t) => {
out.primitive(t.tag, t.value)?;
}
}
Ok(())
}
pub fn to_vec(&self) -> Result<Vec<u8>> {
let mut e = Encoder::new();
self.write(&mut e)?;
Ok(e.into_vec())
}
pub fn invoke_id(&self) -> Option<i64> {
match self {
Mms::ConfirmedRequest { invoke_id, .. } | Mms::ConfirmedResponse { invoke_id, .. } | Mms::ConfirmedError { invoke_id, .. } => Some(*invoke_id),
Mms::CancelRequest(id) | Mms::CancelResponse(id) | Mms::CancelError { invoke_id: id, .. } => Some(*id),
Mms::Reject(r) => r.original_invoke_id,
_ => None,
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn a_name_list_may_be_larger_than_a_data_set() {
use crate::ber::{Encoder, Tag};
use alloc::string::String;
use alloc::vec::Vec;
let names: Vec<String> = (0..2_000).map(|i| alloc::format!("GGIO1$ST$Ind{i}$stVal")).collect();
let borrowed: Vec<&str> = names.iter().map(String::as_str).collect();
let pdu = Mms::ConfirmedResponse { invoke_id: 1, service: ConfirmedResponse::GetNameList { identifiers: borrowed, more_follows: false } }
.to_vec()
.expect("encode");
match Mms::parse(&pdu, &Limits::DEFAULT).expect("a real device's namespace decodes") {
Mms::ConfirmedResponse { service: ConfirmedResponse::GetNameList { identifiers, .. }, .. } => assert_eq!(identifiers.len(), 2_000),
other => panic!("not a name list: {other:?}"),
}
let tight = Limits { max_list_items: 100, ..Limits::DEFAULT };
assert!(matches!(Mms::parse(&pdu, &tight), Err(Error::LimitExceeded { limit: "max_list_items", .. })));
let mut e = Encoder::new();
e.constructed(Tag::universal(universal::SEQUENCE, true), |e| {
for _ in 0..600 {
e.constructed(Tag::universal(universal::SEQUENCE, true), |e| {
e.constructed(Tag::context_constructed(0), |e| {
e.constructed(Tag::context_constructed(1), |e| {
e.visible_string(TAG_IDENTIFIER, "IED1LD0")?;
e.visible_string(TAG_IDENTIFIER, "GGIO1$ST$Ind1$stVal")?;
Ok(())
})?;
Ok(())
})?;
Ok(())
})?;
}
Ok(())
})
.unwrap();
let list = e.into_vec();
let tlv = Cursor::new(&list).next_required().unwrap();
assert!(matches!(parse_variable_list(&tlv, &Limits::DEFAULT), Err(Error::LimitExceeded { limit: "max_dataset_members", .. })));
}
#[test]
fn an_invoke_identifier_outside_unsigned32_is_not_a_pdu() {
let wire = [0xA0u8, 0x05, 0x02, 0x01, 0xFF, 0x9B, 0x00];
assert!(Mms::parse(&wire, &Limits::DEFAULT).is_err(), "invokeID −1");
let wire = [0xA0u8, 0x09, 0x02, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x9B, 0x00];
assert!(Mms::parse(&wire, &Limits::DEFAULT).is_err(), "invokeID above u32::MAX");
for id in [0u32, 1, 0x7FFF_FFFF, u32::MAX] {
let pdu = Mms::ConfirmedRequest { invoke_id: i64::from(id), service: ConfirmedRequest::Identify };
let bytes = pdu.to_vec().unwrap();
let back = Mms::parse(&bytes, &Limits::DEFAULT).unwrap();
assert_eq!(back.invoke_id(), Some(i64::from(id)), "{id}");
}
}
use super::*;
use crate::proto::data::Typed;
use file::{DirectoryEntry, FileAttributes};
fn round_trip(wire: &[u8]) -> Mms<'_> {
let pdu = Mms::parse(wire, &Limits::DEFAULT).expect("decode");
assert_eq!(pdu.to_vec().expect("encode"), wire, "re-encoding must reproduce the octets");
pdu
}
#[test]
fn a_service_error_tagged_like_a_modifier_position_still_re_encodes() {
let wire: &[u8] = &[0xA2, 0x0D, 0x80, 0x01, 0x07, 0x81, 0x01, 0x02, 0xA2, 0x05, 0xA0, 0x03, 0x87, 0x01, 0x0A];
let pdu = Mms::parse(wire, &Limits::DEFAULT).expect("decode");
let Mms::ConfirmedError { invoke_id, modifier_position, error } = pdu else {
panic!("not a confirmed error");
};
assert_eq!((invoke_id, modifier_position), (7, Some(2)));
assert_eq!(error.tag, Tag::context_constructed(2), "the service error is [2], not `whatever is next`");
let re = pdu.to_vec().expect("encode");
assert_eq!(re, wire, "and it re-encodes byte for byte");
assert_eq!(Mms::parse(&re, &Limits::DEFAULT).expect("re-decode").to_vec().expect("re-encode"), re);
let bad: &[u8] = &[130, 18, 128, 4, 2, 3, 42, 2, 129, 8, 0, 128, 4, 0, 0, 239, 255, 255, 129, 0, 0];
assert!(Mms::parse(bad, &Limits::DEFAULT).is_err(), "a 64-bit modifier position is not one");
let e = ServiceError::parse(&error).expect("service error");
assert_eq!((e.class, e.code, e.additional), (7, 10, None), "access error, object-non-existent");
}
#[test]
fn the_reference_initiate_request_round_trips() {
let wire: &[u8] = &[
0xA8, 0x25, 0x80, 0x02, 0x7D, 0x00, 0x81, 0x01, 0x14, 0x82, 0x01, 0x14, 0x83, 0x01, 0x04, 0xA4, 0x16, 0x80, 0x01, 0x01, 0x81, 0x03, 0x05, 0xFB, 0x00, 0x82, 0x0C, 0x03, 0x6E, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x01, 0x98, ];
let Mms::InitiateRequest(i) = round_trip(wire) else { panic!("not an initiate request") };
assert_eq!(i.local_detail, Some(32_000));
assert_eq!((i.max_serv_outstanding_calling, i.max_serv_outstanding_called), (20, 20));
assert_eq!(i.data_structure_nesting_level, Some(4));
assert_eq!(i.version, 1);
assert_eq!(i.parameter_cbb, (5, &[0xFB, 0x00][..]));
}
#[test]
fn the_reference_identify_request_round_trips() {
let wire: &[u8] = &[0xA0, 0x06, 0x02, 0x02, 0x11, 0x4F, 0x82, 0x00];
let pdu = round_trip(wire);
assert_eq!(pdu.invoke_id(), Some(4431));
assert!(matches!(pdu, Mms::ConfirmedRequest { service: ConfirmedRequest::Identify, .. }));
}
#[test]
fn a_file_directory_response_wraps_its_entries_in_a_sequence() {
let response = ConfirmedResponse::FileDirectory {
entries: alloc::vec![DirectoryEntry {
name: FileName::from_encoded(&[0x19, 0x01, b'a']),
attributes: FileAttributes { size: 7, last_modified: None },
}],
more_follows: false,
};
let mut e = Encoder::new();
Mms::ConfirmedResponse { invoke_id: 1, service: response }.write(&mut e).expect("encode");
let bytes = e.into_vec();
let mut c = Cursor::new(&bytes).next_required().expect("pdu").children();
c.next_required().expect("invokeID");
let service = c.next_tag(Tag::context_constructed(SERVICE_FILE_DIRECTORY)).expect("fileDirectory");
let list = service.children().next_tag(Tag::context_constructed(0)).expect("listOfDirectoryEntry");
let inner = list.children().next_required().expect("the SEQUENCE OF");
assert_eq!(inner.tag, TAG_SEQUENCE, "`listOfDirectoryEntry [0]` is not implicitly tagged");
let entry = inner.children().next_required().expect("one entry");
assert_eq!(entry.tag, TAG_SEQUENCE);
assert_eq!(entry.children().next_required().expect("filename").tag, Tag::context_constructed(0));
let back = Mms::parse(&bytes, &Limits::DEFAULT).expect("decode");
let Mms::ConfirmedResponse { service: ConfirmedResponse::FileDirectory { entries, .. }, .. } = &back else { panic!("not a file directory") };
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].name.display(), "a");
assert_eq!(entries[0].attributes.size, 7);
assert_eq!(back.to_vec().expect("re-encode"), bytes);
let mut implicit = Encoder::new();
implicit
.constructed(Tag::context_constructed(2), |e| {
e.integer(TAG_INTEGER, 1)?;
e.constructed(Tag::context_constructed(SERVICE_FILE_DIRECTORY), |e| {
e.constructed(Tag::context_constructed(0), |e| {
e.constructed(TAG_SEQUENCE, |e| {
e.constructed(Tag::context_constructed(0), |e| {
e.primitive(file::TAG_GRAPHIC_STRING, b"a")?;
Ok(())
})?;
e.constructed(Tag::context_constructed(1), |e| {
e.unsigned(Tag::context(0), 7)?;
Ok(())
})?;
Ok(())
})?;
Ok(())
})?;
Ok(())
})?;
Ok(())
})
.expect("encode");
let mut implicit = implicit.into_vec();
implicit[0] = 0xA1; let back = Mms::parse(&implicit, &Limits::DEFAULT).expect("decode the implicit spelling");
let Mms::ConfirmedResponse { service: ConfirmedResponse::FileDirectory { entries, .. }, .. } = back else { panic!("not a file directory") };
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].name.display(), "a");
}
#[test]
fn the_reference_read_request_names_a_domain_variable() {
let wire: &[u8] = &[
0xA0, 0x30, 0x02, 0x02, 0x11, 0x50, 0xA4, 0x2A, 0xA1, 0x28, 0xA0, 0x26, 0x30, 0x24, 0xA0, 0x22, 0xA1, 0x20, 0x1A, 0x08, b'K', b'I', b'R', b'K', b'L', b'A', b'N', b'D', 0x1A, 0x14, b'B', b'i', b'l', b'a', b't', b'e', b'r', b'a', b'l', b'_', b'T', b'a', b'b', b'l', b'e', b'_', b'I', b'D', b'0', b'1',
];
let pdu = round_trip(wire);
let Mms::ConfirmedRequest { invoke_id, service: ConfirmedRequest::Read { access, specification_with_result } } = pdu else { panic!("not a read") };
assert_eq!(invoke_id, 4432);
assert!(!specification_with_result);
let VariableAccess::ListOfVariable(vars) = access else { panic!("not a list") };
assert_eq!(vars.len(), 1);
assert_eq!(vars[0], VariableSpecification::Name(ObjectName::DomainSpecific { domain: "KIRKLAND", item: "Bilateral_Table_ID01" }));
}
#[test]
fn an_information_report_carries_a_data_set_and_its_values() {
let wire: &[u8] = &[
0xA3, 0x2B, 0xA0, 0x29, 0xA1, 0x18, 0xA1, 0x16, 0x1A, 0x08, b'K', b'I', b'R', b'K', b'L', b'A', b'N', b'D', 0x1A, 0x0A, b'E', b'M', b'S', b'_', b'A', b'N', b'A', b'L', b'O', b'G', 0xA0, 0x0D, 0x86, 0x01, 0x01, 0x87, 0x05, 0x08, 0x3F, 0x80, 0x00, 0x00, 0x80, 0x01, 0x0A, ];
let Mms::Unconfirmed(Unconfirmed::InformationReport { access, results }) = round_trip(wire) else { panic!("not a report") };
assert_eq!(access, VariableAccess::VariableListName(ObjectName::DomainSpecific { domain: "KIRKLAND", item: "EMS_ANALOG" }));
assert_eq!(results.len(), 3);
assert_eq!(results[0].value().and_then(|d| d.as_u64()), Some(1));
assert_eq!(results[1].value().and_then(|d| d.as_f64()), Some(1.0));
assert_eq!(results[2], AccessResult::Failure(10));
}
#[test]
fn a_read_response_and_a_write_round_trip() {
let read: &[u8] = &[
0xA1, 0x0D, 0x02, 0x01, 0x07, 0xA4, 0x08, 0xA1, 0x06, 0x83, 0x01, 0xFF, 0x80, 0x01, 0x03, ];
let Mms::ConfirmedResponse { service: ConfirmedResponse::Read { results, access }, .. } = round_trip(read) else { panic!() };
assert!(access.is_none());
assert_eq!(results[0].value().and_then(|d| d.as_bool()), Some(true));
assert_eq!(results[1], AccessResult::Failure(3));
let write: &[u8] = &[
0xA1, 0x0A, 0x02, 0x01, 0x08, 0xA5, 0x05, 0x81, 0x00, 0x80, 0x01, 0x02, ];
let Mms::ConfirmedResponse { service: ConfirmedResponse::Write(results), .. } = round_trip(write) else { panic!() };
assert_eq!(results, [WriteResult::Success, WriteResult::Failure(2)]);
}
#[test]
fn get_name_list_round_trips_in_both_directions() {
let request: &[u8] = &[
0xA0, 0x14, 0x02, 0x01, 0x01, 0xA1, 0x0F, 0xA0, 0x03, 0x80, 0x01, 0x09, 0xA1, 0x08, 0x81, 0x06, b'L', b'D', b'0', b'/', b'L', b'N', ];
let Mms::ConfirmedRequest { service: ConfirmedRequest::GetNameList { object_class, scope, continue_after }, .. } = round_trip(request) else {
panic!()
};
assert_eq!(object_class, 9);
assert_eq!(scope, ObjectScope::DomainSpecific("LD0/LN"));
assert!(continue_after.is_none());
let response: &[u8] = &[
0xA1, 0x0E, 0x02, 0x01, 0x01, 0xA1, 0x09, 0xA0, 0x07, 0x1A, 0x02, b'L', b'D', 0x1A, 0x01, b'X', ];
let Mms::ConfirmedResponse { service: ConfirmedResponse::GetNameList { identifiers, more_follows }, .. } = round_trip(response) else { panic!() };
assert_eq!(identifiers, ["LD", "X"]);
assert!(more_follows, "the field is DEFAULT TRUE, so its absence means more");
}
#[test]
fn an_unmodelled_service_keeps_its_octets() {
let wire: &[u8] = &[0xA0, 0x09, 0x02, 0x01, 0x05, 0xA7, 0x04, 0xA0, 0x02, 0x80, 0x00];
let pdu = round_trip(wire);
assert!(matches!(pdu, Mms::ConfirmedRequest { service: ConfirmedRequest::Other(_), .. }));
}
#[test]
fn conclude_and_errors_round_trip() {
assert_eq!(round_trip(&[0x8B, 0x00]), Mms::ConcludeRequest);
assert_eq!(round_trip(&[0x8C, 0x00]), Mms::ConcludeResponse);
let err: &[u8] = &[0xA2, 0x08, 0x80, 0x01, 0x07, 0xA2, 0x03, 0x80, 0x01, 0x0B];
let Mms::ConfirmedError { invoke_id, .. } = round_trip(err) else { panic!() };
assert_eq!(invoke_id, 7);
}
#[test]
fn the_file_services_round_trip_through_the_high_tag_number_form() {
let name = file::FileNameBuf::from_path("COMTRADE/rec1.cfg").unwrap();
let open = Mms::ConfirmedRequest { invoke_id: 1, service: ConfirmedRequest::FileOpen { name: name.as_name(), position: 0 } };
let bytes = open.to_vec().unwrap();
assert!(bytes.windows(2).any(|w| w == [0xBF, 0x48]), "fileOpen is [72] in the high-tag-number form: {bytes:02X?}");
assert_eq!(round_trip(&bytes), open);
let read = Mms::ConfirmedRequest { invoke_id: 2, service: ConfirmedRequest::FileRead(9) };
let bytes = read.to_vec().unwrap();
assert!(bytes.ends_with(&[0x9F, 0x49, 0x01, 0x09]), "fileRead is a primitive Integer32: {bytes:02X?}");
assert_eq!(round_trip(&bytes), read);
for service in [
ConfirmedRequest::FileClose(9),
ConfirmedRequest::FileDelete(name.as_name()),
ConfirmedRequest::FileDirectory { specification: Some(name.as_name()), continue_after: None },
ConfirmedRequest::FileDirectory { specification: None, continue_after: None },
] {
let pdu = Mms::ConfirmedRequest { invoke_id: 3, service };
assert_eq!(round_trip(&pdu.to_vec().unwrap()), pdu);
}
let answer = Mms::ConfirmedResponse {
invoke_id: 1,
service: ConfirmedResponse::FileOpen { frsm_id: 9, attributes: FileAttributes { size: 4096, last_modified: Some("20240131T101500Z") } },
};
assert_eq!(round_trip(&answer.to_vec().unwrap()), answer);
let last = Mms::ConfirmedResponse { invoke_id: 1, service: ConfirmedResponse::FileRead { data: &[1, 2, 3], more_follows: false } };
let last_bytes = last.to_vec().unwrap();
assert_eq!(round_trip(&last_bytes), last);
let more = Mms::ConfirmedResponse { invoke_id: 1, service: ConfirmedResponse::FileRead { data: &[1, 2, 3], more_follows: true } };
let more_bytes = more.to_vec().unwrap();
assert!(more_bytes.len() < last_bytes.len(), "the default is not written");
assert_eq!(round_trip(&more_bytes), more);
let dir = Mms::ConfirmedResponse {
invoke_id: 1,
service: ConfirmedResponse::FileDirectory {
entries: alloc::vec![DirectoryEntry { name: name.as_name(), attributes: FileAttributes { size: 12, last_modified: None } }],
more_follows: true,
},
};
let dir_bytes = dir.to_vec().unwrap();
let back = round_trip(&dir_bytes);
let Mms::ConfirmedResponse { service: ConfirmedResponse::FileDirectory { entries, more_follows }, .. } = back else { panic!() };
assert!(more_follows);
assert_eq!(entries[0].name.display(), "COMTRADE/rec1.cfg");
assert_eq!(entries[0].attributes.size, 12);
}
#[test]
fn a_data_set_is_created_and_deleted_by_name() {
let members = alloc::vec![
VariableSpecification::Name(ObjectName::DomainSpecific { domain: "IED1LD0", item: "PTRC1$ST$Tr$general" }),
VariableSpecification::Name(ObjectName::DomainSpecific { domain: "IED1LD0", item: "PTRC1$ST$Tr$q" }),
];
let create = Mms::ConfirmedRequest {
invoke_id: 1,
service: ConfirmedRequest::DefineNamedVariableList {
name: ObjectName::DomainSpecific { domain: "IED1LD0", item: "LLN0$dsTemp" },
variables: members,
},
};
assert_eq!(round_trip(&create.to_vec().unwrap()), create);
assert_eq!(
round_trip(&Mms::ConfirmedResponse { invoke_id: 1, service: ConfirmedResponse::DefineNamedVariableList }.to_vec().unwrap()),
Mms::ConfirmedResponse { invoke_id: 1, service: ConfirmedResponse::DefineNamedVariableList }
);
let delete = Mms::ConfirmedRequest {
invoke_id: 2,
service: ConfirmedRequest::DeleteNamedVariableList {
scope: delete_scope::SPECIFIC,
names: alloc::vec![ObjectName::DomainSpecific { domain: "IED1LD0", item: "LLN0$dsTemp" }],
domain: None,
},
};
assert_eq!(round_trip(&delete.to_vec().unwrap()), delete);
let by_domain = Mms::ConfirmedRequest {
invoke_id: 3,
service: ConfirmedRequest::DeleteNamedVariableList { scope: delete_scope::DOMAIN, names: Vec::new(), domain: Some("IED1LD0") },
};
assert_eq!(round_trip(&by_domain.to_vec().unwrap()), by_domain);
let answer = Mms::ConfirmedResponse { invoke_id: 2, service: ConfirmedResponse::DeleteNamedVariableList { matched: 1, deleted: 0 } };
assert_eq!(round_trip(&answer.to_vec().unwrap()), answer);
}
#[test]
fn a_type_is_asked_for_by_name_and_comes_back_as_a_shape() {
let ask = Mms::ConfirmedRequest {
invoke_id: 1,
service: ConfirmedRequest::GetVariableAccessAttributes(ObjectName::DomainSpecific { domain: "IED1LD0", item: "MMXU1$MX$TotW$mag$f" }),
};
let bytes = ask.to_vec().unwrap();
assert!(bytes.windows(4).any(|w| w[0] == 0xA6 && w[2] == 0xA0), "[6] is explicit and wraps the `name [0]` choice: {bytes:02X?}");
assert_eq!(round_trip(&bytes), ask);
let answer = Mms::ConfirmedResponse {
invoke_id: 1,
service: ConfirmedResponse::GetVariableAccessAttributes {
deletable: false,
type_spec: TypeSpec::FloatingPoint { format_width: 32, exponent_width: 8 },
},
};
assert_eq!(round_trip(&answer.to_vec().unwrap()), answer);
}
#[test]
fn a_log_is_read_by_time_and_resumed_after_an_entry() {
use journal::{AfterEntry, JournalEntry, JournalVariable, RangeStop, TimeOfDay};
let log = ObjectName::DomainSpecific { domain: "IED1LD0", item: "LLN0$GeneralLog" };
let from = TimeOfDay::from_unix_millis(1_700_000_000_000);
let by_time = Mms::ConfirmedRequest { invoke_id: 1, service: ConfirmedRequest::ReadJournal(ReadJournal::by_time(log, from, None)) };
let bytes = by_time.to_vec().unwrap();
assert!(bytes.windows(2).any(|w| w == [0xBF, 0x41]), "readJournal is [65]: {bytes:02X?}");
assert_eq!(round_trip(&bytes), by_time);
let mut bounded = ReadJournal::by_time(log, from, Some(TimeOfDay::from_unix_millis(1_700_000_060_000)));
bounded.stop = Some(RangeStop::Count(100));
bounded.variables = alloc::vec!["IED1LD0/LLN0$ST$Mod$stVal"];
let pdu = Mms::ConfirmedRequest { invoke_id: 2, service: ConfirmedRequest::ReadJournal(bounded) };
assert_eq!(round_trip(&pdu.to_vec().unwrap()), pdu);
let after = Mms::ConfirmedRequest {
invoke_id: 3,
service: ConfirmedRequest::ReadJournal(ReadJournal::after_entry(log, AfterEntry { time: from, entry_id: &[1, 2, 3, 4, 5, 6, 7, 8] })),
};
assert_eq!(round_trip(&after.to_vec().unwrap()), after);
let value_bytes = crate::proto::data::Value::encode_all(&[crate::proto::data::Value::Boolean(true)]).unwrap();
let value = Cursor::new(&value_bytes).next_required().unwrap();
let answer = Mms::ConfirmedResponse {
invoke_id: 1,
service: ConfirmedResponse::ReadJournal {
entries: alloc::vec![
JournalEntry::new(&[0, 0, 0, 0, 0, 0, 0, 1], from, alloc::vec![JournalVariable { tag: "IED1LD0/LLN0$ST$Mod$stVal", value }]),
JournalEntry::annotated(&[0, 0, 0, 0, 0, 0, 0, 2], from, "power up"),
],
more_follows: false,
},
};
let answer_bytes = answer.to_vec().unwrap();
let back = round_trip(&answer_bytes);
let Mms::ConfirmedResponse { service: ConfirmedResponse::ReadJournal { entries, .. }, .. } = back else { panic!() };
assert_eq!(entries[0].variables[0].tag, "IED1LD0/LLN0$ST$Mod$stVal");
assert_eq!(entries[0].variables[0].value().and_then(|v| Typed::as_bool(&v)), Some(true));
assert_eq!(entries[1].annotation, Some("power up"));
assert_eq!(entries[1].occurred, from);
}
#[test]
fn truncation_is_an_error_not_a_panic() {
let wire: &[u8] = &[
0xA3, 0x2B, 0xA0, 0x29, 0xA1, 0x18, 0xA1, 0x16, 0x1A, 0x08, b'K', b'I', b'R', b'K', b'L', b'A', b'N', b'D', 0x1A, 0x0A, b'E', b'M', b'S', b'_',
b'A', b'N', b'A', b'L', b'O', b'G', 0xA0, 0x0D, 0x86, 0x01, 0x01, 0x87, 0x05, 0x08, 0x3F, 0x80, 0x00, 0x00, 0x80, 0x01, 0x0A,
];
for cut in 0..wire.len() {
let _ = Mms::parse(&wire[..cut], &Limits::DEFAULT);
}
assert!(Mms::parse(&[], &Limits::DEFAULT).is_err());
assert!(Mms::parse(&[0x30, 0x00], &Limits::DEFAULT).is_err(), "a SEQUENCE is not an MMS PDU");
}
#[test]
fn obtain_file_round_trips_and_its_error_names_the_side() {
let source = file::FileNameBuf::from_path("settings.xml").unwrap();
let destination = file::FileNameBuf::from_path("SETTINGS/settings.xml").unwrap();
let request = Mms::ConfirmedRequest {
invoke_id: 7,
service: ConfirmedRequest::ObtainFile { source_server: None, source: source.as_name(), destination: destination.as_name() },
};
let bytes = request.to_vec().unwrap();
assert!(bytes.windows(2).any(|w| w == [0xbf, 0x2e]), "[46] constructed: {bytes:02x?}");
assert_eq!(Mms::parse(&bytes, &Limits::DEFAULT).unwrap(), request);
let third = Mms::ConfirmedRequest {
invoke_id: 8,
service: ConfirmedRequest::ObtainFile {
source_server: Some(&[0xa2, 0x02, 0x06, 0x00]),
source: source.as_name(),
destination: destination.as_name(),
},
};
assert_eq!(Mms::parse(&third.to_vec().unwrap(), &Limits::DEFAULT).unwrap(), third);
let response = Mms::ConfirmedResponse { invoke_id: 7, service: ConfirmedResponse::ObtainFile };
assert_eq!(Mms::parse(&response.to_vec().unwrap(), &Limits::DEFAULT).unwrap(), response);
let error = ServiceError::encode_obtain_file(
Tag::context_constructed(2),
service_error::FILE,
file_error::DUPLICATE_FILENAME,
obtain_file_error::DESTINATION_FILE,
)
.unwrap();
let t = Cursor::new(&error).next_required().unwrap();
let parsed = ServiceError::parse(&t).unwrap();
assert_eq!((parsed.class, parsed.code, parsed.specific), (11, 8, Some((0, 1))));
assert!(error.ends_with(&[0xa3, 0x03, 0x80, 0x01, 0x01]), "serviceSpecificInformation [3] obtainFile [0], as libiec61850 writes it");
}
}