mod input;
pub(crate) mod paths;
mod stream;
mod tree;
use std::borrow::Cow;
use std::sync::{Arc, LazyLock, RwLock};
use serde::Deserialize;
use thiserror::Error;
pub use paths::{Kind, Path, PathError, Paths, Raw, Slot, Slots, Values};
pub use stream::XmlRecords;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecordSpec {
#[default]
Auto,
Path(Vec<String>),
}
impl TryFrom<String> for RecordSpec {
type Error = String;
fn try_from(s: String) -> Result<Self, Self::Error> {
if s == "auto" {
return Ok(Self::Auto);
}
let path: Vec<String> = s
.strip_prefix('/')
.ok_or_else(|| format!("record: {s:?} is neither `auto` nor a path from `/`"))?
.split('/')
.map(str::to_owned)
.collect();
if path.iter().any(String::is_empty) {
return Err(format!("record: {s:?} has an empty step"));
}
Ok(Self::Path(path))
}
}
impl<'de> Deserialize<'de> for RecordSpec {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Self::try_from(s).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Arrays {
#[default]
Always,
Auto,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Namespaces {
#[default]
Strip,
Keep,
Expand,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Keyed {
pub path: String,
pub attribute: String,
}
impl Keyed {
#[must_use]
pub fn new(path: impl Into<String>, attribute: impl Into<String>) -> Self {
Self {
path: path.into(),
attribute: attribute.into(),
}
}
#[cfg(feature = "record")]
pub(crate) fn applies<'n>(&self, names: impl IntoIterator<Item = &'n [u8]>) -> bool {
let mut names = names.into_iter();
self.path
.split('.')
.all(|part| names.next() == Some(part.as_bytes()))
&& names.next().is_none()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct XmlLimits {
pub max_record_bytes: usize,
pub max_depth: usize,
pub detect_bytes: usize,
pub max_attributes: usize,
}
impl Default for XmlLimits {
fn default() -> Self {
Self {
max_record_bytes: 16 << 20,
max_depth: 64,
detect_bytes: 16 << 20,
max_attributes: 256,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct XmlConfig {
pub record: RecordSpec,
pub arrays: Arrays,
pub single: Vec<String>,
pub namespaces: Namespaces,
#[serde(deserialize_with = "ordered_map")]
pub carry: Vec<(String, String)>,
pub attr_prefix: String,
pub text_key: String,
pub trim_text: bool,
pub meta_key: Option<String>,
pub limits: XmlLimits,
pub dialects: DialectMode,
}
impl Default for XmlConfig {
fn default() -> Self {
Self {
record: RecordSpec::Auto,
arrays: Arrays::Always,
single: Vec::new(),
namespaces: Namespaces::Strip,
attr_prefix: "@".to_owned(),
text_key: "#text".to_owned(),
trim_text: true,
meta_key: Some("_xml".to_owned()),
carry: Vec::new(),
limits: XmlLimits::default(),
dialects: DialectMode::Auto,
}
}
}
fn ordered_map<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<(String, String)>, D::Error> {
struct Pairs;
impl<'de> serde::de::Visitor<'de> for Pairs {
type Value = Vec<(String, String)>;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("a map of output keys to paths")
}
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> Result<Self::Value, A::Error> {
let mut pairs = Vec::new();
while let Some((key, path)) = map.next_entry::<String, String>()? {
let steps = local_steps(&path);
let bad = steps.iter().any(|s| s.is_empty() || s.contains('/'))
|| steps[..steps.len() - 1].iter().any(|s| s.starts_with('@'));
if bad {
return Err(serde::de::Error::custom(format!(
"carry {key}: {path:?} is not a path of local names"
)));
}
pairs.push((key, path));
}
Ok(pairs)
}
}
d.deserialize_map(Pairs)
}
pub(crate) fn local_steps(path: &str) -> Vec<String> {
path.strip_prefix('/').map_or_else(
|| crate::path::keys(path).map(Cow::into_owned).collect(),
|rest| rest.split('/').map(str::to_owned).collect(),
)
}
pub(crate) fn slash_path(path: &str) -> Cow<'_, str> {
if path.starts_with('/') {
Cow::Borrowed(path)
} else {
Cow::Owned(
local_steps(path)
.iter()
.fold(String::new(), |mut out, step| {
out.push('/');
out.push_str(step);
out
}),
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum XmlError {
#[error("xml: malformed at byte {offset}: {reason}")]
Malformed {
offset: u64,
reason: String,
},
#[error("xml: elements nest deeper than {max}")]
TooDeep {
max: usize,
},
#[error("xml: a record spans more than {max} bytes")]
RecordTooLarge {
max: usize,
},
#[error("xml: a <!DOCTYPE> is refused")]
Doctype,
#[error("xml: the declared encoding {label:?} isn't UTF-8")]
Encoding {
label: String,
},
#[error("xml: a {} fault: {}", .0.version, .0.reason)]
SoapFault(Box<SoapFault>),
}
impl XmlError {
#[must_use]
pub const fn kind(&self) -> &'static str {
match self {
Self::Malformed { .. } => "malformed",
Self::TooDeep { .. } => "too_deep",
Self::RecordTooLarge { .. } => "record_too_large",
Self::Doctype => "doctype",
Self::Encoding { .. } => "encoding",
Self::SoapFault(_) => "soap_fault",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SoapFault {
pub version: String,
pub code: String,
pub subcode: Option<String>,
pub reason: String,
pub node: Option<String>,
pub role: Option<String>,
pub detail: Option<String>,
}
impl SoapFault {
#[must_use]
pub fn to_json(&self) -> Vec<u8> {
let mut out = b"{\"version\":".to_vec();
tree::string(&mut out, &self.version);
let optional = [
("code", Some(&self.code)),
("subcode", self.subcode.as_ref()),
("reason", Some(&self.reason)),
("node", self.node.as_ref()),
("role", self.role.as_ref()),
];
for (key, value) in optional {
if let Some(v) = value {
out.push(b',');
tree::string(&mut out, key);
out.push(b':');
tree::string(&mut out, v);
}
}
if let Some(detail) = &self.detail {
out.extend_from_slice(b",\"detail\":");
out.extend_from_slice(detail.as_bytes());
}
out.push(b'}');
out
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct FaultPaths {
pub code: Option<String>,
pub subcode: Option<String>,
pub reason: Option<String>,
pub node: Option<String>,
pub role: Option<String>,
pub detail: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct DialectSpec {
pub version: String,
pub namespace: String,
pub element: String,
pub content: String,
#[serde(default)]
pub header: Option<String>,
#[serde(default)]
pub fault: Option<String>,
#[serde(default)]
pub fault_fields: FaultPaths,
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum RegistryError {
#[error("xml: a dialect for {{{namespace}}}{element} is already registered")]
Duplicate {
namespace: String,
element: String,
},
#[error("xml: dialect {0}: a path is empty or has an empty step")]
BadPath(String),
}
static DIALECTS: LazyLock<RwLock<Arc<[DialectSpec]>>> =
LazyLock::new(|| RwLock::new(Arc::from(soap_dialects())));
pub fn register_dialect(name: &str, spec: DialectSpec) -> Result<(), RegistryError> {
let paths = [
Some(&spec.content),
spec.header.as_ref(),
spec.fault.as_ref(),
];
if paths
.into_iter()
.flatten()
.any(|p| p.is_empty() || p.split('/').any(str::is_empty))
{
return Err(RegistryError::BadPath(name.to_owned()));
}
let mut dialects = DIALECTS
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if dialect(&dialects, &spec.namespace, &spec.element).is_none() {
*dialects = dialects.iter().cloned().chain([spec]).collect();
return Ok(());
}
drop(dialects);
Err(RegistryError::Duplicate {
namespace: spec.namespace,
element: spec.element,
})
}
fn dialects() -> Arc<[DialectSpec]> {
Arc::clone(
&DIALECTS
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner),
)
}
fn soap_dialects() -> [DialectSpec; 2] {
let soap = |version: &str, namespace: &str, fields: FaultPaths| DialectSpec {
version: version.to_owned(),
namespace: namespace.to_owned(),
element: "Envelope".to_owned(),
content: "Body".to_owned(),
header: Some("Header".to_owned()),
fault: Some("Body/Fault".to_owned()),
fault_fields: fields,
};
let path = |s: &str| Some(s.to_owned());
[
soap(
"1.1",
"http://schemas.xmlsoap.org/soap/envelope/",
FaultPaths {
code: path("faultcode"),
reason: path("faultstring"),
role: path("faultactor"),
detail: path("detail"),
..FaultPaths::default()
},
),
soap(
"1.2",
"http://www.w3.org/2003/05/soap-envelope",
FaultPaths {
code: path("Code/Value"),
subcode: path("Code/Subcode/Value"),
reason: path("Reason/Text"),
node: path("Node"),
role: path("Role"),
detail: path("Detail"),
},
),
]
}
fn dialect<'d>(
dialects: &'d [DialectSpec],
namespace: &str,
element: &str,
) -> Option<&'d DialectSpec> {
dialects
.iter()
.find(|d| d.namespace == namespace && d.element == element)
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum DialectMode {
#[default]
Auto,
Off,
}
pub fn to_records(doc: &[u8], cfg: &XmlConfig) -> Result<Vec<Vec<u8>>, XmlError> {
let mut records = XmlRecords::new(Arc::new(cfg.clone()));
let mut out = Vec::new();
records.feed(doc, &mut out)?;
records.finish(&mut out)?;
Ok(out)
}
pub fn to_json(fragment: &[u8], cfg: &XmlConfig) -> Result<Vec<u8>, XmlError> {
let mut records = XmlRecords::whole(Arc::new(cfg.clone()));
let mut out = Vec::new();
records.feed(fragment, &mut out)?;
records.finish(&mut out)?;
out.pop().ok_or_else(|| XmlError::Malformed {
offset: 0,
reason: "no element".to_owned(),
})
}
#[must_use]
pub fn is_xml_media_type(content_type: &str) -> bool {
let essence = content_type
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase();
essence == "application/xml" || essence == "text/xml" || essence.ends_with("+xml")
}
#[cfg(test)]
mod tests;