Files
Liber-public/crates/liber-format/src/sanitize.rs
T

349 lines
10 KiB
Rust

//! The sanitizer (docs/FORMATS.md §3, §4): a whitelist from the parsed tree to Liber's own tree, and the
//! serializer that turns that tree into well-formed XHTML the WebView's XML parser reads back unchanged.
use crate::xml::{XEl, XNode, local};
/// Dropped with everything inside.
pub(crate) const DROP: &[&str] = &[
"script", "style", "iframe", "frame", "frameset", "object", "embed", "applet", "form", "input", "button", "select",
"textarea", "option", "optgroup", "datalist", "output", "noscript", "template", "audio", "video", "source",
"track", "canvas", "link", "meta", "base", "title", "head", "math", "param", "map", "area", "dialog", "portal",
"slot", "picture", "keygen", "menu", "marquee", "frame",
];
/// Kept (with the attribute whitelist); everything else is unwrapped.
const KEEP: &[&str] = &[
"p",
"div",
"span",
"section",
"article",
"aside",
"header",
"footer",
"main",
"nav",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"blockquote",
"pre",
"code",
"em",
"i",
"strong",
"b",
"u",
"s",
"sub",
"sup",
"small",
"br",
"hr",
"ul",
"ol",
"li",
"dl",
"dt",
"dd",
"table",
"thead",
"tbody",
"tfoot",
"tr",
"td",
"th",
"caption",
"colgroup",
"col",
"figure",
"figcaption",
"img",
"a",
"abbr",
"cite",
"q",
"dfn",
"kbd",
"samp",
"var",
"mark",
"ruby",
"rt",
"rp",
"bdi",
"bdo",
"wbr",
"time",
"del",
"ins",
];
const VOID: &[&str] = &["br", "hr", "img", "wbr", "col"];
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Node {
Element(Element),
Text(String),
}
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct Element {
pub name: String,
pub attrs: Vec<(String, String)>,
pub children: Vec<Node>,
}
impl Element {
pub fn new(name: &str) -> Element {
Element { name: name.to_owned(), ..Element::default() }
}
pub fn attr(&self, k: &str) -> Option<&str> {
self.attrs.iter().find(|(a, _)| a == k).map(|(_, v)| v.as_str())
}
/// Appends text, merged with a preceding text node; characters XML cannot carry are dropped here, so the tree
/// and its serialization hold the same text.
pub fn push_text(&mut self, t: &str) {
let t: String = t
.chars()
.filter(|&c| !((c as u32) < 0x20 && !matches!(c, '\t' | '\n' | '\r')) && c != '\u{FFFE}' && c != '\u{FFFF}')
.collect();
if t.is_empty() {
return;
}
if let Some(Node::Text(last)) = self.children.last_mut() {
last.push_str(&t);
} else {
self.children.push(Node::Text(t));
}
}
pub fn push(&mut self, e: Element) {
self.children.push(Node::Element(e));
}
/// Every text node below, in order (iterative).
pub fn collect_text(&self, out: &mut String) {
let mut stack: Vec<&Node> = self.children.iter().rev().collect();
while let Some(n) = stack.pop() {
match n {
Node::Text(t) => out.push_str(t),
Node::Element(e) => stack.extend(e.children.iter().rev()),
}
}
}
pub fn text(&self) -> String {
let mut s = String::new();
self.collect_text(&mut s);
s
}
pub fn text_len_utf16(&self) -> usize {
crate::text::utf16_len(&self.text())
}
pub fn element_children(&self) -> impl Iterator<Item = &Element> {
self.children.iter().filter_map(|c| if let Node::Element(e) = c { Some(e) } else { None })
}
/// Every descendant element, in document order (iterative).
pub fn descendants(&self) -> Vec<&Element> {
let mut out = Vec::new();
let mut stack: Vec<&Element> = self.element_children().collect::<Vec<_>>().into_iter().rev().collect();
while let Some(e) = stack.pop() {
out.push(e);
stack.extend(e.element_children().collect::<Vec<_>>().into_iter().rev());
}
out
}
pub fn first_heading(&self) -> Option<String> {
self.descendants()
.into_iter()
.find(|e| matches!(e.name.as_str(), "h1" | "h2" | "h3" | "h4" | "h5" | "h6"))
.map(|h| h.text())
}
}
/// Resolves links and images while sanitizing. Both answer `None` for anything outside the book.
pub(crate) trait Resolver {
/// `href` as written → `"<chapter>#<id>"` (or `"<chapter>"`).
fn link(&mut self, href: &str) -> Option<String>;
/// `src` as written → the image's index.
fn image(&mut self, src: &str) -> Option<usize>;
}
pub(crate) fn is_remote(url: &str) -> bool {
let u = url.trim().to_ascii_lowercase();
u.starts_with("//") || u.split_once(':').is_some_and(|(s, _)| !s.contains('/') && s.len() > 1)
}
pub(crate) struct Sanitized {
pub root: Element,
pub notes: Vec<(String, String)>,
pub dropped: usize,
}
/// Sanitizes the children of `body` into a chapter root.
pub(crate) fn sanitize(body: &XEl, r: &mut dyn Resolver) -> Sanitized {
let mut root = Element::new("div");
let mut dropped = 0;
children(body, &mut root, r, &mut dropped);
let notes = collect_notes(&root);
Sanitized { root, notes, dropped }
}
fn children(from: &XEl, to: &mut Element, r: &mut dyn Resolver, dropped: &mut usize) {
for c in &from.children {
match c {
XNode::Text(t) => to.push_text(t),
XNode::El(e) => one(e, to, r, dropped),
}
}
}
fn one(e: &XEl, to: &mut Element, r: &mut dyn Resolver, dropped: &mut usize) {
let name = e.local().to_ascii_lowercase();
if name == "svg" {
// An SVG cover page: keep its one raster image, drop the rest of the SVG.
if let Some(img) = e.find("image")
&& let Some(href) = img.attr("xlink:href").or_else(|| img.attr("href"))
&& let Some(i) = r.image(href)
{
let mut out = Element::new("img");
out.attrs.push(("data-img".into(), i.to_string()));
out.attrs.push(("alt".into(), String::new()));
to.push(out);
} else {
*dropped += 1;
}
return;
}
if DROP.contains(&name.as_str()) {
return;
}
if !KEEP.contains(&name.as_str()) {
children(e, to, r, dropped);
return;
}
let mut out = Element::new(&name);
for (k, v) in &e.attrs {
let kl = k.to_ascii_lowercase();
let ll = local(&kl);
let v = v.trim();
match (kl.as_str(), ll) {
("epub:type", _) => out.attrs.push(("data-epub-type".into(), short(v))),
(_, "id") if !kl.contains(':') || kl == "xml:id" => out.attrs.push(("id".into(), short(v))),
("lang" | "xml:lang", _) => out.attrs.push(("lang".into(), short(v))),
("title" | "dir" | "alt", _) => out.attrs.push((kl.clone(), short(v))),
("colspan" | "rowspan", _) if v.len() <= 3 && v.bytes().all(|b| b.is_ascii_digit()) => {
out.attrs.push((kl.clone(), v.to_owned()))
}
("href", _) if name == "a" => {
if let Some(t) = r.link(v) {
out.attrs.push(("data-href".into(), t));
}
}
("src", _) if name == "img" => {
if let Some(i) = r.image(v) {
out.attrs.push(("data-img".into(), i.to_string()));
}
}
_ => {}
}
}
if name == "img" && out.attr("data-img").is_none() {
*dropped += 1;
return;
}
// One attribute of a name: the first wins.
let mut seen = std::collections::BTreeSet::new();
out.attrs.retain(|(k, _)| seen.insert(k.clone()));
if !VOID.contains(&name.as_str()) {
children(e, &mut out, r, dropped);
}
to.push(out);
}
fn short(v: &str) -> String {
v.chars().filter(|c| !c.is_control()).take(1024).collect()
}
fn note_type(t: &str) -> bool {
t.split_whitespace().any(|w| matches!(w, "footnote" | "endnote" | "rearnote" | "note"))
}
fn collect_notes(root: &Element) -> Vec<(String, String)> {
let mut out = Vec::new();
for e in root.descendants() {
let is_note = e.attr("data-epub-type").is_some_and(note_type) || e.name == "aside";
if is_note && let Some(id) = e.attr("id") {
let mut wrap = Element::new("div");
wrap.children = e.children.clone();
out.push((id.to_owned(), serialize(&wrap)));
}
}
out
}
fn esc(s: &str, out: &mut String, attr: bool) {
for c in s.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' if attr => out.push_str("&quot;"),
// XML 1.0 forbids most controls; drop them rather than break the document.
c if (c as u32) < 0x20 && !matches!(c, '\t' | '\n' | '\r') => {}
'\r' => out.push_str("&#13;"),
'\u{FFFE}' | '\u{FFFF}' => {}
c => out.push(c),
}
}
}
/// The root as `<div xmlns="http://www.w3.org/1999/xhtml">…</div>`.
pub fn serialize(root: &Element) -> String {
let mut out = String::new();
out.push_str("<div xmlns=\"http://www.w3.org/1999/xhtml\">");
// Iterative: (element, child index) frames.
let mut stack: Vec<(&Element, usize)> = vec![(root, 0)];
while let Some((e, i)) = stack.pop() {
if i < e.children.len() {
stack.push((e, i + 1));
match &e.children[i] {
Node::Text(t) => esc(t, &mut out, false),
Node::Element(c) => {
out.push('<');
out.push_str(&c.name);
for (k, v) in &c.attrs {
out.push(' ');
out.push_str(k);
out.push_str("=\"");
esc(v, &mut out, true);
out.push('"');
}
if c.children.is_empty() && VOID.contains(&c.name.as_str()) {
out.push_str("/>");
} else {
out.push('>');
stack.push((c, 0));
}
}
}
} else if !std::ptr::eq(e, root) {
out.push_str("</");
out.push_str(&e.name);
out.push('>');
}
}
out.push_str("</div>");
out
}