Skip to main content

openbim_ilcd_epd/
parser.rs

1use openbim_epd::InformationModule;
2use roxmltree::{Document as XmlDocument, Error as XmlError, Node, ParsingOptions};
3
4use crate::{
5    Document, FormatVersion, MultilingualName, ParseError, ParseErrorKind, ProcessDataset,
6    COMMON_NAMESPACE, EPD_2013_NAMESPACE, EPD_2019_NAMESPACE, PROCESS_NAMESPACE,
7};
8
9const XML_NAMESPACE: &str = "http://www.w3.org/XML/1998/namespace";
10
11/// Resource budgets for parsing untrusted ILCD+EPD XML.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct ParseOptions {
14    /// Maximum UTF-8 input bytes.
15    pub max_bytes: usize,
16    /// Maximum XML nodes, including text and comments.
17    pub max_nodes: usize,
18    /// Maximum nested element depth, counting the root as one.
19    pub max_depth: usize,
20    /// Maximum attributes on one element.
21    pub max_attributes: usize,
22}
23
24impl Default for ParseOptions {
25    fn default() -> Self {
26        Self {
27            max_bytes: 16 * 1024 * 1024,
28            max_nodes: 1_000_000,
29            max_depth: 128,
30            max_attributes: 256,
31        }
32    }
33}
34
35impl ParseOptions {
36    /// Returns these limits with a different byte budget.
37    #[must_use]
38    pub const fn with_max_bytes(mut self, max_bytes: usize) -> Self {
39        self.max_bytes = max_bytes;
40        self
41    }
42
43    /// Returns these limits with a different node budget.
44    #[must_use]
45    pub const fn with_max_nodes(mut self, max_nodes: usize) -> Self {
46        self.max_nodes = max_nodes;
47        self
48    }
49
50    /// Returns these limits with a different element-depth budget.
51    #[must_use]
52    pub const fn with_max_depth(mut self, max_depth: usize) -> Self {
53        self.max_depth = max_depth;
54        self
55    }
56
57    /// Returns these limits with a different per-element attribute budget.
58    #[must_use]
59    pub const fn with_max_attributes(mut self, max_attributes: usize) -> Self {
60        self.max_attributes = max_attributes;
61        self
62    }
63}
64
65pub(crate) fn parse(input: &[u8], options: ParseOptions) -> Result<Document, ParseError> {
66    if input.len() > options.max_bytes {
67        return Err(ParseError::new(
68            ParseErrorKind::InputTooLarge,
69            format!("{} bytes exceeds limit {}", input.len(), options.max_bytes),
70        ));
71    }
72    let xml = std::str::from_utf8(input)
73        .map_err(|error| ParseError::new(ParseErrorKind::InvalidUtf8, error.to_string()))?;
74    let parsed = XmlDocument::parse_with_options(
75        xml,
76        ParsingOptions {
77            allow_dtd: false,
78            nodes_limit: u32::try_from(options.max_nodes).unwrap_or(u32::MAX),
79            entity_resolver: None,
80        },
81    )
82    .map_err(map_xml_error)?;
83
84    enforce_tree_limits(&parsed, options)?;
85    let root = parsed.root_element();
86    if root.tag_name().namespace() != Some(PROCESS_NAMESPACE)
87        || root.tag_name().name() != "processDataSet"
88    {
89        return Err(ParseError::new(
90            ParseErrorKind::UnexpectedRoot,
91            format!(
92                "expected {{{PROCESS_NAMESPACE}}}processDataSet, found {{{}}}{}",
93                root.tag_name().namespace().unwrap_or(""),
94                root.tag_name().name()
95            ),
96        ));
97    }
98
99    let version = match root.attribute((EPD_2019_NAMESPACE, "epd-version")) {
100        Some("1.3") => FormatVersion::V1_3,
101        Some(value) => {
102            return Err(ParseError::new(
103                ParseErrorKind::UnsupportedFormatVersion,
104                format!("unsupported epd-version `{value}`; expected `1.3`"),
105            ))
106        }
107        None => {
108            return Err(ParseError::new(
109                ParseErrorKind::MissingFormatVersion,
110                "missing namespaced epd2019:epd-version attribute",
111            ))
112        }
113    };
114
115    let data_set_information = child_named(root, PROCESS_NAMESPACE, "processInformation")
116        .and_then(|node| child_named(node, PROCESS_NAMESPACE, "dataSetInformation"));
117    let uuid = data_set_information
118        .and_then(|node| child_named(node, COMMON_NAMESPACE, "UUID"))
119        .and_then(|node| node.text())
120        .map(str::trim)
121        .filter(|value| !value.is_empty())
122        .ok_or_else(|| {
123            ParseError::new(ParseErrorKind::MissingUuid, "missing non-empty common:UUID")
124        })?
125        .to_owned();
126    if !is_canonical_uuid(&uuid) {
127        return Err(ParseError::new(
128            ParseErrorKind::InvalidUuid,
129            format!("`{uuid}` is not a canonical UUID"),
130        ));
131    }
132
133    let names: Vec<_> = data_set_information
134        .and_then(|node| child_named(node, PROCESS_NAMESPACE, "name"))
135        .into_iter()
136        .flat_map(|node| node.children())
137        .filter(|node| element_named(*node, PROCESS_NAMESPACE, "baseName"))
138        .filter_map(|node| {
139            let text = node.text()?.trim();
140            if text.is_empty() {
141                return None;
142            }
143            let language = node.attribute((XML_NAMESPACE, "lang")).unwrap_or("und");
144            Some(MultilingualName::new(language.to_owned(), text.to_owned()))
145        })
146        .collect();
147    if names.is_empty() {
148        return Err(ParseError::new(
149            ParseErrorKind::MissingName,
150            "missing non-empty process:name/process:baseName",
151        ));
152    }
153
154    let mut declared = Vec::new();
155    for (container_name, item_name) in [("exchanges", "exchange"), ("LCIAResults", "LCIAResult")] {
156        let Some(container) = child_named(root, PROCESS_NAMESPACE, container_name) else {
157            continue;
158        };
159        for item in container
160            .children()
161            .filter(|node| element_named(*node, PROCESS_NAMESPACE, item_name))
162        {
163            for other in item
164                .children()
165                .filter(|node| element_named(*node, COMMON_NAMESPACE, "other"))
166            {
167                for amount in other
168                    .children()
169                    .filter(|node| element_named(*node, EPD_2013_NAMESPACE, "amount"))
170                {
171                    let Some(code) = amount.attribute((EPD_2013_NAMESPACE, "module")) else {
172                        continue;
173                    };
174                    let module = InformationModule::from_code(code).ok_or_else(|| {
175                        ParseError::new(
176                            ParseErrorKind::InvalidInformationModule,
177                            format!("unsupported EPD module code `{code}`"),
178                        )
179                    })?;
180                    if !declared.contains(&module) {
181                        declared.push(module);
182                    }
183                }
184            }
185        }
186    }
187    let modules = InformationModule::ALL
188        .into_iter()
189        .filter(|module| declared.contains(module))
190        .collect();
191
192    Ok(Document::parsed(
193        input,
194        ProcessDataset::new(version, uuid, names, modules),
195    ))
196}
197
198fn element_named(node: Node<'_, '_>, namespace: &str, local_name: &str) -> bool {
199    node.is_element()
200        && node.tag_name().namespace() == Some(namespace)
201        && node.tag_name().name() == local_name
202}
203
204fn child_named<'a, 'input>(
205    node: Node<'a, 'input>,
206    namespace: &str,
207    local_name: &str,
208) -> Option<Node<'a, 'input>> {
209    node.children().find(|child| {
210        child.is_element()
211            && child.tag_name().namespace() == Some(namespace)
212            && child.tag_name().name() == local_name
213    })
214}
215
216fn is_canonical_uuid(value: &str) -> bool {
217    value.len() == 36
218        && value.bytes().enumerate().all(|(index, byte)| match index {
219            8 | 13 | 18 | 23 => byte == b'-',
220            _ => byte.is_ascii_hexdigit(),
221        })
222}
223
224fn enforce_tree_limits(parsed: &XmlDocument<'_>, options: ParseOptions) -> Result<(), ParseError> {
225    for node in parsed.descendants().filter(roxmltree::Node::is_element) {
226        let depth = node.ancestors().filter(roxmltree::Node::is_element).count();
227        if depth > options.max_depth {
228            return Err(ParseError::new(
229                ParseErrorKind::DepthLimitExceeded,
230                format!("element depth {depth} exceeds limit {}", options.max_depth),
231            ));
232        }
233        let attributes = node.attributes().len();
234        if attributes > options.max_attributes {
235            return Err(ParseError::new(
236                ParseErrorKind::AttributeLimitExceeded,
237                format!(
238                    "element has {attributes} attributes; limit is {}",
239                    options.max_attributes
240                ),
241            ));
242        }
243    }
244    Ok(())
245}
246
247fn map_xml_error(error: XmlError) -> ParseError {
248    let kind = match error {
249        XmlError::DtdDetected => ParseErrorKind::DoctypeForbidden,
250        XmlError::NodesLimitReached => ParseErrorKind::NodeLimitExceeded,
251        _ => ParseErrorKind::MalformedXml,
252    };
253    ParseError::new(kind, error.to_string())
254}