Skip to main content

gwa_core/
device_info.rs

1//! Decode the WAN API v2.0.0 device-information example for a commissioned logical device.
2
3use std::fmt;
4use xml::{
5    attribute::OwnedAttribute,
6    name::OwnedName,
7    reader::{ParserConfig, XmlEvent},
8};
9
10/// Media type of decoded COSEM XML in the WAN API.
11pub const XML_MEDIA_TYPE: &str = "application/vnd.de-dke-k461-ic1+xml";
12/// Maximum size of the decoded XML document in this lab profile.
13pub const MAX_XML_BYTES: usize = 4 * 1024 * 1024;
14/// Maximum element nesting, counting the document element as depth one.
15pub const MAX_XML_DEPTH: usize = 32;
16
17const INFO_NS: &str = "urn:k461-dke-de:smgw_info-1";
18const EXT_NS: &str = "urn:k461-dke-de:extension-1";
19const MAX_VALUE_BYTES: usize = 256;
20
21/// Values read directly from the device-info object, excluding component inventory.
22#[derive(Debug, PartialEq, Eq)]
23pub struct DeviceInfo {
24    /// Three-character manufacturer identifier.
25    pub manufacturer: String,
26    /// Firmware version of the gateway itself.
27    pub firmware: String,
28}
29
30/// Stable failure categories. These carry no peer-provided identifiers or XML.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum DeviceInfoError {
33    XmlTooLarge,
34    XmlTooDeep,
35    InvalidXml,
36    UnsupportedObject,
37    DeviceMismatch,
38    InvalidField,
39}
40
41impl DeviceInfoError {
42    /// A diagnostic suitable for publication in a redacted receipt.
43    pub const fn code(self) -> &'static str {
44        match self {
45            Self::XmlTooLarge => "xml-too-large",
46            Self::XmlTooDeep => "xml-too-deep",
47            Self::InvalidXml => "invalid-xml",
48            Self::UnsupportedObject => "unsupported-object",
49            Self::DeviceMismatch => "device-mismatch",
50            Self::InvalidField => "invalid-field",
51        }
52    }
53}
54impl fmt::Display for DeviceInfoError {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.write_str(self.code())
57    }
58}
59impl std::error::Error for DeviceInfoError {}
60
61#[derive(Clone, Copy)]
62enum Element {
63    Object,
64    Attributes,
65    LogicalName,
66    Device,
67    Manufacturer,
68    Firmware,
69    Inventory,
70}
71
72#[derive(Default)]
73struct Fields {
74    logical_name: Option<String>,
75    device: Option<String>,
76    manufacturer: Option<String>,
77    firmware: Option<String>,
78}
79
80impl Fields {
81    fn value(&mut self, element: Element) -> Option<&mut Option<String>> {
82        match element {
83            Element::LogicalName => Some(&mut self.logical_name),
84            Element::Device => Some(&mut self.device),
85            Element::Manufacturer => Some(&mut self.manufacturer),
86            Element::Firmware => Some(&mut self.firmware),
87            _ => None,
88        }
89    }
90}
91
92fn check_object(
93    name: &OwnedName,
94    attributes: &[OwnedAttribute],
95    expected: &str,
96) -> Result<(), DeviceInfoError> {
97    if !matches_name(name, INFO_NS, "object")
98        || attributes.len() != 3
99        || attribute(attributes, "class_id") != Some("32781")
100        || attribute(attributes, "class_version") != Some("1")
101    {
102        return Err(DeviceInfoError::UnsupportedObject);
103    }
104    if attribute(attributes, "id") != Some(expected) {
105        return Err(DeviceInfoError::DeviceMismatch);
106    }
107    Ok(())
108}
109
110fn field(name: &OwnedName) -> Result<Element, DeviceInfoError> {
111    match (name.namespace.as_deref(), name.local_name.as_str()) {
112        (Some(EXT_NS), "logical_name") => Ok(Element::LogicalName),
113        (Some(INFO_NS), "smgw_id") => Ok(Element::Device),
114        (Some(INFO_NS), "manufacturer") => Ok(Element::Manufacturer),
115        (Some(INFO_NS), "fw_version") => Ok(Element::Firmware),
116        (
117            Some(INFO_NS),
118            "components" | "ipv4_addresses" | "ipv6_addresses" | "manufacturer_data",
119        ) => Ok(Element::Inventory),
120        _ => Err(DeviceInfoError::InvalidField),
121    }
122}
123
124fn attribute<'a>(attrs: &'a [OwnedAttribute], key: &str) -> Option<&'a str> {
125    attrs
126        .iter()
127        .find(|attr| attr.name.namespace.is_none() && attr.name.local_name == key)
128        .map(|attr| attr.value.as_str())
129}
130
131/// Read the example's unannotated `fw_version` representation. The requested
132/// logical device includes its `.sm` suffix. All three identity fields must agree.
133/// Unsupported version/active representations require a separate reviewed mapping.
134pub fn decode_device_info(xml: &[u8], logical_device: &str) -> Result<DeviceInfo, DeviceInfoError> {
135    use DeviceInfoError::*;
136    if xml.len() > MAX_XML_BYTES {
137        return Err(XmlTooLarge);
138    }
139    let id = logical_device.strip_suffix(".sm").ok_or(DeviceMismatch)?;
140    if id.is_empty()
141        || id.len() > 63
142        || !id
143            .bytes()
144            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
145    {
146        return Err(DeviceMismatch);
147    }
148    let expected_object = format!("01005e3180a0.{logical_device}");
149    let reader = ParserConfig::new()
150        .allow_multiple_root_elements(false)
151        .max_entity_expansion_depth(0)
152        .max_entity_expansion_length(0)
153        .max_name_length(256)
154        .max_attributes(64)
155        .max_attribute_length(4096)
156        .max_data_length(MAX_XML_BYTES)
157        .create_reader(xml);
158    let mut stack = Vec::with_capacity(MAX_XML_DEPTH);
159    let mut fields = Fields::default();
160    let mut saw_attributes = false;
161    for event in reader {
162        match event.map_err(|_| InvalidXml)? {
163            XmlEvent::StartDocument { encoding, .. } if !encoding.eq_ignore_ascii_case("UTF-8") => {
164                return Err(InvalidXml);
165            }
166            XmlEvent::Doctype { .. } | XmlEvent::ProcessingInstruction { .. } => {
167                return Err(InvalidXml);
168            }
169            XmlEvent::StartElement {
170                name, attributes, ..
171            } => {
172                if stack.len() == MAX_XML_DEPTH {
173                    return Err(XmlTooDeep);
174                }
175                let element = match stack.last() {
176                    None => {
177                        check_object(&name, &attributes, &expected_object)?;
178                        Element::Object
179                    }
180                    Some(Element::Object)
181                        if !saw_attributes
182                            && matches_name(&name, INFO_NS, "attributes")
183                            && attributes.is_empty() =>
184                    {
185                        saw_attributes = true;
186                        Element::Attributes
187                    }
188                    Some(Element::Attributes) => {
189                        let element = field(&name)?;
190                        if let Some(slot) = fields.value(element)
191                            && (!attributes.is_empty() || slot.replace(String::new()).is_some())
192                        {
193                            return Err(InvalidField);
194                        }
195                        element
196                    }
197                    Some(Element::Inventory) => Element::Inventory,
198                    _ => return Err(InvalidField),
199                };
200                stack.push(element);
201            }
202            XmlEvent::EndElement { .. } => {
203                stack.pop();
204            }
205            XmlEvent::Characters(chunk) | XmlEvent::CData(chunk) | XmlEvent::Whitespace(chunk) => {
206                if let Some(Some(value)) = stack.last().and_then(|&element| fields.value(element)) {
207                    if value.len() + chunk.len() > MAX_VALUE_BYTES
208                        || chunk.chars().any(char::is_control)
209                    {
210                        return Err(InvalidField);
211                    }
212                    value.push_str(&chunk);
213                } else if !matches!(stack.last(), Some(Element::Inventory))
214                    && !chunk.trim().is_empty()
215                {
216                    return Err(InvalidField);
217                }
218            }
219            _ => {}
220        }
221    }
222    if fields.logical_name.as_deref() != Some(&expected_object)
223        || fields.device.as_deref() != Some(logical_device)
224    {
225        return Err(DeviceMismatch);
226    }
227    let manufacturer = fields
228        .manufacturer
229        .filter(|value| value.chars().count() == 3 && !value.chars().any(char::is_whitespace))
230        .ok_or(InvalidField)?;
231    let firmware = fields
232        .firmware
233        .filter(|value| !value.trim().is_empty())
234        .ok_or(InvalidField)?;
235    Ok(DeviceInfo {
236        manufacturer,
237        firmware,
238    })
239}
240
241fn matches_name(name: &OwnedName, namespace: &str, local: &str) -> bool {
242    name.namespace.as_deref() == Some(namespace) && name.local_name == local
243}