[format][library] Books: EPUB/FB2/TXT/MOBI/AZW3 into one sanitized model, CFI anchors, the event-log library, stats, CSV import, export

This commit is contained in:
2026-11-17 01:36:21 +01:00
parent 0b0e35d727
commit 8729119984
35 changed files with 7956 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
[package]
name = "liber-format"
description = "Liber Domi: e-book formats (EPUB, FB2, TXT, DRM-free MOBI/AZW3) into one sanitized document model"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
[lints]
workspace = true
[dependencies]
quick-xml.workspace = true
html5ever.workspace = true
markup5ever_rcdom.workspace = true
encoding_rs.workspace = true
chardetng.workspace = true
miniz_oxide.workspace = true
crc32fast.workspace = true
sha2.workspace = true
base64.workspace = true
unicode-normalization.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
[dev-dependencies]
proptest.workspace = true
miniz_oxide.workspace = true
+56
View File
@@ -0,0 +1,56 @@
//! DRM detection (docs/FORMATS.md §2). Detection only: there is no decrypt path anywhere in Liber.
use crate::xml;
use crate::zip::Zip;
use crate::{FormatError, Limits, Result};
/// Font obfuscation is not DRM: these algorithms only scramble embedded fonts.
const FONT_OBFUSCATION: &[&str] = &["http://www.idpf.org/2008/embedding", "http://ns.adobe.com/pdf/enc#RC"];
/// KFX and Topaz containers, refused before anything else looks at the bytes.
pub(crate) fn refuse_other_containers(bytes: &[u8]) -> Result<()> {
let head = &bytes[..bytes.len().min(1024)];
if crate::text::find(head, b"\xeaDRMION\xee").is_some() {
return Err(FormatError::Drm);
}
if bytes.starts_with(b"TPZ") {
return Err(FormatError::Drm);
}
if bytes.starts_with(b"CONT\x02\x00") {
return Err(FormatError::Unsupported("KFX books (convert them with the tool that made them)".into()));
}
Ok(())
}
pub(crate) fn epub(zip: &Zip, limits: &Limits) -> Result<()> {
for marker in ["META-INF/rights.xml", "META-INF/license.lcpl", "META-INF/sinf.xml"] {
if zip.find(marker).is_some() {
return Err(FormatError::Drm);
}
}
if let Some(bytes) = zip.read_name_capped("META-INF/encryption.xml", limits.max_xml as u64)? {
let text = crate::text::decode_xml(&bytes);
let root = match xml::parse(&text, limits) {
Ok(r) => r,
// An encryption.xml Liber cannot read: treat the book as protected rather than guess.
Err(FormatError::Unsafe(w)) => return Err(FormatError::Unsafe(w)),
Err(_) => return Err(FormatError::Drm),
};
let methods: Vec<String> = root
.descendants()
.into_iter()
.filter(|e| e.is("EncryptionMethod"))
.filter_map(|e| e.attr("Algorithm").map(str::to_owned))
.collect();
if methods.iter().any(|m| !FONT_OBFUSCATION.contains(&m.trim())) {
return Err(FormatError::Drm);
}
}
Ok(())
}
/// The PalmDOC header's encryption type (record 0, offset 12).
pub(crate) fn mobi(record0: &[u8]) -> Result<()> {
let enc = record0.get(12..14).map(|b| u16::from_be_bytes([b[0], b[1]])).unwrap_or(0);
if enc != 0 { Err(FormatError::Drm) } else { Ok(()) }
}
+168
View File
@@ -0,0 +1,168 @@
//! The named entities an XHTML book may use without declaring them: the five XML ones and HTML 4's (Latin-1,
//! symbols, specials). Nothing is ever resolved from a DOCTYPE.
pub fn resolve(name: &str) -> Option<&'static str> {
Some(match name {
"amp" => "&",
"lt" => "<",
"gt" => ">",
"quot" => "\"",
"apos" => "'",
"nbsp" => "\u{a0}",
"iexcl" => "¡",
"cent" => "¢",
"pound" => "£",
"curren" => "¤",
"yen" => "¥",
"brvbar" => "¦",
"sect" => "§",
"uml" => "¨",
"copy" => "©",
"ordf" => "ª",
"laquo" => "«",
"not" => "¬",
"shy" => "\u{ad}",
"reg" => "®",
"macr" => "¯",
"deg" => "°",
"plusmn" => "±",
"sup2" => "²",
"sup3" => "³",
"acute" => "´",
"micro" => "µ",
"para" => "",
"middot" => "·",
"cedil" => "¸",
"sup1" => "¹",
"ordm" => "º",
"raquo" => "»",
"frac14" => "¼",
"frac12" => "½",
"frac34" => "¾",
"iquest" => "¿",
"Agrave" => "À",
"Aacute" => "Á",
"Acirc" => "Â",
"Atilde" => "Ã",
"Auml" => "Ä",
"Aring" => "Å",
"AElig" => "Æ",
"Ccedil" => "Ç",
"Egrave" => "È",
"Eacute" => "É",
"Ecirc" => "Ê",
"Euml" => "Ë",
"Igrave" => "Ì",
"Iacute" => "Í",
"Icirc" => "Î",
"Iuml" => "Ï",
"ETH" => "Ð",
"Ntilde" => "Ñ",
"Ograve" => "Ò",
"Oacute" => "Ó",
"Ocirc" => "Ô",
"Otilde" => "Õ",
"Ouml" => "Ö",
"times" => "×",
"Oslash" => "Ø",
"Ugrave" => "Ù",
"Uacute" => "Ú",
"Ucirc" => "Û",
"Uuml" => "Ü",
"Yacute" => "Ý",
"THORN" => "Þ",
"szlig" => "ß",
"agrave" => "à",
"aacute" => "á",
"acirc" => "â",
"atilde" => "ã",
"auml" => "ä",
"aring" => "å",
"aelig" => "æ",
"ccedil" => "ç",
"egrave" => "è",
"eacute" => "é",
"ecirc" => "ê",
"euml" => "ë",
"igrave" => "ì",
"iacute" => "í",
"icirc" => "î",
"iuml" => "ï",
"eth" => "ð",
"ntilde" => "ñ",
"ograve" => "ò",
"oacute" => "ó",
"ocirc" => "ô",
"otilde" => "õ",
"ouml" => "ö",
"divide" => "÷",
"oslash" => "ø",
"ugrave" => "ù",
"uacute" => "ú",
"ucirc" => "û",
"uuml" => "ü",
"yacute" => "ý",
"thorn" => "þ",
"yuml" => "ÿ",
"OElig" => "Œ",
"oelig" => "œ",
"Scaron" => "Š",
"scaron" => "š",
"Yuml" => "Ÿ",
"fnof" => "ƒ",
"circ" => "ˆ",
"tilde" => "˜",
"ensp" => "\u{2002}",
"emsp" => "\u{2003}",
"thinsp" => "\u{2009}",
"zwnj" => "\u{200c}",
"zwj" => "\u{200d}",
"lrm" => "\u{200e}",
"rlm" => "\u{200f}",
"ndash" => "–",
"mdash" => "—",
"lsquo" => "‘",
"rsquo" => "’",
"sbquo" => "‚",
"ldquo" => "“",
"rdquo" => "”",
"bdquo" => "„",
"dagger" => "†",
"Dagger" => "‡",
"bull" => "•",
"hellip" => "…",
"permil" => "‰",
"prime" => "′",
"Prime" => "″",
"lsaquo" => "‹",
"rsaquo" => "›",
"oline" => "‾",
"frasl" => "⁄",
"euro" => "€",
"trade" => "™",
"larr" => "←",
"uarr" => "↑",
"rarr" => "→",
"darr" => "↓",
"harr" => "↔",
"minus" => "−",
"infin" => "∞",
"ne" => "≠",
"le" => "≤",
"ge" => "≥",
"loz" => "◊",
"spades" => "♠",
"clubs" => "♣",
"hearts" => "♥",
"diams" => "♦",
"alpha" => "α",
"beta" => "β",
"gamma" => "γ",
"delta" => "δ",
"pi" => "π",
"sigma" => "σ",
"omega" => "ω",
"Omega" => "Ω",
_ => return None,
})
}
+432
View File
@@ -0,0 +1,432 @@
//! EPUB 2 and 3.
use crate::sanitize::{Resolver, is_remote, sanitize};
use crate::xml::{self, XEl};
use crate::zip::Zip;
use crate::{Document, Format, FormatError, Image, Limits, Metadata, Result, Series, TocEntry, drm, text};
use std::collections::{BTreeMap, HashMap};
struct Item {
href: String,
media: String,
props: String,
}
/// Percent-decodes and normalises `rel` against the directory `base` (`""` for the root). `None` if it climbs out.
pub(crate) fn join(base: &str, rel: &str) -> Option<String> {
let rel = rel.split(['#', '?']).next().unwrap_or("");
let decoded = percent_decode(rel);
let mut parts: Vec<&str> =
if decoded.starts_with('/') { Vec::new() } else { base.split('/').filter(|s| !s.is_empty()).collect() };
for seg in decoded.split('/') {
match seg {
"" | "." => {}
".." => {
parts.pop()?;
}
s => parts.push(s),
}
}
Some(parts.join("/"))
}
fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
if b[i] == b'%'
&& i + 2 < b.len()
&& let (Some(h), Some(l)) = ((b[i + 1] as char).to_digit(16), (b[i + 2] as char).to_digit(16))
{
out.push((h * 16 + l) as u8);
i += 3;
continue;
}
out.push(b[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
fn dir_of(path: &str) -> &str {
path.rfind('/').map_or("", |i| &path[..i])
}
fn fragment(href: &str) -> Option<String> {
href.split_once('#').map(|(_, f)| percent_decode(f)).filter(|f| !f.is_empty())
}
/// Sniffs a raster image; `None` for anything else (SVG included).
pub(crate) fn raster(bytes: &[u8]) -> Option<&'static str> {
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
Some("image/png")
} else if bytes.starts_with(b"\xff\xd8\xff") {
Some("image/jpeg")
} else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
Some("image/gif")
} else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
Some("image/webp")
} else {
None
}
}
struct Ctx<'z, 'a> {
zip: &'z Zip<'a>,
limits: &'z Limits,
/// Spine path → chapter index.
spine: HashMap<String, usize>,
images: Vec<Image>,
by_path: HashMap<String, Option<usize>>,
base: String,
chapter: usize,
warnings: Vec<String>,
}
impl Ctx<'_, '_> {
fn load_image(&mut self, path: &str) -> Option<usize> {
if let Some(i) = self.by_path.get(path) {
return *i;
}
let r = (|| {
if self.images.len() >= self.limits.max_images {
return None;
}
let e = self.zip.find(path)?;
let bytes = self.zip.read(e).ok()?;
let media_type = raster(&bytes)?;
let index = self.images.len();
self.images.push(Image { index, media_type, bytes });
Some(index)
})();
self.by_path.insert(path.to_owned(), r);
r
}
}
impl Resolver for Ctx<'_, '_> {
fn link(&mut self, href: &str) -> Option<String> {
if is_remote(href) {
return None;
}
let frag = fragment(href);
let path_part = href.split('#').next().unwrap_or("");
let ch = if path_part.is_empty() { self.chapter } else { *self.spine.get(&join(&self.base, path_part)?)? };
Some(match frag {
Some(f) => format!("{ch}#{f}"),
None => ch.to_string(),
})
}
fn image(&mut self, src: &str) -> Option<usize> {
if is_remote(src) {
self.warnings.push("a remote image was not loaded".into());
return None;
}
let path = join(&self.base, src)?;
self.load_image(&path)
}
}
fn read_xml(zip: &Zip, path: &str, limits: &Limits) -> Result<Option<XEl>> {
match zip.read_name_capped(path, limits.max_xml as u64)? {
Some(b) => xml::parse(&text::decode_xml(&b), limits).map(Some),
None => Ok(None),
}
}
pub(crate) fn open(zip: &Zip, limits: &Limits) -> Result<Document> {
drm::epub(zip, limits)?;
let container = read_xml(zip, "META-INF/container.xml", limits)?
.ok_or_else(|| FormatError::Malformed("no META-INF/container.xml".into()))?;
let opf_path = container
.descendants()
.into_iter()
.filter(|e| e.is("rootfile"))
.find(|e| e.attr("media-type").is_none_or(|m| m.contains("oebps-package")))
.and_then(|e| e.attr("full-path"))
.and_then(|p| join("", p))
.ok_or_else(|| FormatError::Malformed("container.xml names no package".into()))?;
let opf =
read_xml(zip, &opf_path, limits)?.ok_or_else(|| FormatError::Malformed(format!("{opf_path} is missing")))?;
let opf_dir = dir_of(&opf_path).to_owned();
let mut items: HashMap<String, Item> = HashMap::new();
if let Some(manifest) = opf.child("manifest") {
for it in manifest.children_named("item") {
if let (Some(id), Some(href)) = (it.attr("id"), it.attr("href"))
&& let Some(href) = join(&opf_dir, href)
{
items.insert(
id.to_owned(),
Item {
href,
media: it.attr("media-type").unwrap_or("").to_owned(),
props: it.attr("properties").unwrap_or("").to_owned(),
},
);
}
}
}
let spine_el = opf.child("spine").ok_or_else(|| FormatError::Malformed("the package has no spine".into()))?;
let mut spine: Vec<(String, bool)> = Vec::new();
for r in spine_el.children_named("itemref") {
if let Some(it) = r.attr("idref").and_then(|id| items.get(id))
&& (it.media.contains("html") || it.media.is_empty())
&& !spine.iter().any(|(h, _)| *h == it.href)
{
spine.push((it.href.clone(), r.attr("linear") != Some("no")));
}
}
if spine.len() > limits.max_chapters {
return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters)));
}
let metadata = metadata(&opf);
let mut ctx = Ctx {
zip,
limits,
spine: spine.iter().enumerate().map(|(i, (h, _))| (h.clone(), i)).collect(),
images: Vec::new(),
by_path: HashMap::new(),
base: String::new(),
chapter: 0,
warnings: Vec::new(),
};
let mut chapters = Vec::new();
let mut footnotes = BTreeMap::new();
for (i, (href, linear)) in spine.iter().enumerate() {
ctx.base = dir_of(href).to_owned();
ctx.chapter = i;
let root = match chapter_body(zip, href, limits) {
Ok(b) => b,
Err(e @ (FormatError::Unsafe(_) | FormatError::TooLarge(_))) => return Err(e),
Err(e) => {
ctx.warnings.push(format!("{href}: {}", e.message()));
XEl::new("body")
}
};
let s = sanitize(&root, &mut ctx);
if s.dropped > 0 {
ctx.warnings.push(format!("{href}: {} element(s) dropped (remote or unsupported images)", s.dropped));
}
for (id, x) in s.notes {
footnotes.insert(format!("{i}#{id}"), x);
}
chapters.push(crate::chapter(href.clone(), None, *linear, s.root));
}
// Table of contents: the EPUB 3 nav, else the NCX.
let nav = items.values().find(|it| it.props.split_whitespace().any(|p| p == "nav"));
let mut toc = Vec::new();
if let Some(nav) = nav
&& let Ok(Some(doc)) = chapter_body(zip, &nav.href, limits).map(Some)
{
let base = dir_of(&nav.href).to_owned();
if let Some(n) = doc
.descendants()
.into_iter()
.filter(|e| e.is("nav"))
.find(|e| e.attr("epub:type").is_some_and(|t| t.split_whitespace().any(|w| w == "toc")))
&& let Some(ol) = n.child("ol")
{
toc = nav_list(ol, &base, &ctx.spine, 0);
}
}
if toc.is_empty() {
let ncx = spine_el
.attr("toc")
.and_then(|id| items.get(id))
.or_else(|| items.values().find(|it| it.media == "application/x-dtbncx+xml"));
if let Some(ncx) = ncx
&& let Ok(Some(root)) = read_xml(zip, &ncx.href, limits)
&& let Some(map) = root.child("navMap")
{
toc = ncx_list(map, dir_of(&ncx.href), &ctx.spine, 0);
}
}
// Chapter titles from the TOC where the chapter has no heading of its own.
fn first_titles(entries: &[TocEntry], out: &mut BTreeMap<usize, String>) {
for e in entries {
out.entry(e.chapter).or_insert_with(|| e.title.clone());
first_titles(&e.children, out);
}
}
let mut titles = BTreeMap::new();
first_titles(&toc, &mut titles);
for (i, c) in chapters.iter_mut().enumerate() {
if let Some(t) = titles.get(&i) {
c.title = Some(t.clone());
}
}
// Cover: EPUB 3 `cover-image`, else the EPUB 2 `<meta name="cover">`.
let cover_path = items
.values()
.find(|it| it.props.split_whitespace().any(|p| p == "cover-image"))
.map(|it| it.href.clone())
.or_else(|| {
let id = opf
.child("metadata")?
.children_named("meta")
.find(|m| m.attr("name") == Some("cover"))?
.attr("content")?
.to_owned();
items.get(&id).map(|it| it.href.clone())
});
let cover = cover_path.and_then(|p| ctx.load_image(&p));
Ok(Document {
format: Format::Epub,
metadata,
chapters,
toc,
footnotes,
images: ctx.images,
cover,
warnings: ctx.warnings,
})
}
/// A chapter's `<body>`: XML first, then tag soup if the chapter is not well-formed.
fn chapter_body(zip: &Zip, href: &str, limits: &Limits) -> Result<XEl> {
let bytes = zip
.read_name_capped(href, limits.max_xml as u64)?
.ok_or_else(|| FormatError::Malformed(format!("{href} is missing")))?;
let s = text::decode_xml(&bytes);
let root = match xml::parse(&s, limits) {
Ok(r) => r,
Err(e @ FormatError::Unsafe(_)) => return Err(e),
Err(_) => crate::html::parse(&s, limits)?,
};
if root.is("body") {
return Ok(root);
}
Ok(root.child("body").cloned().unwrap_or(root))
}
fn toc_target(base: &str, href: &str, spine: &HashMap<String, usize>) -> Option<(usize, Option<String>)> {
if is_remote(href) {
return None;
}
let path = join(base, href)?;
Some((*spine.get(&path)?, fragment(href)))
}
fn nav_list(ol: &XEl, base: &str, spine: &HashMap<String, usize>, depth: usize) -> Vec<TocEntry> {
let mut out = Vec::new();
if depth > 16 {
return out;
}
for li in ol.children_named("li") {
let label = li.child("a").or_else(|| li.child("span"));
let title = label.map(|l| text::collapse(&l.text())).unwrap_or_default();
let children = li.child("ol").map(|o| nav_list(o, base, spine, depth + 1)).unwrap_or_default();
match label.and_then(|l| l.attr("href")).and_then(|h| toc_target(base, h, spine)) {
Some((chapter, fragment)) if !title.is_empty() => out.push(TocEntry { title, chapter, fragment, children }),
_ => out.extend(children),
}
}
out
}
fn ncx_list(parent: &XEl, base: &str, spine: &HashMap<String, usize>, depth: usize) -> Vec<TocEntry> {
let mut out = Vec::new();
if depth > 16 {
return out;
}
for p in parent.children_named("navPoint") {
let title = p.child("navLabel").map(|l| text::collapse(&l.text())).unwrap_or_default();
let children = ncx_list(p, base, spine, depth + 1);
match p.child("content").and_then(|c| c.attr("src")).and_then(|h| toc_target(base, h, spine)) {
Some((chapter, fragment)) if !title.is_empty() => out.push(TocEntry { title, chapter, fragment, children }),
_ => out.extend(children),
}
}
out
}
/// Strips markup from a description (it is often escaped HTML).
pub(crate) fn plain(s: &str) -> String {
let mut out = String::new();
let mut tag = false;
for c in s.chars() {
match c {
'<' => tag = true,
'>' if tag => {
tag = false;
out.push(' ');
}
c if !tag => out.push(c),
_ => {}
}
}
let out = out
.replace("&nbsp;", " ")
.replace("&amp;", "&")
.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"");
text::collapse(&out)
}
fn metadata(opf: &XEl) -> Metadata {
let mut m = Metadata::default();
let Some(md) = opf.child("metadata") else { return m };
let all: Vec<&XEl> = md.descendants();
let refines = |id: Option<&str>, prop: &str| -> Option<String> {
let id = id?;
all.iter()
.filter(|e| e.is("meta"))
.find(|e| e.attr("refines") == Some(&format!("#{id}")) && e.attr("property") == Some(prop))
.map(|e| text::collapse(&e.text()))
};
for e in md.elements() {
let v = text::collapse(&e.text());
match e.local() {
"title" if m.title.is_none() && !v.is_empty() => m.title = Some(v),
"creator" => {
let role = e.attr("opf:role").map(str::to_owned).or_else(|| refines(e.attr("id"), "role"));
if role.as_deref().is_none_or(|r| r == "aut") && !v.is_empty() {
m.authors.push(v);
}
}
"language" if m.language.is_none() && !v.is_empty() => m.language = Some(v),
"identifier" if !v.is_empty() => m.identifiers.push(v),
"publisher" if m.publisher.is_none() && !v.is_empty() => m.publisher = Some(v),
"date" if m.published.is_none() && !v.is_empty() => m.published = Some(v),
"description" if m.description.is_none() => {
let p = plain(&e.text());
if !p.is_empty() {
m.description = Some(p);
}
}
"subject" if !v.is_empty() => m.subjects.push(v),
"meta" => {
if e.attr("name") == Some("calibre:series")
&& let Some(c) = e.attr("content")
{
m.series.get_or_insert_with(Series::default).name = c.trim().to_owned();
}
if e.attr("name") == Some("calibre:series_index")
&& let Some(c) = e.attr("content")
{
m.series.get_or_insert_with(Series::default).index = c.trim().parse().ok();
}
if e.attr("property") == Some("belongs-to-collection") && !v.is_empty() {
let kind = refines(e.attr("id"), "collection-type");
if kind.as_deref().is_none_or(|k| k == "series") {
let index = refines(e.attr("id"), "group-position").and_then(|p| p.parse().ok());
m.series = Some(Series { name: v, index });
}
}
}
_ => {}
}
}
if m.series.as_ref().is_some_and(|s| s.name.is_empty()) {
m.series = None;
}
m
}
+260
View File
@@ -0,0 +1,260 @@
//! FictionBook 2 (and `.fb2.zip`): FB2's vocabulary mapped to XHTML, then the same sanitizer as every format.
use crate::sanitize::{Resolver, is_remote, sanitize};
use crate::xml::{self, XEl, XNode};
use crate::zip::Zip;
use crate::{Document, Format, FormatError, Image, Limits, Metadata, Result, Series, TocEntry, text};
use base64::Engine;
use std::collections::{BTreeMap, HashMap};
pub(crate) fn open_zip(zip: &Zip, limits: &Limits) -> Result<Document> {
let e = zip
.entries()
.iter()
.find(|e| e.name.to_lowercase().ends_with(".fb2"))
.ok_or_else(|| FormatError::Malformed("the archive holds no .fb2 file".into()))?;
open(&zip.read_capped(e, limits.max_xml as u64)?, limits)
}
struct Ctx<'a> {
binaries: HashMap<String, (&'a str, String)>,
images: Vec<Image>,
loaded: HashMap<String, Option<usize>>,
ids: HashMap<String, usize>,
limits: &'a Limits,
warnings: Vec<String>,
}
impl Resolver for Ctx<'_> {
fn link(&mut self, href: &str) -> Option<String> {
if is_remote(href) {
return None;
}
let id = href.strip_prefix('#')?;
let ch = self.ids.get(id)?;
Some(format!("{ch}#{id}"))
}
fn image(&mut self, src: &str) -> Option<usize> {
if is_remote(src) {
self.warnings.push("a remote image was not loaded".into());
return None;
}
let id = src.strip_prefix('#')?.to_owned();
if let Some(r) = self.loaded.get(&id) {
return *r;
}
let r = (|| {
if self.images.len() >= self.limits.max_images {
return None;
}
let (_, b64) = self.binaries.get(&id)?;
let clean: String = b64.chars().filter(|c| !c.is_whitespace()).collect();
if clean.len() as u64 > self.limits.max_entry * 4 / 3 + 4 {
return None;
}
let bytes = base64::engine::general_purpose::STANDARD.decode(clean).ok()?;
let media_type = crate::epub::raster(&bytes)?;
let index = self.images.len();
self.images.push(Image { index, media_type, bytes });
Some(index)
})();
self.loaded.insert(id, r);
r
}
}
fn person(a: &XEl) -> Option<String> {
let part = |n: &str| a.child(n).map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty());
let name: Vec<String> = ["first-name", "middle-name", "last-name"].iter().filter_map(|n| part(n)).collect();
if name.is_empty() { part("nickname") } else { Some(name.join(" ")) }
}
fn metadata(root: &XEl) -> Metadata {
let mut m = Metadata::default();
let Some(desc) = root.child("description") else { return m };
if let Some(ti) = desc.child("title-info") {
m.title = ti.child("book-title").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty());
m.authors = ti.children_named("author").filter_map(person).collect();
m.language = ti.child("lang").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty());
m.subjects = ti.children_named("genre").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty()).collect();
m.description = ti.child("annotation").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty());
m.published = ti.child("date").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty());
if let Some(seq) = ti.child("sequence")
&& let Some(name) = seq.attr("name")
{
m.series = Some(Series {
name: name.trim().to_owned(),
index: seq.attr("number").and_then(|n| n.trim().parse().ok()),
});
}
}
if let Some(pi) = desc.child("publish-info") {
if let Some(isbn) = pi.child("isbn") {
m.identifiers.push(text::collapse(&isbn.text()));
}
m.publisher = pi.child("publisher").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty());
if m.published.is_none() {
m.published = pi.child("year").map(|e| text::collapse(&e.text())).filter(|s| !s.is_empty());
}
}
m
}
/// FB2 → XHTML vocabulary. `level` is the section depth (for heading levels).
fn convert(e: &XEl, level: usize) -> XEl {
let name = match e.local() {
"section" => "section",
"title" => ["h1", "h2", "h3", "h4", "h5", "h6"][(level + 1).min(5)],
"subtitle" => "h6",
"p" | "v" | "text-author" | "date" => "p",
"emphasis" => "em",
"strong" => "strong",
"strikethrough" => "s",
"sub" => "sub",
"sup" => "sup",
"code" => "code",
"empty-line" => "br",
"epigraph" | "cite" => "blockquote",
"poem" | "stanza" | "annotation" => "div",
"a" => "a",
"image" => "img",
"table" | "tr" | "td" | "th" => e.local(),
_ => "span",
};
let mut out = XEl::new(name);
for (k, v) in &e.attrs {
match xml::local(k) {
"id" => out.attrs.push(("id".into(), v.clone())),
"href" if name == "a" => out.attrs.push(("href".into(), v.clone())),
"href" if name == "img" => out.attrs.push(("src".into(), v.clone())),
"alt" | "title" | "colspan" | "rowspan" => out.attrs.push((xml::local(k).to_owned(), v.clone())),
_ => {}
}
}
let in_title = e.is("title");
let mut first = true;
for c in &e.children {
match c {
XNode::Text(t) => out.push_text(t),
XNode::El(child) => {
let next = if e.is("section") { level + 1 } else { level };
let mut conv = convert(child, next);
if in_title && child.is("p") {
conv.name = "span".into();
if !first {
out.children.push(XNode::El(XEl::new("br")));
}
first = false;
}
out.children.push(XNode::El(conv));
}
}
}
out
}
fn collect_ids(e: &XEl, chapter: usize, out: &mut HashMap<String, usize>) {
if let Some(id) = e.attr("id") {
out.entry(id.to_owned()).or_insert(chapter);
}
for d in e.descendants() {
if let Some(id) = d.attr("id") {
out.entry(id.to_owned()).or_insert(chapter);
}
}
}
pub(crate) fn open(bytes: &[u8], limits: &Limits) -> Result<Document> {
let s = text::decode_xml(bytes);
let root = xml::parse(&s, limits)?;
if !root.is("FictionBook") {
return Err(FormatError::Malformed("not a FictionBook document".into()));
}
let metadata = metadata(&root);
let mut binaries = HashMap::new();
for b in root.children_named("binary") {
if let Some(id) = b.attr("id") {
binaries.insert(id.to_owned(), ("", b.text()));
}
}
// Chapter sources: the main bodies' title pages and top-level sections, then the notes bodies.
let mut sources: Vec<(XEl, bool, bool)> = Vec::new(); // (converted chapter, linear, notes)
for body in root.children_named("body") {
let notes = matches!(body.attr("name"), Some("notes" | "comments"));
if notes {
sources.push((convert(body, 0), false, true));
continue;
}
let mut front = XEl::new("div");
let mut sections = Vec::new();
for c in body.elements() {
if c.is("section") {
sections.push(convert(c, 0));
} else {
front.children.push(XNode::El(convert(c, 0)));
}
}
let empty = front.children.is_empty();
if !empty {
sources.push((front, true, false));
}
if sections.is_empty() && empty {
sources.push((convert(body, 0), true, false));
}
for s in sections {
sources.push((s, true, false));
}
}
if sources.len() > limits.max_chapters {
return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters)));
}
let mut ids = HashMap::new();
for (i, (src, _, _)) in sources.iter().enumerate() {
collect_ids(src, i, &mut ids);
}
let mut ctx = Ctx { binaries, images: Vec::new(), loaded: HashMap::new(), ids, limits, warnings: Vec::new() };
let mut chapters = Vec::new();
let mut footnotes = BTreeMap::new();
let mut toc = Vec::new();
for (i, (src, linear, notes)) in sources.iter().enumerate() {
let mut wrap = XEl::new("body");
wrap.children.push(XNode::El(src.clone()));
let s = sanitize(&wrap, &mut ctx);
if *notes {
for sec in s.root.descendants() {
if sec.name == "section"
&& let Some(id) = sec.attr("id")
{
let mut w = crate::Element::new("div");
w.children = sec.children.clone();
footnotes.insert(format!("{i}#{id}"), crate::sanitize::serialize(&w));
}
}
}
let ch = crate::chapter(format!("chapter-{i}"), None, *linear, s.root);
if let Some(t) = &ch.title
&& *linear
{
toc.push(TocEntry { title: t.clone(), chapter: i, fragment: None, children: vec![] });
}
chapters.push(ch);
}
let cover = root
.child("description")
.and_then(|d| d.child("title-info"))
.and_then(|t| t.child("coverpage"))
.and_then(|c| c.child("image"))
.and_then(|i| i.attr("href").map(str::to_owned))
.and_then(|h| ctx.image(&h));
Ok(Document {
format: Format::Fb2,
metadata,
chapters,
toc,
footnotes,
images: ctx.images,
cover,
warnings: ctx.warnings,
})
}
+65
View File
@@ -0,0 +1,65 @@
//! Tag-soup HTML (MOBI text, XHTML that is not well-formed) through html5ever into the same owned tree as XML.
//! The walk is depth-capped: below `max_depth` only text is collected, iteratively.
use crate::xml::{XEl, XNode};
use crate::{FormatError, Limits, Result};
use html5ever::tendril::TendrilSink;
use markup5ever_rcdom::{Handle, NodeData, RcDom};
/// Parses an HTML document; returns its `<html>` element (html5ever always makes one).
pub(crate) fn parse(text: &str, limits: &Limits) -> Result<XEl> {
if text.len() > limits.max_text {
return Err(FormatError::TooLarge("the text is larger than the limit".into()));
}
let dom = html5ever::parse_document(RcDom::default(), Default::default()).one(text);
let mut doc = XEl::new("#document");
let kids: Vec<Handle> = dom.document.children.borrow().clone();
for k in kids {
convert(&k, &mut doc, 0, limits.max_depth);
}
doc.elements()
.find(|e| e.is("html"))
.cloned()
.ok_or_else(|| FormatError::Malformed("HTML without a document element".into()))
}
fn convert(h: &Handle, parent: &mut XEl, depth: usize, max: usize) {
match &h.data {
NodeData::Text { contents } => parent.push_text(&contents.borrow()),
NodeData::Element { name, attrs, .. } => {
if depth >= max {
parent.push_text(&text_of(h));
return;
}
let mut el = XEl::new(&name.local);
for a in attrs.borrow().iter() {
let key = match &a.name.prefix {
Some(p) => format!("{p}:{}", a.name.local),
None => a.name.local.to_string(),
};
el.attrs.push((key, a.value.to_string()));
}
let kids: Vec<Handle> = h.children.borrow().clone();
for k in &kids {
convert(k, &mut el, depth + 1, max);
}
parent.children.push(XNode::El(el));
}
_ => {}
}
}
fn text_of(h: &Handle) -> String {
let mut s = String::new();
let mut stack = vec![h.clone()];
while let Some(n) = stack.pop() {
match &n.data {
NodeData::Text { contents } => s.push_str(&contents.borrow()),
NodeData::Element { name, .. } if crate::sanitize::DROP.contains(&&*name.local) => continue,
_ => {}
}
let kids: Vec<Handle> = n.children.borrow().clone();
stack.extend(kids.into_iter().rev());
}
s
}
+278
View File
@@ -0,0 +1,278 @@
//! Liber's book formats (docs/FORMATS.md): EPUB 2/3, FB2, TXT and DRM-free MOBI/AZW3 in, one sanitized
//! [`Document`] out. Pure: bytes in, values out. No file system, no network, no clock.
//!
//! ```
//! let txt = "Chapter 1\n\nIt was a dark and stormy night.\n".as_bytes();
//! let doc = liber_format::open(txt, Some("storm.txt"), &liber_format::Limits::default()).unwrap();
//! assert_eq!(doc.format, liber_format::Format::Txt);
//! assert_eq!(doc.chapters.len(), 1);
//! ```
mod drm;
mod entities;
mod epub;
mod fb2;
mod html;
mod mobi;
pub mod position;
mod sanitize;
pub mod text;
mod txt;
mod xml;
pub mod zip;
pub use position::{Anchor, Point, Quote, Resolved};
pub use sanitize::{Element, Node};
use serde::Serialize;
use std::collections::BTreeMap;
/// The one sentence the app shows for a protected book.
pub const DRM_MESSAGE: &str = "This book is DRM-protected, so Liber cannot open it.";
/// What a file is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Format {
Epub,
Fb2,
Txt,
Mobi,
Azw3,
Pdf,
}
impl Format {
pub fn as_str(self) -> &'static str {
match self {
Format::Epub => "epub",
Format::Fb2 => "fb2",
Format::Txt => "txt",
Format::Mobi => "mobi",
Format::Azw3 => "azw3",
Format::Pdf => "pdf",
}
}
}
/// Why a book did not open. [`FormatError::message`] is the sentence for the person.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum FormatError {
#[error("DRM-protected")]
Drm,
/// A PDF: the app opens it read-only in its PDF view.
#[error("a PDF")]
Pdf,
#[error("unsupported: {0}")]
Unsupported(String),
#[error("too large: {0}")]
TooLarge(String),
/// Zip slip, symlinks, entity declarations: refused, never sanitized around.
#[error("unsafe: {0}")]
Unsafe(String),
#[error("malformed: {0}")]
Malformed(String),
}
impl FormatError {
pub fn message(&self) -> String {
match self {
FormatError::Drm => DRM_MESSAGE.to_owned(),
FormatError::Pdf => "This is a PDF: Liber opens it read-only.".to_owned(),
FormatError::Unsupported(w) => format!("Liber cannot open this book: {w}."),
FormatError::TooLarge(w) => format!("This book is too large to open safely: {w}."),
FormatError::Unsafe(w) => format!("Liber refused this file because it is unsafe: {w}."),
FormatError::Malformed(w) => format!("This book file is damaged: {w}."),
}
}
}
pub type Result<T> = std::result::Result<T, FormatError>;
/// Hard caps for one book. Every size read out of a file is checked against these before anything is allocated.
#[derive(Clone, Debug)]
pub struct Limits {
pub max_input: u64,
pub max_entries: usize,
pub max_entry: u64,
pub max_total: u64,
/// Inflated / compressed, for entries larger than 1 MiB.
pub max_ratio: u64,
pub max_xml: usize,
pub max_depth: usize,
pub max_chapters: usize,
pub max_images: usize,
pub max_text: usize,
}
impl Default for Limits {
fn default() -> Self {
const MIB: u64 = 1024 * 1024;
Limits {
max_input: 1024 * MIB,
max_entries: 10_000,
max_entry: 64 * MIB,
max_total: 512 * MIB,
max_ratio: 100,
max_xml: 32 * MIB as usize,
max_depth: 256,
max_chapters: 5_000,
max_images: 5_000,
max_text: 256 * MIB as usize,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Series {
pub name: String,
pub index: Option<f64>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize)]
pub struct Metadata {
pub title: Option<String>,
pub authors: Vec<String>,
pub language: Option<String>,
pub identifiers: Vec<String>,
/// The first valid ISBN among the identifiers, as ISBN-13.
pub isbn: Option<String>,
pub publisher: Option<String>,
pub published: Option<String>,
/// Plain text.
pub description: Option<String>,
pub subjects: Vec<String>,
pub series: Option<Series>,
}
/// One chapter: the sanitized tree and its serialization.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Chapter {
/// Stable within the book: the spine path (EPUB) or `chapter-<n>`.
pub href: String,
pub title: Option<String>,
pub linear: bool,
/// `<div xmlns="http://www.w3.org/1999/xhtml">…</div>`: insert with an XML parser, never `innerHTML`.
pub xhtml: String,
/// SHA-256 of `xhtml`, hex.
pub hash: String,
/// Length of the chapter's text in UTF-16 code units.
pub text_len: usize,
#[serde(skip)]
pub root: Element,
}
impl Chapter {
/// The chapter's text: every text node in document order, nothing added.
pub fn text(&self) -> String {
let mut s = String::new();
self.root.collect_text(&mut s);
s
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct TocEntry {
pub title: String,
pub chapter: usize,
pub fragment: Option<String>,
pub children: Vec<TocEntry>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Image {
pub index: usize,
pub media_type: &'static str,
#[serde(skip)]
pub bytes: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Document {
pub format: Format,
pub metadata: Metadata,
pub chapters: Vec<Chapter>,
pub toc: Vec<TocEntry>,
/// `"<chapter>#<id>"` → the note's sanitized XHTML, for the footnote popover.
pub footnotes: BTreeMap<String, String>,
pub images: Vec<Image>,
pub cover: Option<usize>,
/// Things dropped on the way (remote images, unreadable chapters), for the import report.
pub warnings: Vec<String>,
}
impl Document {
/// The book's text fingerprint (docs/FORMATS.md §6).
pub fn fingerprint(&self) -> String {
let mut all = String::new();
for c in &self.chapters {
c.root.collect_text(&mut all);
all.push(' ');
}
text::fingerprint(&all)
}
}
/// What the bytes are, by content (the name is only a hint for TXT and FB2).
pub fn sniff(bytes: &[u8], name: Option<&str>) -> Option<Format> {
if bytes.starts_with(b"%PDF-") {
return Some(Format::Pdf);
}
if bytes.len() >= 68 && &bytes[60..68] == b"BOOKMOBI" {
return Some(Format::Mobi);
}
if bytes.starts_with(b"PK\x03\x04") || bytes.starts_with(b"PK\x05\x06") {
let lower = name.map(|n| n.to_lowercase()).unwrap_or_default();
return Some(if lower.ends_with(".fb2.zip") || lower.ends_with(".fbz") { Format::Fb2 } else { Format::Epub });
}
let head = &bytes[..bytes.len().min(4096)];
if text::find(head, b"<FictionBook").is_some() {
return Some(Format::Fb2);
}
Some(Format::Txt)
}
/// Opens a book. `name` is the file name, used only as a hint (TXT title, `.fb2.zip`).
pub fn open(bytes: &[u8], name: Option<&str>, limits: &Limits) -> Result<Document> {
if bytes.len() as u64 > limits.max_input {
return Err(FormatError::TooLarge(format!("the file is larger than {} MiB", limits.max_input >> 20)));
}
drm::refuse_other_containers(bytes)?;
let mut doc = match sniff(bytes, name) {
Some(Format::Pdf) => return Err(FormatError::Pdf),
Some(Format::Mobi) => mobi::open(bytes, limits)?,
Some(Format::Epub) => {
let zip = zip::Zip::parse(bytes, limits)?;
if is_fb2_zip(&zip) { fb2::open_zip(&zip, limits)? } else { epub::open(&zip, limits)? }
}
Some(Format::Fb2) => {
if bytes.starts_with(b"PK") {
fb2::open_zip(&zip::Zip::parse(bytes, limits)?, limits)?
} else {
fb2::open(bytes, limits)?
}
}
_ => txt::open(bytes, name, limits)?,
};
if doc.chapters.is_empty() {
return Err(FormatError::Malformed("the book has no readable text".into()));
}
doc.metadata.isbn = doc.metadata.identifiers.iter().find_map(|i| text::isbn13(i));
Ok(doc)
}
fn is_fb2_zip(zip: &zip::Zip) -> bool {
zip.find("mimetype").is_none()
&& zip.find("META-INF/container.xml").is_none()
&& zip.entries().iter().filter(|e| !e.is_dir()).count() == 1
&& zip.entries().iter().any(|e| e.name.to_lowercase().ends_with(".fb2"))
}
/// Builds a chapter from its sanitized tree.
pub(crate) fn chapter(href: String, title: Option<String>, linear: bool, root: Element) -> Chapter {
let xhtml = sanitize::serialize(&root);
let hash = text::sha256_hex(xhtml.as_bytes());
let text_len = root.text_len_utf16();
let title = title.or_else(|| root.first_heading()).map(|t| text::collapse(&t)).filter(|t| !t.is_empty());
Chapter { href, title, linear, xhtml, hash, text_len, root }
}
+493
View File
@@ -0,0 +1,493 @@
//! DRM-free MOBI (6) and AZW3 (KF8): the PalmDB records, PalmDOC LZ77 and HUFF/CDIC decompression, the trailing
//! entries, EXTH metadata, images by record. Every offset and count read from the file is checked against it.
use crate::html;
use crate::sanitize::{Resolver, is_remote, sanitize};
use crate::xml::XEl;
use crate::{Document, Format, FormatError, Image, Limits, Metadata, Result, drm, text};
fn be16(d: &[u8], o: usize) -> Option<u16> {
Some(u16::from_be_bytes(d.get(o..o + 2)?.try_into().ok()?))
}
fn be32(d: &[u8], o: usize) -> Option<u32> {
Some(u32::from_be_bytes(d.get(o..o + 4)?.try_into().ok()?))
}
fn bad(w: &str) -> FormatError {
FormatError::Malformed(format!("the MOBI file is broken ({w})"))
}
/// The PalmDB's records, as slices.
fn records(d: &[u8]) -> Result<Vec<&[u8]>> {
let n = be16(d, 76).ok_or_else(|| bad("header"))? as usize;
if n == 0 || 78 + n * 8 > d.len() {
return Err(bad("record list"));
}
let mut offs = Vec::with_capacity(n);
for i in 0..n {
offs.push(be32(d, 78 + i * 8).ok_or_else(|| bad("record list"))? as usize);
}
let mut out = Vec::with_capacity(n);
for i in 0..n {
let start = offs[i];
let end = if i + 1 < n { offs[i + 1] } else { d.len() };
if start > end || end > d.len() {
return Err(bad("a record lies outside the file"));
}
out.push(&d[start..end]);
}
Ok(out)
}
/// PalmDOC LZ77, writing at most `cap` bytes.
pub(crate) fn palmdoc(data: &[u8], out: &mut Vec<u8>, cap: usize) -> Result<()> {
let start = out.len();
let mut i = 0;
while i < data.len() {
if out.len() - start > cap {
return Err(bad("a text record inflates past its size"));
}
let c = data[i];
i += 1;
match c {
0x00 | 0x09..=0x7f => out.push(c),
0x01..=0x08 => {
let n = c as usize;
let lit = data.get(i..i + n).ok_or_else(|| bad("a literal runs past the record"))?;
out.extend_from_slice(lit);
i += n;
}
0x80..=0xbf => {
let next = *data.get(i).ok_or_else(|| bad("a back-reference is cut off"))?;
i += 1;
let v = ((c as usize) << 8) | next as usize;
let dist = (v >> 3) & 0x7ff;
let len = (v & 7) + 3;
if dist == 0 || dist > out.len() - start {
return Err(bad("a back-reference points before the record"));
}
for _ in 0..len {
let b = out[out.len() - dist];
out.push(b);
}
}
_ => {
out.push(b' ');
out.push(c ^ 0x80);
}
}
}
Ok(())
}
/// HUFF/CDIC (calibre's `huffcdic.py`, rewritten with bounds).
struct Huff {
dict1: Vec<(u32, bool, u64)>,
mincode: [u64; 33],
maxcode: [u64; 33],
dict: Vec<(Vec<u8>, bool)>,
}
impl Huff {
fn new(huff: &[u8], cdics: &[&[u8]]) -> Result<Huff> {
if !huff.starts_with(b"HUFF") {
return Err(bad("the HUFF record"));
}
let off1 = be32(huff, 8).ok_or_else(|| bad("HUFF"))? as usize;
let off2 = be32(huff, 12).ok_or_else(|| bad("HUFF"))? as usize;
let mut dict1 = Vec::with_capacity(256);
for i in 0..256 {
let v = be32(huff, off1 + i * 4).ok_or_else(|| bad("HUFF table 1"))?;
let codelen = v & 0x1f;
let term = v & 0x80 != 0;
if codelen == 0 || (codelen <= 8 && !term) {
return Err(bad("HUFF table 1"));
}
let maxcode = (((v >> 8) as u64 + 1) << (32 - codelen)).wrapping_sub(1);
dict1.push((codelen, term, maxcode));
}
let mut mincode = [0u64; 33];
let mut maxcode = [0u64; 33];
for codelen in 1..=32usize {
let lo = be32(huff, off2 + (codelen - 1) * 8).ok_or_else(|| bad("HUFF table 2"))? as u64;
let hi = be32(huff, off2 + (codelen - 1) * 8 + 4).ok_or_else(|| bad("HUFF table 2"))? as u64;
mincode[codelen] = lo << (32 - codelen);
maxcode[codelen] = ((hi + 1) << (32 - codelen)).wrapping_sub(1);
}
let mut dict = Vec::new();
for c in cdics {
if !c.starts_with(b"CDIC") {
return Err(bad("a CDIC record"));
}
let phrases = be32(c, 8).ok_or_else(|| bad("CDIC"))? as usize;
let bits = be32(c, 12).ok_or_else(|| bad("CDIC"))?;
if bits > 24 {
return Err(bad("CDIC"));
}
let n = (1usize << bits).min(phrases.saturating_sub(dict.len()));
for i in 0..n {
let off = be16(c, 16 + i * 2).ok_or_else(|| bad("CDIC offsets"))? as usize;
let blen = be16(c, 16 + off).ok_or_else(|| bad("CDIC phrase"))? as usize;
let len = blen & 0x7fff;
let data = c.get(18 + off..18 + off + len).ok_or_else(|| bad("CDIC phrase"))?;
dict.push((data.to_vec(), blen & 0x8000 != 0));
}
}
Ok(Huff { dict1, mincode, maxcode, dict })
}
fn unpack(&mut self, data: &[u8], out: &mut Vec<u8>, depth: usize, cap: usize) -> Result<()> {
if depth > 32 {
return Err(bad("HUFF phrases nest too deep"));
}
let mut bitsleft = data.len() as i64 * 8;
let mut padded = data.to_vec();
padded.extend_from_slice(&[0; 8]);
let mut pos = 0usize;
let rd = |p: usize| u64::from_be_bytes(padded[p..p + 8].try_into().unwrap_or([0; 8]));
let mut x = rd(0);
let mut n: i64 = 32;
loop {
if out.len() > cap {
return Err(bad("HUFF output past its size"));
}
if n <= 0 {
pos += 4;
if pos + 8 > padded.len() {
break;
}
x = rd(pos);
n += 32;
}
let code = (x >> n) & 0xffff_ffff;
let (mut codelen, term, mut maxcode) = self.dict1[(code >> 24) as usize];
if !term {
while codelen < 32 && code < self.mincode[codelen as usize] {
codelen += 1;
}
maxcode = self.maxcode[codelen as usize];
}
n -= codelen as i64;
bitsleft -= codelen as i64;
if bitsleft < 0 {
break;
}
let r = (maxcode.wrapping_sub(code) >> (32 - codelen)) as usize;
let (slice, done) = self.dict.get(r).cloned().ok_or_else(|| bad("a HUFF code outside the dictionary"))?;
if done {
out.extend_from_slice(&slice);
} else {
// Mark as in progress, so a cycle fails instead of looping.
self.dict[r] = (Vec::new(), true);
let mut expanded = Vec::new();
self.unpack(&slice, &mut expanded, depth + 1, cap)?;
out.extend_from_slice(&expanded);
self.dict[r] = (expanded, true);
}
}
Ok(())
}
}
/// The trailing entries at the end of a text record (calibre's `getSizeOfTrailingDataEntries`).
fn trailing(rec: &[u8], flags: u16) -> usize {
let mut num = 0usize;
let mut f = flags >> 1;
while f != 0 {
if f & 1 != 0 && num < rec.len() {
let end = rec.len() - num;
let mut v = 0usize;
for &b in &rec[end.saturating_sub(4)..end] {
if b & 0x80 != 0 {
v = 0;
}
v = (v << 7) | (b & 0x7f) as usize;
}
num += v;
}
f >>= 1;
}
if flags & 1 != 0 && num < rec.len() {
num += (rec[rec.len() - num - 1] & 0x3) as usize + 1;
}
num.min(rec.len())
}
struct Exth {
entries: Vec<(u32, Vec<u8>)>,
}
impl Exth {
fn get(&self, t: u32) -> Option<String> {
self.entries.iter().find(|(k, _)| *k == t).map(|(_, v)| text::collapse(&String::from_utf8_lossy(v)))
}
fn all(&self, t: u32) -> Vec<String> {
self.entries.iter().filter(|(k, _)| *k == t).map(|(_, v)| text::collapse(&String::from_utf8_lossy(v))).collect()
}
fn u32(&self, t: u32) -> Option<u32> {
self.entries
.iter()
.find(|(k, v)| *k == t && v.len() == 4)
.map(|(_, v)| u32::from_be_bytes([v[0], v[1], v[2], v[3]]))
}
}
fn exth(r0: &[u8], header_len: usize) -> Exth {
let mut entries = Vec::new();
let flags = be32(r0, 0x80).unwrap_or(0);
let at = 16 + header_len;
if flags & 0x40 != 0 && r0.get(at..at + 4) == Some(b"EXTH") {
let count = be32(r0, at + 8).unwrap_or(0) as usize;
let mut p = at + 12;
for _ in 0..count.min(4096) {
let (Some(t), Some(len)) = (be32(r0, p), be32(r0, p + 4)) else { break };
let len = len as usize;
if len < 8 {
break;
}
match r0.get(p + 8..p + len) {
Some(v) => entries.push((t, v.to_vec())),
None => break,
}
p += len;
}
}
Exth { entries }
}
/// One MOBI section (a MOBI 6 file, or the KF8 half of a combined file) starting at record `base`.
struct Section<'a> {
recs: &'a [&'a [u8]],
base: usize,
exth: Exth,
version: u32,
encoding: u32,
title: Option<String>,
first_resource: usize,
}
fn section<'a>(recs: &'a [&'a [u8]], base: usize) -> Result<Section<'a>> {
let r0 = *recs.get(base).ok_or_else(|| bad("record 0"))?;
if r0.get(16..20) != Some(b"MOBI") {
return Err(bad("no MOBI header"));
}
drm::mobi(r0)?;
let header_len = be32(r0, 20).ok_or_else(|| bad("MOBI header"))? as usize;
let encoding = be32(r0, 28).unwrap_or(1252);
let version = be32(r0, 36).unwrap_or(6);
let name_off = be32(r0, 84).unwrap_or(0) as usize;
let name_len = be32(r0, 88).unwrap_or(0) as usize;
let title =
r0.get(name_off..name_off.saturating_add(name_len)).map(|b| decode(b, encoding)).filter(|s| !s.is_empty());
let first_resource = be32(r0, 0x6c).unwrap_or(u32::MAX) as usize;
Ok(Section { recs, base, exth: exth(r0, header_len), version, encoding, title, first_resource })
}
fn decode(b: &[u8], encoding: u32) -> String {
if encoding == 65001 {
String::from_utf8_lossy(b).into_owned()
} else {
encoding_rs::WINDOWS_1252.decode_without_bom_handling(b).0.into_owned()
}
}
fn text_of(s: &Section, limits: &Limits) -> Result<Vec<u8>> {
let r0 = s.recs[s.base];
let compression = be16(r0, 0).ok_or_else(|| bad("PalmDOC header"))?;
let text_len = be32(r0, 4).ok_or_else(|| bad("PalmDOC header"))? as usize;
let count = be16(r0, 8).ok_or_else(|| bad("PalmDOC header"))? as usize;
let header_len = be32(r0, 20).unwrap_or(0) as usize;
let flags = if header_len >= 0xe4 { be16(r0, 0xf2).unwrap_or(0) } else { 0 };
let cap = text_len.min(limits.max_text);
if s.base + count >= s.recs.len() {
return Err(bad("more text records than records"));
}
let mut out = Vec::with_capacity(cap.min(64 * 1024 * 1024));
let mut huff = if compression == 17480 {
let first = be32(r0, 0x70).ok_or_else(|| bad("HUFF index"))? as usize + s.base;
let n = be32(r0, 0x74).ok_or_else(|| bad("HUFF count"))? as usize;
if n == 0 || first + n > s.recs.len() {
return Err(bad("HUFF records outside the file"));
}
Some(Huff::new(s.recs[first], &s.recs[first + 1..first + n])?)
} else {
None
};
for i in 1..=count {
let rec = s.recs[s.base + i];
let rec = &rec[..rec.len() - trailing(rec, flags)];
let room = cap.saturating_sub(out.len()) + 8192;
match compression {
1 => out.extend_from_slice(&rec[..rec.len().min(room)]),
2 => palmdoc(rec, &mut out, room)?,
17480 => {
let start = out.len();
huff.as_mut().ok_or_else(|| bad("HUFF"))?.unpack(rec, &mut out, 0, start + room)?;
}
c => return Err(FormatError::Unsupported(format!("MOBI compression {c}"))),
}
if out.len() >= cap {
break;
}
}
out.truncate(cap);
Ok(out)
}
struct Ctx<'a> {
section: &'a Section<'a>,
images: Vec<Image>,
loaded: std::collections::HashMap<usize, Option<usize>>,
limits: &'a Limits,
}
impl Ctx<'_> {
fn resource(&mut self, n: usize) -> Option<usize> {
if let Some(r) = self.loaded.get(&n) {
return *r;
}
let r = (|| {
if n == 0 || self.images.len() >= self.limits.max_images || self.section.first_resource == u32::MAX as usize
{
return None;
}
let rec = *self.section.recs.get(self.section.base + self.section.first_resource + n - 1)?;
let media_type = crate::epub::raster(rec)?;
let index = self.images.len();
self.images.push(Image { index, media_type, bytes: rec.to_vec() });
Some(index)
})();
self.loaded.insert(n, r);
r
}
}
impl Resolver for Ctx<'_> {
fn link(&mut self, _href: &str) -> Option<String> {
// `filepos` and `kindle:pos` links are not mapped in v0.1 (docs/FORMATS.md §7): the text stays.
None
}
fn image(&mut self, src: &str) -> Option<usize> {
if let Some(rest) = src.strip_prefix("kindle:embed:") {
let digits: String = rest.chars().take_while(|c| c.is_ascii_alphanumeric()).collect();
let n = usize::from_str_radix(&digits, 32).ok()?;
return self.resource(n);
}
// MOBI 6: `recindex` arrives here as `recindex:<n>`.
if let Some(r) = src.strip_prefix("recindex:") {
let n: usize = r.trim_start_matches('0').parse().ok()?;
return self.resource(n);
}
if is_remote(src) {
return None;
}
None
}
}
/// MOBI 6 writes `<img recindex="00001">`; give it a `src` the resolver understands.
fn fix_recindex(e: &mut XEl) {
let mut stack: Vec<&mut XEl> = vec![e];
while let Some(el) = stack.pop() {
if el.is("img")
&& let Some(r) = el.attr("recindex").map(str::to_owned)
{
el.attrs.retain(|(k, _)| k != "src");
el.attrs.push(("src".into(), format!("recindex:{r}")));
}
for c in el.children.iter_mut() {
if let crate::xml::XNode::El(child) = c {
stack.push(child);
}
}
}
}
/// Splits the text into chapter-sized HTML pieces: KF8 at each new document, MOBI 6 at page breaks.
fn pieces(t: &str, kf8: bool) -> Vec<String> {
let lower = t.to_ascii_lowercase();
let marks: Vec<usize> = if kf8 {
lower.match_indices("<html").map(|(i, _)| i).collect()
} else {
lower.match_indices("<mbp:pagebreak").map(|(i, _)| i).collect()
};
let mut out = Vec::new();
let mut prev = 0;
for m in marks {
if m > prev {
out.push(t[prev..m].to_owned());
}
prev = m;
}
out.push(t[prev..].to_owned());
out.retain(|p| !p.trim().is_empty());
out
}
pub(crate) fn open(bytes: &[u8], limits: &Limits) -> Result<Document> {
let recs = records(bytes)?;
let first = section(&recs, 0)?;
// A combined file: EXTH 121 points at the KF8 half, which is preferred.
let kf8_base = first.exth.u32(121).map(|b| b as usize).filter(|&b| b > 0 && b < recs.len());
let sec = match kf8_base {
Some(b) => match section(&recs, b) {
Ok(s) => s,
Err(FormatError::Drm) => return Err(FormatError::Drm),
Err(_) => first,
},
None => first,
};
let kf8 = sec.version >= 8;
let raw = text_of(&sec, limits)?;
let t = decode(&raw, sec.encoding);
let mut md = Metadata {
title: sec.exth.get(503).or_else(|| sec.title.clone()),
authors: sec.exth.all(100),
publisher: sec.exth.get(101),
description: sec.exth.get(103).map(|d| crate::epub::plain(&d)),
subjects: sec.exth.all(105),
published: sec.exth.get(106),
language: sec.exth.get(524),
..Metadata::default()
};
md.identifiers = sec.exth.all(104);
let mut ctx = Ctx { section: &sec, images: Vec::new(), loaded: Default::default(), limits };
let parts = pieces(&t, kf8);
if parts.len() > limits.max_chapters {
return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters)));
}
let mut chapters = Vec::new();
let mut toc = Vec::new();
for (i, p) in parts.iter().enumerate() {
let mut doc = html::parse(p, limits)?;
fix_recindex(&mut doc);
let body = doc.child("body").cloned().unwrap_or(doc);
let s = sanitize(&body, &mut ctx);
let ch = crate::chapter(format!("chapter-{i}"), None, true, s.root);
if ch.text_len == 0 && ch.root.descendants().iter().all(|e| e.name != "img") {
continue;
}
if let Some(title) = &ch.title {
toc.push(crate::TocEntry {
title: title.clone(),
chapter: chapters.len(),
fragment: None,
children: vec![],
});
}
chapters.push(ch);
}
let cover = sec.exth.u32(201).and_then(|c| ctx.resource(c as usize + 1));
let images = ctx.images;
Ok(Document {
format: if kf8 { Format::Azw3 } else { Format::Mobi },
metadata: md,
chapters,
toc,
footnotes: Default::default(),
images,
cover,
warnings: vec![],
})
}
+312
View File
@@ -0,0 +1,312 @@
//! Positions (docs/FORMATS.md §5): CFI points over the sanitized chapter tree, and anchors that degrade to
//! "approximate" or "lost" instead of pointing at other text.
use crate::Document;
use crate::sanitize::{Element, Node};
use crate::text::{byte_at_utf16, utf16_len};
use serde::{Deserialize, Serialize};
const CONTEXT: usize = 32;
/// A point in a chapter: `epubcfi(/6/<2(chapter+1)>!/4<steps>:<offset>)`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Point {
pub chapter: usize,
pub steps: Vec<u32>,
/// UTF-16 code units into the text node.
pub offset: u32,
}
impl Point {
pub fn to_cfi(&self) -> String {
let mut s = format!("epubcfi(/6/{}!/4", 2 * (self.chapter + 1));
for st in &self.steps {
s.push_str(&format!("/{st}"));
}
s.push_str(&format!(":{})", self.offset));
s
}
pub fn parse(cfi: &str) -> Option<Point> {
let inner = cfi.trim().strip_prefix("epubcfi(")?.strip_suffix(')')?;
let (pkg, path) = inner.split_once('!')?;
let spine: u32 = pkg.strip_prefix("/6/")?.split('[').next()?.parse().ok()?;
if spine < 2 || !spine.is_multiple_of(2) {
return None;
}
let (path, offset) = match path.rsplit_once(':') {
Some((p, o)) => (p, o.parse().ok()?),
None => (path, 0),
};
let mut parts = path.split('/').skip(1);
if parts.next()?.split('[').next()? != "4" {
return None;
}
let mut steps = Vec::new();
for p in parts {
let n: u32 = p.split('[').next()?.parse().ok()?;
if n == 0 {
return None;
}
steps.push(n);
}
if steps.len() > 512 {
return None;
}
Some(Point { chapter: (spine / 2 - 1) as usize, steps, offset })
}
}
/// One text node: its CFI steps, where it starts in the chapter's text (UTF-16), and its text.
struct TextNode<'a> {
steps: Vec<u32>,
start: usize,
text: &'a str,
}
fn text_nodes(root: &Element) -> Vec<TextNode<'_>> {
fn walk<'a>(e: &'a Element, path: &mut Vec<u32>, at: &mut usize, out: &mut Vec<TextNode<'a>>) {
let mut k = 0u32;
for c in &e.children {
match c {
Node::Element(child) => {
k += 1;
path.push(2 * k);
walk(child, path, at, out);
path.pop();
}
Node::Text(t) => {
let mut steps = path.clone();
steps.push(2 * k + 1);
out.push(TextNode { steps, start: *at, text: t });
*at += utf16_len(t);
}
}
}
}
let mut out = Vec::new();
walk(root, &mut Vec::new(), &mut 0, &mut out);
out
}
/// The point at a UTF-16 offset into the chapter's text. At a boundary between two text nodes, `end` picks the
/// earlier node (the end of a range) and otherwise the later one (the start of a range).
pub fn point_at(chapter: usize, root: &Element, offset: usize, end: bool) -> Point {
let nodes = text_nodes(root);
let before = |n: &&TextNode| offset > n.start && offset <= n.start + utf16_len(n.text);
let after = |n: &&TextNode| offset >= n.start && offset < n.start + utf16_len(n.text);
let pick = if end {
nodes.iter().find(before).or_else(|| nodes.iter().find(after))
} else {
nodes.iter().find(after).or_else(|| nodes.iter().find(before))
}
.or_else(|| nodes.last());
match pick {
Some(n) => {
let len = utf16_len(n.text);
let o = offset.saturating_sub(n.start).min(len);
Point { chapter, steps: n.steps.clone(), offset: o as u32 }
}
None => Point { chapter, steps: vec![], offset: 0 },
}
}
/// The UTF-16 offset into the chapter's text that a point names, if it names one.
pub fn offset_of(root: &Element, p: &Point) -> Option<usize> {
let nodes = text_nodes(root);
if let Some(n) = nodes.iter().find(|n| n.steps == p.steps) {
let o = p.offset as usize;
return (o <= utf16_len(n.text)).then_some(n.start + o);
}
// A point on an element (an even last step): the start of its text.
if p.steps.last().is_some_and(|s| s % 2 == 0) && p.offset == 0 {
return nodes.iter().find(|n| n.steps.starts_with(&p.steps)).map(|n| n.start);
}
if p.steps.is_empty() && p.offset == 0 {
return Some(0);
}
None
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Quote {
pub exact: String,
pub prefix: String,
pub suffix: String,
}
/// What a highlight, note or bookmark stores about where it is.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Anchor {
pub chapter: usize,
pub start: String,
pub end: String,
pub chapter_hash: String,
pub quote: Quote,
}
/// Where an anchor is in a document. Offsets are UTF-16 into the chapter's text.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Resolved {
Exact { chapter: usize, start: usize, end: usize },
Approximate { chapter: usize, start: usize, end: usize },
Lost,
}
fn u16_of_byte(s: &str, b: usize) -> usize {
utf16_len(&s[..b])
}
fn tail_chars(s: &str, n: usize) -> String {
let v: Vec<char> = s.chars().collect();
v[v.len().saturating_sub(n)..].iter().collect()
}
fn head_chars(s: &str, n: usize) -> String {
s.chars().take(n).collect()
}
/// An anchor for `[start, end)` (UTF-16) in a chapter; `None` if the range is empty or outside the text.
pub fn anchor(doc: &Document, chapter: usize, start: usize, end: usize) -> Option<Anchor> {
let ch = doc.chapters.get(chapter)?;
let text = ch.text();
let (bs, be) = (byte_at_utf16(&text, start)?, byte_at_utf16(&text, end)?);
if bs >= be {
return None;
}
Some(Anchor {
chapter,
start: point_at(chapter, &ch.root, start, false).to_cfi(),
end: point_at(chapter, &ch.root, end, true).to_cfi(),
chapter_hash: ch.hash.clone(),
quote: Quote {
exact: text[bs..be].to_owned(),
prefix: tail_chars(&text[..bs], CONTEXT),
suffix: head_chars(&text[be..], CONTEXT),
},
})
}
fn common_suffix(a: &str, b: &str) -> usize {
a.chars().rev().zip(b.chars().rev()).take_while(|(x, y)| x == y).count()
}
fn common_prefix(a: &str, b: &str) -> usize {
a.chars().zip(b.chars()).take_while(|(x, y)| x == y).count()
}
/// Lowercased, whitespace runs to one space; with each output char's byte index in the input.
fn normalized(s: &str) -> (String, Vec<usize>) {
let mut out = String::new();
let mut map = Vec::new();
let mut space = false;
for (i, c) in s.char_indices() {
if c.is_whitespace() {
if !space {
out.push(' ');
map.push(i);
}
space = true;
} else {
space = false;
for l in c.to_lowercase() {
out.push(l);
map.push(i);
}
}
}
map.push(s.len());
(out, map)
}
pub fn resolve(doc: &Document, a: &Anchor) -> Resolved {
if a.quote.exact.is_empty() {
return Resolved::Lost;
}
if let Some(ch) = doc.chapters.get(a.chapter)
&& let (Some(ps), Some(pe)) = (Point::parse(&a.start), Point::parse(&a.end))
&& let (Some(s), Some(e)) = (offset_of(&ch.root, &ps), offset_of(&ch.root, &pe))
&& s < e
{
let text = ch.text();
if let (Some(bs), Some(be)) = (byte_at_utf16(&text, s), byte_at_utf16(&text, e)) {
let same = text[bs..be] == a.quote.exact;
if same && ch.hash == a.chapter_hash {
return Resolved::Exact { chapter: a.chapter, start: s, end: e };
}
if same
&& tail_chars(&text[..bs], CONTEXT) == a.quote.prefix
&& head_chars(&text[be..], CONTEXT) == a.quote.suffix
{
return Resolved::Exact { chapter: a.chapter, start: s, end: e };
}
}
}
// Search: the anchor's chapter first, then outwards.
let mut order: Vec<usize> = (0..doc.chapters.len()).collect();
order.sort_by_key(|&i| (i as i64 - a.chapter as i64).unsigned_abs());
for exact_pass in [true, false] {
for &ci in &order {
let text = doc.chapters[ci].text();
let hits = if exact_pass { find_exact(&text, &a.quote) } else { find_loose(&text, &a.quote) };
let mut hits: Vec<(usize, usize, usize)> = hits; // (score, byte start, byte end)
if hits.is_empty() {
continue;
}
hits.sort_by_key(|h| std::cmp::Reverse(h.0));
if hits.len() > 1 && hits[0].0 == hits[1].0 {
// Two equally good places: never guess.
return Resolved::Lost;
}
let (_, bs, be) = hits[0];
return Resolved::Approximate { chapter: ci, start: u16_of_byte(&text, bs), end: u16_of_byte(&text, be) };
}
}
Resolved::Lost
}
fn find_exact(text: &str, q: &Quote) -> Vec<(usize, usize, usize)> {
let mut out = Vec::new();
let mut from = 0;
while let Some(p) = text[from..].find(&q.exact) {
let bs = from + p;
let be = bs + q.exact.len();
let score = common_suffix(&text[..bs], &q.prefix) + common_prefix(&text[be..], &q.suffix);
out.push((score, bs, be));
if out.len() >= 1000 {
break;
}
from = bs + q.exact.chars().next().map_or(1, char::len_utf8);
}
out
}
fn find_loose(text: &str, q: &Quote) -> Vec<(usize, usize, usize)> {
let (nt, map) = normalized(text);
let (nq, _) = normalized(&q.exact);
let nq = nq.trim();
if nq.chars().count() < 8 {
return Vec::new();
}
let (np, _) = normalized(&q.prefix);
let (ns, _) = normalized(&q.suffix);
let mut out = Vec::new();
let mut from = 0;
while let Some(p) = nt[from..].find(nq) {
let s = from + p;
let e = s + nq.len();
let score = common_suffix(&nt[..s], &np) + common_prefix(&nt[e..], &ns);
// Map normalized byte offsets back to the original text.
let cs = nt[..s].chars().count();
let ce = nt[..e].chars().count();
if let (Some(&bs), Some(&be)) = (map.get(cs), map.get(ce)) {
out.push((score, bs, be));
}
if out.len() >= 1000 {
break;
}
from = s + nq.chars().next().map_or(1, char::len_utf8);
}
out
}
+348
View File
@@ -0,0 +1,348 @@
//! 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
}
+181
View File
@@ -0,0 +1,181 @@
//! Text helpers: decoding, hashing, the text fingerprint, ISBNs.
use sha2::{Digest, Sha256};
use unicode_normalization::UnicodeNormalization;
pub fn sha256_hex(bytes: &[u8]) -> String {
let d = Sha256::digest(bytes);
let mut s = String::with_capacity(64);
for b in d {
s.push_str(&format!("{b:02x}"));
}
s
}
/// SHA-256 of the text, NFKC-normalised, lowercased, letters and digits only (docs/FORMATS.md §6).
pub fn fingerprint(text: &str) -> String {
let mut h = Sha256::new();
let mut buf = [0u8; 4];
for c in text.nfkc() {
if c.is_alphanumeric() {
for l in c.to_lowercase() {
h.update(l.encode_utf8(&mut buf).as_bytes());
}
}
}
let d = h.finalize();
d.iter().map(|b| format!("{b:02x}")).collect()
}
/// The first position of `needle` in `hay`.
pub fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() || hay.len() < needle.len() {
return None;
}
hay.windows(needle.len()).position(|w| w == needle)
}
/// Whitespace runs to one space, trimmed.
pub fn collapse(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut space = false;
for c in s.chars() {
if c.is_whitespace() {
space = !out.is_empty();
} else {
if space {
out.push(' ');
space = false;
}
out.push(c);
}
}
out
}
pub fn utf16_len(s: &str) -> usize {
s.chars().map(char::len_utf16).sum()
}
/// The byte index in `s` of UTF-16 offset `u`, or `None` past the end or inside a surrogate pair.
pub fn byte_at_utf16(s: &str, u: usize) -> Option<usize> {
let mut n = 0;
for (i, c) in s.char_indices() {
if n == u {
return Some(i);
}
n += c.len_utf16();
if n > u {
return None;
}
}
(n == u).then_some(s.len())
}
/// Decodes a text file: BOM, then strict UTF-8, then detection with the Czech hint (Windows-1250 and friends).
/// Returns the text and the encoding's name.
pub fn decode_text(bytes: &[u8]) -> (String, &'static str) {
if let Some((enc, bom)) = encoding_rs::Encoding::for_bom(bytes) {
let (s, _) = enc.decode_without_bom_handling(&bytes[bom..]);
return (s.into_owned(), enc.name());
}
if let Ok(s) = std::str::from_utf8(bytes) {
return (s.to_owned(), "UTF-8");
}
let mut det = chardetng::EncodingDetector::new(chardetng::Iso2022JpDetection::Deny);
det.feed(bytes, true);
let enc = det.guess(Some(b"cz"), chardetng::Utf8Detection::Allow);
let (s, _) = enc.decode_without_bom_handling(bytes);
(s.into_owned(), enc.name())
}
/// Decodes an XML document: BOM, then the declaration's `encoding`, else UTF-8 (lossy).
pub fn decode_xml(bytes: &[u8]) -> String {
if let Some((enc, bom)) = encoding_rs::Encoding::for_bom(bytes) {
return enc.decode_without_bom_handling(&bytes[bom..]).0.into_owned();
}
let head = &bytes[..bytes.len().min(512)];
if head.starts_with(b"<?xml")
&& let Some(end) = find(head, b"?>")
{
let decl = String::from_utf8_lossy(&head[..end]).to_lowercase();
if let Some(p) = decl.find("encoding") {
let rest = &decl[p + 8..];
let rest = rest.trim_start().strip_prefix('=').unwrap_or(rest).trim_start();
let q = rest.chars().next().unwrap_or('"');
let label: String = rest.chars().skip(1).take_while(|&c| c != q).collect();
if let Some(enc) = encoding_rs::Encoding::for_label(label.trim().as_bytes())
&& enc != encoding_rs::UTF_8
{
return enc.decode_without_bom_handling(bytes).0.into_owned();
}
}
}
String::from_utf8_lossy(bytes).into_owned()
}
/// An ISBN-10 or ISBN-13 (with or without hyphens, `urn:isbn:` or `isbn:`), check digit verified, as ISBN-13.
pub fn isbn13(s: &str) -> Option<String> {
let s = s.trim();
let lower = s.to_lowercase();
let s = lower.strip_prefix("urn:isbn:").or_else(|| lower.strip_prefix("isbn:")).unwrap_or(&lower).trim();
let chars: Vec<char> = s.chars().filter(|c| !matches!(c, '-' | ' ')).collect();
if chars.len() == 13 && chars.iter().all(char::is_ascii_digit) {
let d: Vec<u32> = chars.iter().map(|c| c.to_digit(10).unwrap_or(0)).collect();
let sum: u32 = d[..12].iter().enumerate().map(|(i, v)| if i % 2 == 0 { *v } else { v * 3 }).sum();
let check = (10 - sum % 10) % 10;
if check == d[12] && (chars.starts_with(&['9', '7', '8']) || chars.starts_with(&['9', '7', '9'])) {
return Some(chars.iter().collect());
}
return None;
}
if chars.len() == 10
&& chars[..9].iter().all(char::is_ascii_digit)
&& (chars[9].is_ascii_digit() || chars[9] == 'x')
{
let sum: u32 = chars
.iter()
.enumerate()
.map(|(i, c)| (10 - i as u32) * if *c == 'x' { 10 } else { c.to_digit(10).unwrap_or(0) })
.sum();
if !sum.is_multiple_of(11) {
return None;
}
let body: String = std::iter::once("978".to_owned()).chain(chars[..9].iter().map(|c| c.to_string())).collect();
let d: Vec<u32> = body.chars().map(|c| c.to_digit(10).unwrap_or(0)).collect();
let sum: u32 = d.iter().enumerate().map(|(i, v)| if i % 2 == 0 { *v } else { v * 3 }).sum();
return Some(format!("{body}{}", (10 - sum % 10) % 10));
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn isbns() {
assert_eq!(isbn13("978-0-441-17271-9").as_deref(), Some("9780441172719"));
assert_eq!(isbn13("0441172717").as_deref(), Some("9780441172719"));
assert_eq!(isbn13("urn:isbn:080442957X").as_deref(), Some("9780804429573"));
assert_eq!(isbn13("9780441172718"), None);
assert_eq!(isbn13("urn:uuid:1234"), None);
}
#[test]
fn utf16() {
let s = "a😀b";
assert_eq!(utf16_len(s), 4);
assert_eq!(byte_at_utf16(s, 3), Some(5));
assert_eq!(byte_at_utf16(s, 2), None);
assert_eq!(byte_at_utf16(s, 4), Some(6));
}
#[test]
fn windows_1250() {
let (enc_bytes, _, _) =
encoding_rs::WINDOWS_1250.encode("Příliš žluťoučký kůň úpěl ďábelské ódy. Šťastný Řehoř.");
let (s, name) = decode_text(&enc_bytes);
assert!(s.starts_with("Příliš žluťoučký"), "{s} ({name})");
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Plain text: encoding detection, paragraphs, chapters by heading lines or by size.
use crate::sanitize::Element;
use crate::{Document, Format, FormatError, Limits, Metadata, Result, TocEntry, text};
const CHUNK: usize = 40_000;
fn roman(s: &str) -> bool {
let s = s.trim_end_matches('.');
!s.is_empty() && s.len() <= 8 && s.chars().all(|c| matches!(c, 'I' | 'V' | 'X' | 'L' | 'C'))
}
/// A heading line: `Chapter 3`, `KAPITOLA III.`, `Kapitel 3`, a lone Roman numeral or number.
pub(crate) fn heading(p: &str) -> bool {
let p = p.trim();
if p.is_empty() || p.chars().count() > 80 || p.contains('\n') {
return false;
}
if roman(p)
|| (p.trim_end_matches('.').len() <= 3
&& p.trim_end_matches('.').chars().all(|c| c.is_ascii_digit())
&& !p.is_empty())
{
return true;
}
const NUMBERS: &[&str] = &[
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "first",
"second", "third", "last", "první", "druhá", "třetí", "eins", "zwei", "drei",
];
let lower = p.to_lowercase();
for w in ["chapter", "kapitola", "kapitel", "část", "part", "book", "kniha", "buch", "teil"] {
if let Some(rest) = lower.strip_prefix(w)
&& rest.starts_with(' ')
{
let next = rest.split_whitespace().next().unwrap_or("").trim_end_matches(['.', ':']);
return (!next.is_empty() && next.chars().all(|c| c.is_ascii_digit()))
|| roman(&next.to_uppercase())
|| NUMBERS.contains(&next);
}
}
["prologue", "epilogue", "prolog", "epilog"].iter().any(|w| lower == *w || lower.starts_with(&format!("{w}:")))
}
pub(crate) fn open(bytes: &[u8], name: Option<&str>, limits: &Limits) -> Result<Document> {
let (raw, _enc) = text::decode_text(bytes);
if raw.len() > limits.max_text {
return Err(FormatError::TooLarge("the text is larger than the limit".into()));
}
if raw.chars().take(4096).filter(|c| *c == '\u{0}').count() > 16 {
return Err(FormatError::Unsupported("this does not look like a book (binary data)".into()));
}
let s = raw.replace("\r\n", "\n").replace('\r', "\n");
let blank_separated = s.contains("\n\n");
let paras: Vec<String> = if blank_separated {
s.split("\n\n")
.map(|p| p.lines().map(str::trim).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" "))
.collect()
} else {
s.lines().map(|l| l.trim().to_owned()).collect()
};
let paras: Vec<String> = paras.into_iter().filter(|p| !p.is_empty()).collect();
let mut meta = Metadata::default();
// Project Gutenberg's header.
for line in s.lines().take(100) {
if let Some(t) = line.strip_prefix("Title:") {
meta.title.get_or_insert_with(|| text::collapse(t));
} else if let Some(a) = line.strip_prefix("Author:") {
if meta.authors.is_empty() {
meta.authors.push(text::collapse(a));
}
} else if let Some(l) = line.strip_prefix("Language:") {
meta.language.get_or_insert_with(|| text::collapse(l));
}
}
if meta.title.is_none() {
meta.title = name.map(|n| {
let base = n.rsplit(['/', '\\']).next().unwrap_or(n);
base.rsplit_once('.').map_or(base, |(b, _)| b).replace('_', " ")
});
}
// Chapters: at heading lines; else by size.
let mut groups: Vec<(Option<String>, Vec<String>)> = Vec::new();
let has_headings = paras.iter().filter(|p| heading(p)).count() >= 2;
for p in paras {
if has_headings && heading(&p) {
groups.push((Some(p), Vec::new()));
continue;
}
let size: usize = groups.last().map_or(0, |g| g.1.iter().map(String::len).sum());
if groups.is_empty() || (!has_headings && size > CHUNK) {
groups.push((None, Vec::new()));
}
if let Some(g) = groups.last_mut() {
g.1.push(p);
}
}
if groups.len() > limits.max_chapters {
return Err(FormatError::TooLarge(format!("more than {} chapters", limits.max_chapters)));
}
let mut chapters = Vec::new();
let mut toc = Vec::new();
for (i, (title, ps)) in groups.into_iter().enumerate() {
let mut root = Element::new("div");
if let Some(t) = &title {
let mut h = Element::new("h2");
h.push_text(t);
root.push(h);
toc.push(TocEntry { title: text::collapse(t), chapter: i, fragment: None, children: vec![] });
}
for p in ps {
let mut e = Element::new("p");
e.push_text(&p);
root.push(e);
}
chapters.push(crate::chapter(format!("chapter-{i}"), title, true, root));
}
Ok(Document {
format: Format::Txt,
metadata: meta,
chapters,
toc,
footnotes: Default::default(),
images: vec![],
cover: None,
warnings: vec![],
})
}
+220
View File
@@ -0,0 +1,220 @@
//! A small owned XML tree over quick-xml, for OPF, NCX, nav, FB2 and well-formed XHTML. Entity declarations are
//! refused; only XML's and HTML's named entities and numeric references resolve; depth is capped while building,
//! with an explicit stack, so no input recurses.
use crate::{FormatError, Limits, Result, entities};
use quick_xml::XmlVersion;
use quick_xml::events::{BytesStart, Event};
#[derive(Clone, Debug)]
pub(crate) enum XNode {
El(XEl),
Text(String),
}
#[derive(Clone, Debug, Default)]
pub(crate) struct XEl {
/// The qualified name as written (`dc:title`).
pub name: String,
pub attrs: Vec<(String, String)>,
pub children: Vec<XNode>,
}
pub(crate) fn local(q: &str) -> &str {
q.rsplit(':').next().unwrap_or(q)
}
impl XEl {
pub fn new(name: &str) -> XEl {
XEl { name: name.to_owned(), ..XEl::default() }
}
pub fn local(&self) -> &str {
local(&self.name)
}
pub fn is(&self, l: &str) -> bool {
self.local().eq_ignore_ascii_case(l)
}
/// An attribute by exact qualified name, else by local name.
pub fn attr(&self, name: &str) -> Option<&str> {
self.attrs
.iter()
.find(|(k, _)| k == name)
.or_else(|| self.attrs.iter().find(|(k, _)| local(k).eq_ignore_ascii_case(local(name))))
.map(|(_, v)| v.as_str())
}
pub fn elements(&self) -> impl Iterator<Item = &XEl> {
self.children.iter().filter_map(|c| if let XNode::El(e) = c { Some(e) } else { None })
}
pub fn child(&self, l: &str) -> Option<&XEl> {
self.elements().find(|e| e.is(l))
}
pub fn children_named<'s>(&'s self, l: &'s str) -> impl Iterator<Item = &'s XEl> + 's {
self.elements().filter(move |e| e.is(l))
}
/// Every descendant element in document order (iterative).
pub fn descendants(&self) -> Vec<&XEl> {
let mut out = Vec::new();
let mut stack: Vec<&XEl> = self.elements().collect::<Vec<_>>().into_iter().rev().collect();
while let Some(e) = stack.pop() {
out.push(e);
let kids: Vec<&XEl> = e.elements().collect();
stack.extend(kids.into_iter().rev());
}
out
}
pub fn find(&self, l: &str) -> Option<&XEl> {
self.descendants().into_iter().find(|e| e.is(l))
}
/// All text below, in order (iterative).
pub fn text(&self) -> String {
let mut s = String::new();
let mut stack: Vec<&XNode> = self.children.iter().rev().collect();
while let Some(n) = stack.pop() {
match n {
XNode::Text(t) => s.push_str(t),
XNode::El(e) => stack.extend(e.children.iter().rev()),
}
}
s
}
pub fn push_text(&mut self, t: &str) {
if t.is_empty() {
return;
}
if let Some(XNode::Text(last)) = self.children.last_mut() {
last.push_str(t);
} else {
self.children.push(XNode::Text(t.to_owned()));
}
}
}
fn element(e: &BytesStart) -> XEl {
let name = e.name().as_ref().to_owned();
let mut attrs = Vec::new();
for a in e.attributes().with_checks(false).flatten() {
let key = a.key.as_ref().to_owned();
let value = match a.normalized_value_with(XmlVersion::Implicit1_0, 16, entities::resolve) {
Ok(v) => v.into_owned(),
Err(_) => a.value.to_string(),
};
attrs.push((key, value));
}
XEl { name, attrs, children: Vec::new() }
}
/// Parses a whole document and returns its root element.
pub(crate) fn parse(s: &str, limits: &Limits) -> Result<XEl> {
if s.len() > limits.max_xml {
return Err(FormatError::TooLarge(format!("an XML document over {} MiB", limits.max_xml >> 20)));
}
let mut r = quick_xml::Reader::from_str(s);
{
let c = r.config_mut();
c.check_end_names = true;
c.trim_text(false);
}
let mut stack: Vec<XEl> = Vec::new();
let mut skip = 0usize;
let mut root: Option<XEl> = None;
loop {
let ev =
r.read_event().map_err(|e| FormatError::Malformed(format!("XML at byte {}: {e}", r.buffer_position())))?;
match ev {
Event::Eof => break,
Event::DocType(t) => {
let d = t.xml10_content().to_ascii_lowercase();
if d.contains("<!entity") {
return Err(FormatError::Unsafe("the book declares XML entities".into()));
}
}
Event::Start(e) => {
if root.is_some() {
return Err(FormatError::Malformed("XML: content after the root element".into()));
}
if skip > 0 || stack.len() >= limits.max_depth {
skip += 1;
} else {
stack.push(element(&e));
}
}
Event::Empty(e) => {
if skip == 0 && stack.len() < limits.max_depth {
let el = element(&e);
match stack.last_mut() {
Some(top) => top.children.push(XNode::El(el)),
None if root.is_none() => root = Some(el),
None => return Err(FormatError::Malformed("XML: two root elements".into())),
}
}
}
Event::End(_) => {
if skip > 0 {
skip -= 1;
} else if let Some(done) = stack.pop() {
match stack.last_mut() {
Some(top) => top.children.push(XNode::El(done)),
None => root = Some(done),
}
}
}
Event::Text(t) => {
if let Some(top) = stack.last_mut() {
top.push_text(&t.xml10_content());
}
}
Event::CData(t) => {
if let Some(top) = stack.last_mut() {
top.push_text(&t.xml10_content());
}
}
Event::GeneralRef(g) => {
if let Some(top) = stack.last_mut() {
let resolved: String = if g.is_char_ref() {
match g.resolve_char_ref() {
Ok(Some(c)) => c.to_string(),
_ => String::new(),
}
} else {
let name = g.xml10_content();
match entities::resolve(&name) {
Some(v) => v.to_owned(),
None => format!("&{name};"),
}
};
top.push_text(&resolved);
}
}
_ => {}
}
}
if !stack.is_empty() {
return Err(FormatError::Malformed("XML: the document ends inside an element".into()));
}
root.ok_or_else(|| FormatError::Malformed("XML: no root element".into()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn entities_and_depth() {
let l = Limits { max_depth: 3, ..Limits::default() };
let root = parse("<a>x&amp;&nbsp;&#x41;&unknown;<b><c><d>deep</d></c></b></a>", &l).unwrap();
assert_eq!(root.text(), "x&\u{a0}A&unknown;deep");
assert!(root.find("d").is_none());
let err = parse("<!DOCTYPE a [<!ENTITY x SYSTEM \"file:///etc/passwd\">]><a>&x;</a>", &l).unwrap_err();
assert!(matches!(err, FormatError::Unsafe(_)));
}
}
+361
View File
@@ -0,0 +1,361 @@
//! A small zip reader and writer, written for hostile input (docs/FORMATS.md §3): the central directory is checked
//! entry by entry before anything is read, names are refused rather than cleaned, and inflation stops at a cap that
//! never trusts the sizes the archive declares. Stored and deflate only; no ZIP64, no encryption.
use crate::{FormatError, Limits, Result};
use std::cell::Cell;
use std::io::{self, Read, Write};
const EOCD: u32 = 0x0605_4b50;
const CENTRAL: u32 = 0x0201_4b50;
const LOCAL: u32 = 0x0403_4b50;
const DESCRIPTOR: u32 = 0x0807_4b50;
const MIB: u64 = 1024 * 1024;
#[derive(Clone, Debug)]
pub struct Entry {
pub name: String,
method: u16,
crc: u32,
csize: u64,
usize: u64,
local: u64,
}
impl Entry {
pub fn is_dir(&self) -> bool {
self.name.ends_with('/')
}
/// The size the archive declares (never trusted for allocation).
pub fn declared_size(&self) -> u64 {
self.usize
}
}
/// A parsed archive over borrowed bytes.
pub struct Zip<'a> {
data: &'a [u8],
entries: Vec<Entry>,
limits: Limits,
inflated: Cell<u64>,
}
fn u16_at(d: &[u8], o: usize) -> Option<u16> {
Some(u16::from_le_bytes(d.get(o..o + 2)?.try_into().ok()?))
}
fn u32_at(d: &[u8], o: usize) -> Option<u32> {
Some(u32::from_le_bytes(d.get(o..o + 4)?.try_into().ok()?))
}
fn bad(w: &str) -> FormatError {
FormatError::Malformed(format!("the archive is broken ({w})"))
}
/// Whether a name may appear in an archive Liber reads: relative, no `..`, no backslash, no drive, no controls.
pub fn safe_name(name: &str) -> bool {
if name.is_empty() || name.len() > 1024 {
return false;
}
if name.starts_with('/') || name.contains('\\') || name.chars().any(|c| c.is_control()) {
return false;
}
let b = name.as_bytes();
if b.len() >= 2 && b[1] == b':' {
return false;
}
!name.split('/').any(|seg| seg == "..")
}
impl<'a> Zip<'a> {
pub fn parse(data: &'a [u8], limits: &Limits) -> Result<Zip<'a>> {
if data.len() < 22 {
return Err(bad("too short"));
}
let from = data.len().saturating_sub(22 + 65_535);
let eocd = (from..=data.len() - 22)
.rev()
.find(|&i| u32_at(data, i) == Some(EOCD))
.ok_or_else(|| bad("no end of central directory: the file is truncated or not a zip"))?;
let count = u16_at(data, eocd + 10).ok_or_else(|| bad("eocd"))? as usize;
let cd_size = u32_at(data, eocd + 12).ok_or_else(|| bad("eocd"))? as u64;
let cd_off = u32_at(data, eocd + 16).ok_or_else(|| bad("eocd"))? as u64;
if count == 0xFFFF || cd_size == 0xFFFF_FFFF || cd_off == 0xFFFF_FFFF {
return Err(FormatError::Unsupported("ZIP64 archives".into()));
}
if u16_at(data, eocd + 4) != Some(0) || u16_at(data, eocd + 6) != Some(0) {
return Err(FormatError::Unsupported("multi-part archives".into()));
}
if count > limits.max_entries {
return Err(FormatError::TooLarge(format!("more than {} files in the archive", limits.max_entries)));
}
if cd_off + cd_size > eocd as u64 {
return Err(bad("the central directory points past its end"));
}
let mut entries = Vec::with_capacity(count);
let mut p = cd_off as usize;
for _ in 0..count {
if u32_at(data, p) != Some(CENTRAL) {
return Err(bad("a central directory entry"));
}
let made_by = u16_at(data, p + 4).ok_or_else(|| bad("entry"))?;
let flags = u16_at(data, p + 8).ok_or_else(|| bad("entry"))?;
let method = u16_at(data, p + 10).ok_or_else(|| bad("entry"))?;
let crc = u32_at(data, p + 16).ok_or_else(|| bad("entry"))?;
let csize = u32_at(data, p + 20).ok_or_else(|| bad("entry"))? as u64;
let usize = u32_at(data, p + 24).ok_or_else(|| bad("entry"))? as u64;
let nlen = u16_at(data, p + 28).ok_or_else(|| bad("entry"))? as usize;
let elen = u16_at(data, p + 30).ok_or_else(|| bad("entry"))? as usize;
let clen = u16_at(data, p + 32).ok_or_else(|| bad("entry"))? as usize;
let external = u32_at(data, p + 38).ok_or_else(|| bad("entry"))?;
let local = u32_at(data, p + 42).ok_or_else(|| bad("entry"))? as u64;
let raw = data.get(p + 46..p + 46 + nlen).ok_or_else(|| bad("an entry name"))?;
let name = String::from_utf8_lossy(raw).into_owned();
if !safe_name(&name) {
return Err(FormatError::Unsafe(format!("the archive contains the path {name:?}")));
}
if made_by >> 8 == 3 && (external >> 16) & 0o170000 == 0o120000 {
return Err(FormatError::Unsafe(format!("the archive contains a symbolic link ({name})")));
}
if flags & 1 != 0 {
return Err(FormatError::Unsupported("password-protected archives".into()));
}
if csize == 0xFFFF_FFFF || usize == 0xFFFF_FFFF || local == 0xFFFF_FFFF {
return Err(FormatError::Unsupported("ZIP64 archives".into()));
}
if local + 30 > data.len() as u64 || local + csize > data.len() as u64 {
return Err(bad("an entry points past the end: the file is truncated"));
}
entries.push(Entry { name, method, crc, csize, usize, local });
p += 46 + nlen + elen + clen;
}
Ok(Zip { data, entries, limits: limits.clone(), inflated: Cell::new(0) })
}
pub fn entries(&self) -> &[Entry] {
&self.entries
}
/// An entry by exact name, else ignoring ASCII case.
pub fn find(&self, name: &str) -> Option<&Entry> {
self.entries
.iter()
.find(|e| e.name == name)
.or_else(|| self.entries.iter().find(|e| e.name.eq_ignore_ascii_case(name)))
}
/// Reads one entry, inflating at most up to the caps.
pub fn read(&self, e: &Entry) -> Result<Vec<u8>> {
self.read_capped(e, u64::MAX)
}
/// Reads one entry with an extra cap for this kind of file (an XML document: `max_xml`).
pub fn read_capped(&self, e: &Entry, extra: u64) -> Result<Vec<u8>> {
let d = self.data;
let l = e.local as usize;
if u32_at(d, l) != Some(LOCAL) {
return Err(bad("a local header"));
}
let nlen = u16_at(d, l + 26).ok_or_else(|| bad("local"))? as usize;
let elen = u16_at(d, l + 28).ok_or_else(|| bad("local"))? as usize;
let start = l + 30 + nlen + elen;
let body = d.get(start..start + e.csize as usize).ok_or_else(|| bad("an entry is cut off"))?;
let used = self.inflated.get();
let left = self.limits.max_total.saturating_sub(used);
let mut cap = self.limits.max_entry.min(left).min(extra);
if e.csize > 0 {
cap = cap.min((e.csize.saturating_mul(self.limits.max_ratio)).max(MIB));
}
let out = match e.method {
0 => {
if body.len() as u64 > cap {
return Err(FormatError::TooLarge(format!("{} is larger than the limit", e.name)));
}
body.to_vec()
}
8 => miniz_oxide::inflate::decompress_to_vec_with_limit(body, cap as usize).map_err(|err| {
if err.status == miniz_oxide::inflate::TINFLStatus::HasMoreOutput {
FormatError::TooLarge(format!(
"{} inflates beyond the limit (a zip bomb, or a book over the size cap)",
e.name
))
} else {
bad(&format!("{} does not inflate", e.name))
}
})?,
m => return Err(FormatError::Unsupported(format!("compression method {m}"))),
};
if crc32fast::hash(&out) != e.crc {
return Err(bad(&format!("{} fails its checksum", e.name)));
}
self.inflated.set(used + out.len() as u64);
Ok(out)
}
pub fn read_name(&self, name: &str) -> Result<Option<Vec<u8>>> {
self.read_name_capped(name, u64::MAX)
}
pub fn read_name_capped(&self, name: &str, extra: u64) -> Result<Option<Vec<u8>>> {
match self.find(name) {
Some(e) => self.read_capped(e, extra).map(Some),
None => Ok(None),
}
}
}
/// A streaming zip writer: deflated in-memory entries, and stored streams with a data descriptor (no seeking).
pub struct ZipWriter<W: Write> {
w: W,
at: u64,
central: Vec<u8>,
count: u16,
}
impl<W: Write> ZipWriter<W> {
pub fn new(w: W) -> ZipWriter<W> {
ZipWriter { w, at: 0, central: Vec::new(), count: 0 }
}
fn put(&mut self, b: &[u8]) -> io::Result<()> {
self.w.write_all(b)?;
self.at += b.len() as u64;
Ok(())
}
fn check(&self, name: &str) -> io::Result<()> {
if !safe_name(name) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsafe name {name:?}")));
}
if self.count == u16::MAX - 1 {
return Err(io::Error::other("too many entries for a zip without ZIP64"));
}
Ok(())
}
fn header(&mut self, name: &str, flags: u16, method: u16, crc: u32, csize: u32, usize: u32) -> io::Result<u32> {
let off = u32::try_from(self.at).map_err(|_| io::Error::other("the archive passed 4 GiB"))?;
let mut h = Vec::with_capacity(30 + name.len());
h.extend_from_slice(&LOCAL.to_le_bytes());
h.extend_from_slice(&20u16.to_le_bytes());
h.extend_from_slice(&(flags | 0x0800).to_le_bytes());
h.extend_from_slice(&method.to_le_bytes());
h.extend_from_slice(&0u16.to_le_bytes()); // time
h.extend_from_slice(&0x21u16.to_le_bytes()); // date 1980-01-01
h.extend_from_slice(&crc.to_le_bytes());
h.extend_from_slice(&csize.to_le_bytes());
h.extend_from_slice(&usize.to_le_bytes());
h.extend_from_slice(&(name.len() as u16).to_le_bytes());
h.extend_from_slice(&0u16.to_le_bytes());
h.extend_from_slice(name.as_bytes());
self.put(&h)?;
Ok(off)
}
#[allow(clippy::too_many_arguments)]
fn record(&mut self, name: &str, flags: u16, method: u16, crc: u32, csize: u32, usize: u32, off: u32) {
let c = &mut self.central;
c.extend_from_slice(&CENTRAL.to_le_bytes());
c.extend_from_slice(&0x0314u16.to_le_bytes()); // made by Unix, 2.0
c.extend_from_slice(&20u16.to_le_bytes());
c.extend_from_slice(&(flags | 0x0800).to_le_bytes());
c.extend_from_slice(&method.to_le_bytes());
c.extend_from_slice(&0u16.to_le_bytes());
c.extend_from_slice(&0x21u16.to_le_bytes());
c.extend_from_slice(&crc.to_le_bytes());
c.extend_from_slice(&csize.to_le_bytes());
c.extend_from_slice(&usize.to_le_bytes());
c.extend_from_slice(&(name.len() as u16).to_le_bytes());
c.extend_from_slice(&[0; 8]); // extra, comment, disk, internal
c.extend_from_slice(&(0o100644u32 << 16).to_le_bytes());
c.extend_from_slice(&off.to_le_bytes());
c.extend_from_slice(name.as_bytes());
self.count += 1;
}
/// Adds an in-memory file; `deflate` compresses it.
pub fn add(&mut self, name: &str, data: &[u8], deflate: bool) -> io::Result<()> {
self.check(name)?;
let crc = crc32fast::hash(data);
let usize = u32::try_from(data.len()).map_err(|_| io::Error::other("an entry over 4 GiB"))?;
let (method, body) =
if deflate { (8, miniz_oxide::deflate::compress_to_vec(data, 6)) } else { (0, data.to_vec()) };
let csize = u32::try_from(body.len()).map_err(|_| io::Error::other("an entry over 4 GiB"))?;
let off = self.header(name, 0, method, crc, csize, usize)?;
self.put(&body)?;
self.record(name, 0, method, crc, csize, usize, off);
Ok(())
}
/// Adds a file streamed from `r`, stored (book files are compressed already), with a data descriptor.
pub fn add_stream(&mut self, name: &str, r: &mut dyn Read) -> io::Result<()> {
self.check(name)?;
let off = self.header(name, 0x0008, 0, 0, 0, 0)?;
let mut hasher = crc32fast::Hasher::new();
let mut n: u64 = 0;
let mut buf = vec![0u8; 64 * 1024];
loop {
let k = r.read(&mut buf)?;
if k == 0 {
break;
}
hasher.update(&buf[..k]);
self.put(&buf[..k])?;
n += k as u64;
}
let size = u32::try_from(n).map_err(|_| io::Error::other("an entry over 4 GiB"))?;
let crc = hasher.finalize();
let mut d = Vec::with_capacity(16);
d.extend_from_slice(&DESCRIPTOR.to_le_bytes());
d.extend_from_slice(&crc.to_le_bytes());
d.extend_from_slice(&size.to_le_bytes());
d.extend_from_slice(&size.to_le_bytes());
self.put(&d)?;
self.record(name, 0x0008, 0, crc, size, size, off);
Ok(())
}
pub fn finish(mut self) -> io::Result<W> {
let cd_off = u32::try_from(self.at).map_err(|_| io::Error::other("the archive passed 4 GiB"))?;
let central = std::mem::take(&mut self.central);
self.put(&central)?;
let mut e = Vec::with_capacity(22);
e.extend_from_slice(&EOCD.to_le_bytes());
e.extend_from_slice(&[0; 4]);
e.extend_from_slice(&self.count.to_le_bytes());
e.extend_from_slice(&self.count.to_le_bytes());
e.extend_from_slice(&(central.len() as u32).to_le_bytes());
e.extend_from_slice(&cd_off.to_le_bytes());
e.extend_from_slice(&0u16.to_le_bytes());
self.put(&e)?;
self.w.flush()?;
Ok(self.w)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip() {
let mut w = ZipWriter::new(Vec::new());
w.add("mimetype", b"application/epub+zip", false).unwrap();
w.add("a/b.txt", "žluťoučký kůň".repeat(100).as_bytes(), true).unwrap();
w.add_stream("c.bin", &mut &b"streamed"[..]).unwrap();
let bytes = w.finish().unwrap();
let z = Zip::parse(&bytes, &Limits::default()).unwrap();
assert_eq!(z.entries().len(), 3);
assert_eq!(z.read_name("mimetype").unwrap().unwrap(), b"application/epub+zip");
assert_eq!(z.read_name("a/b.txt").unwrap().unwrap(), "žluťoučký kůň".repeat(100).as_bytes());
assert_eq!(z.read_name("c.bin").unwrap().unwrap(), b"streamed");
}
#[test]
fn names() {
for n in ["../x", "a/../../x", "/etc/passwd", "C:x", "c:/x", "a\\b", "a\0b", ""] {
assert!(!safe_name(n), "{n:?}");
}
for n in ["OEBPS/content.opf", "a..b/c", "..a", "META-INF/"] {
assert!(safe_name(n), "{n:?}");
}
}
}
+356
View File
@@ -0,0 +1,356 @@
//! Fixture builders: every test book is generated here, so no binary is ever committed.
#![allow(dead_code)]
use liber_format::zip::ZipWriter;
pub const CONTAINER: &str = r#"<?xml version="1.0"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles>
</container>"#;
pub fn xhtml(body: &str) -> String {
format!(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" \
xmlns:epub=\"http://www.idpf.org/2007/ops\"><head><title>t</title>\
<link rel=\"stylesheet\" href=\"style.css\"/></head><body>{body}</body></html>"
)
}
/// An EPUB 3 with the given chapter bodies (`(title, body)`), plus extra files.
pub struct Epub {
pub title: String,
pub chapters: Vec<(String, String)>,
pub extra: Vec<(String, Vec<u8>)>,
pub extra_manifest: String,
pub metadata_extra: String,
pub opf_override: Option<String>,
}
impl Epub {
pub fn new(title: &str) -> Epub {
Epub {
title: title.into(),
chapters: vec![],
extra: vec![],
extra_manifest: String::new(),
metadata_extra: String::new(),
opf_override: None,
}
}
pub fn chapter(mut self, title: &str, body: &str) -> Epub {
self.chapters.push((title.into(), body.into()));
self
}
pub fn file(mut self, name: &str, data: &[u8]) -> Epub {
self.extra.push((name.into(), data.to_vec()));
self
}
pub fn opf(&self) -> String {
if let Some(o) = &self.opf_override {
return o.clone();
}
let mut manifest =
String::from(r#"<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>"#);
let mut spine = String::new();
for (i, _) in self.chapters.iter().enumerate() {
manifest
.push_str(&format!(r#"<item id="c{i}" href="text/ch{i}.xhtml" media-type="application/xhtml+xml"/>"#));
spine.push_str(&format!(r#"<itemref idref="c{i}"/>"#));
}
manifest.push_str(&self.extra_manifest);
format!(
r##"<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:title>{}</dc:title><dc:creator id="a1">Karel Čapek</dc:creator>
<meta refines="#a1" property="role">aut</meta>
<dc:creator id="t1">Some Translator</dc:creator><meta refines="#t1" property="role">trl</meta>
<dc:language>cs</dc:language><dc:identifier id="id">urn:isbn:978-80-207-1247-9</dc:identifier>
<dc:description>&lt;p&gt;A &lt;b&gt;play&lt;/b&gt; about robots.&lt;/p&gt;</dc:description>
<dc:subject>Drama</dc:subject>
<meta property="belongs-to-collection" id="s1">Plays</meta>
<meta refines="#s1" property="collection-type">series</meta><meta refines="#s1" property="group-position">2</meta>
{}
</metadata>
<manifest>{manifest}</manifest>
<spine>{spine}</spine>
</package>"##,
self.title, self.metadata_extra
)
}
pub fn nav(&self) -> String {
let mut li = String::new();
for (i, (t, _)) in self.chapters.iter().enumerate() {
li.push_str(&format!(r#"<li><a href="text/ch{i}.xhtml">{t}</a></li>"#));
}
xhtml(&format!(r#"<nav epub:type="toc"><ol>{li}</ol></nav>"#))
}
pub fn build(&self) -> Vec<u8> {
let mut w = ZipWriter::new(Vec::new());
w.add("mimetype", b"application/epub+zip", false).unwrap();
w.add("META-INF/container.xml", CONTAINER.as_bytes(), true).unwrap();
w.add("OEBPS/content.opf", self.opf().as_bytes(), true).unwrap();
w.add("OEBPS/nav.xhtml", self.nav().as_bytes(), true).unwrap();
for (i, (_, body)) in self.chapters.iter().enumerate() {
w.add(&format!("OEBPS/text/ch{i}.xhtml"), xhtml(body).as_bytes(), true).unwrap();
}
for (n, d) in &self.extra {
w.add(n, d, true).unwrap();
}
w.finish().unwrap()
}
}
/// One entry of a hand-made zip, for archives the safe writer refuses to make.
pub struct Raw {
pub name: String,
pub data: Vec<u8>,
pub deflate: bool,
pub unix_mode: u32,
/// Overrides the declared uncompressed size.
pub declared: Option<u32>,
}
impl Raw {
pub fn file(name: &str, data: &[u8]) -> Raw {
Raw { name: name.into(), data: data.to_vec(), deflate: true, unix_mode: 0o100644, declared: None }
}
}
pub fn raw_zip(entries: &[Raw]) -> Vec<u8> {
let mut out = Vec::new();
let mut central = Vec::new();
for e in entries {
let crc = crc32(&e.data);
let body = if e.deflate { deflate(&e.data) } else { e.data.clone() };
let method: u16 = if e.deflate { 8 } else { 0 };
let usize = e.declared.unwrap_or(e.data.len() as u32);
let off = out.len() as u32;
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
out.extend_from_slice(&20u16.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&method.to_le_bytes());
out.extend_from_slice(&[0, 0, 0x21, 0]);
out.extend_from_slice(&crc.to_le_bytes());
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
out.extend_from_slice(&usize.to_le_bytes());
out.extend_from_slice(&(e.name.len() as u16).to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(e.name.as_bytes());
out.extend_from_slice(&body);
central.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
central.extend_from_slice(&0x0314u16.to_le_bytes());
central.extend_from_slice(&20u16.to_le_bytes());
central.extend_from_slice(&0u16.to_le_bytes());
central.extend_from_slice(&method.to_le_bytes());
central.extend_from_slice(&[0, 0, 0x21, 0]);
central.extend_from_slice(&crc.to_le_bytes());
central.extend_from_slice(&(body.len() as u32).to_le_bytes());
central.extend_from_slice(&usize.to_le_bytes());
central.extend_from_slice(&(e.name.len() as u16).to_le_bytes());
central.extend_from_slice(&[0; 8]);
central.extend_from_slice(&(e.unix_mode << 16).to_le_bytes());
central.extend_from_slice(&off.to_le_bytes());
central.extend_from_slice(e.name.as_bytes());
}
let cd_off = out.len() as u32;
out.extend_from_slice(&central);
out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
out.extend_from_slice(&[0; 4]);
out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
out.extend_from_slice(&(central.len() as u32).to_le_bytes());
out.extend_from_slice(&cd_off.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out
}
pub fn crc32(d: &[u8]) -> u32 {
let mut c: u32 = 0xffff_ffff;
for &b in d {
c ^= b as u32;
for _ in 0..8 {
c = if c & 1 != 0 { (c >> 1) ^ 0xedb8_8320 } else { c >> 1 };
}
}
!c
}
/// Raw deflate with stored blocks only (enough for fixtures; the bomb uses `deflate_zeros`).
pub fn deflate(d: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let chunks: Vec<&[u8]> = if d.is_empty() { vec![&[][..]] } else { d.chunks(65_535).collect() };
for (i, c) in chunks.iter().enumerate() {
out.push(if i + 1 == chunks.len() { 1 } else { 0 });
out.extend_from_slice(&(c.len() as u16).to_le_bytes());
out.extend_from_slice(&(!(c.len() as u16)).to_le_bytes());
out.extend_from_slice(c);
}
out
}
/// A raw deflate stream of `n` zero bytes, tiny (fixed Huffman, length-258 back-references): a bomb.
pub fn deflate_zeros(n: usize) -> Vec<u8> {
struct Bits {
out: Vec<u8>,
acc: u32,
n: u32,
}
impl Bits {
fn put(&mut self, v: u32, len: u32) {
self.acc |= v << self.n;
self.n += len;
while self.n >= 8 {
self.out.push(self.acc as u8);
self.acc >>= 8;
self.n -= 8;
}
}
fn put_rev(&mut self, code: u32, len: u32) {
let mut r = 0;
for i in 0..len {
r |= ((code >> i) & 1) << (len - 1 - i);
}
self.put(r, len);
}
}
let mut b = Bits { out: vec![], acc: 0, n: 0 };
b.put(1, 1); // final
b.put(1, 2); // fixed Huffman
// literal 0: code 0x30 (8 bits)
b.put_rev(0x30, 8);
let mut left = n - 1;
while left >= 258 {
// length 258: code 285 → 7-bit code 285-256 = 29 → 0b0011101 (codes 256..279 are 7 bits from 0)... 285 is
// in 280..287: 8 bits, 0xC0 + (285 - 280).
b.put_rev(0xC0 + 5, 8);
// distance 1: code 0 (5 bits), no extra bits
b.put_rev(0, 5);
left -= 258;
}
for _ in 0..left {
b.put_rev(0x30, 8);
}
b.put_rev(0, 7); // end of block (256)
if b.n > 0 {
b.out.push(b.acc as u8);
}
b.out
}
/// A PalmDB MOBI 6 (or KF8 with `version = 8`) around `html`, uncompressed (1) or PalmDOC literals (2).
pub struct Mobi {
pub html: String,
pub compression: u16,
pub encryption: u16,
pub version: u32,
pub images: Vec<Vec<u8>>,
pub exth: Vec<(u32, Vec<u8>)>,
pub title: String,
}
impl Mobi {
pub fn new(html: &str) -> Mobi {
Mobi {
html: html.into(),
compression: 2,
encryption: 0,
version: 6,
images: vec![],
exth: vec![],
title: "Mobi Title".into(),
}
}
pub fn build(&self) -> Vec<u8> {
let text = self.html.as_bytes();
let mut text_recs: Vec<Vec<u8>> = Vec::new();
for chunk in text.chunks(4096) {
text_recs.push(match self.compression {
2 => palmdoc_literals(chunk),
_ => chunk.to_vec(),
});
}
let mut exth = Vec::new();
let mut entries = self.exth.clone();
entries.push((100, "Karel Čapek".as_bytes().to_vec()));
entries.push((104, b"9788020712479".to_vec()));
exth.extend_from_slice(b"EXTH");
let body_len: usize = entries.iter().map(|(_, v)| 8 + v.len()).sum();
exth.extend_from_slice(&((12 + body_len) as u32).to_be_bytes());
exth.extend_from_slice(&(entries.len() as u32).to_be_bytes());
for (t, v) in &entries {
exth.extend_from_slice(&t.to_be_bytes());
exth.extend_from_slice(&((8 + v.len()) as u32).to_be_bytes());
exth.extend_from_slice(v);
}
let header_len: u32 = 0xe8;
let mut r0 = vec![0u8; 16 + header_len as usize];
r0[0..2].copy_from_slice(&self.compression.to_be_bytes());
r0[4..8].copy_from_slice(&(text.len() as u32).to_be_bytes());
r0[8..10].copy_from_slice(&(text_recs.len() as u16).to_be_bytes());
r0[10..12].copy_from_slice(&4096u16.to_be_bytes());
r0[12..14].copy_from_slice(&self.encryption.to_be_bytes());
r0[16..20].copy_from_slice(b"MOBI");
r0[20..24].copy_from_slice(&header_len.to_be_bytes());
r0[24..28].copy_from_slice(&2u32.to_be_bytes());
r0[28..32].copy_from_slice(&65001u32.to_be_bytes());
r0[36..40].copy_from_slice(&self.version.to_be_bytes());
let first_image = 1 + text_recs.len() as u32;
r0[0x6c..0x70].copy_from_slice(&first_image.to_be_bytes());
r0[0x80..0x84].copy_from_slice(&0x40u32.to_be_bytes());
r0.extend_from_slice(&exth);
let name_off = r0.len() as u32;
r0[84..88].copy_from_slice(&name_off.to_be_bytes());
r0[88..92].copy_from_slice(&(self.title.len() as u32).to_be_bytes());
r0.extend_from_slice(self.title.as_bytes());
r0.extend_from_slice(&[0, 0]);
let mut recs = vec![r0];
recs.extend(text_recs);
recs.extend(self.images.iter().cloned());
let mut out = vec![0u8; 78 + recs.len() * 8 + 2];
out[..10].copy_from_slice(b"liber-test");
out[60..68].copy_from_slice(b"BOOKMOBI");
out[76..78].copy_from_slice(&(recs.len() as u16).to_be_bytes());
let mut off = out.len();
for (i, r) in recs.iter().enumerate() {
out[78 + i * 8..82 + i * 8].copy_from_slice(&(off as u32).to_be_bytes());
off += r.len();
}
for r in recs {
out.extend_from_slice(&r);
}
out
}
}
/// PalmDOC with literal runs only: bytes 0x09–0x7f as themselves, others in 1–8 byte literal runs.
pub fn palmdoc_literals(d: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let mut i = 0;
while i < d.len() {
let b = d[i];
if (0x09..=0x7f).contains(&b) || b == 0 {
out.push(b);
i += 1;
} else {
let n = (d.len() - i).min(8);
out.push(n as u8);
out.extend_from_slice(&d[i..i + n]);
i += n;
}
}
out
}
/// A 1×1 PNG.
pub const PNG: &[u8] = &[
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6,
0, 0, 0, 0x1f, 0x15, 0xc4, 0x89, 0, 0, 0, 13, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0,
0x1f, 0, 5, 0, 1, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0, 0, 0, 0, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];
+19
View File
@@ -0,0 +1,19 @@
//! Opens every file `fixtures-fetch/fetch.mjs` put in `fixtures/fetched/` (none by default): no panic, bounded
//! time, nothing active or remote in the output.
#[test]
fn fetched_corpus() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched");
let Ok(entries) = std::fs::read_dir(&dir) else { return };
for e in entries.flatten() {
let bytes = std::fs::read(e.path()).unwrap();
let t = std::time::Instant::now();
if let Ok(d) = liber_format::open(&bytes, e.file_name().to_str(), &liber_format::Limits::default()) {
for c in &d.chapters {
let x = c.xhtml.replacen("http://www.w3.org/1999/xhtml", "", 1);
assert!(!x.contains("<script") && !x.contains("http"), "{}", e.path().display());
}
}
assert!(t.elapsed().as_secs() < 30, "{}", e.path().display());
}
}
+179
View File
@@ -0,0 +1,179 @@
//! Every format opens into the same model.
mod common;
use common::*;
use liber_format::{Format, FormatError, Limits, open, sniff};
#[test]
fn epub_metadata_toc_images_cover() {
let mut e = Epub::new("R.U.R.")
.chapter("Předmluva", "<p>První <img src=\"../images/a.png\" alt=\"obr\"/> text.</p>")
.chapter("Druhá", "<h2>Heading two</h2><p>Text <a href=\"ch0.xhtml\">back</a>.</p>")
.file("OEBPS/images/a.png", PNG)
.file("OEBPS/images/cover.png", PNG);
e.extra_manifest =
r#"<item id="cover" href="images/cover.png" media-type="image/png" properties="cover-image"/>"#.into();
let d = open(&e.build(), Some("rur.epub"), &Limits::default()).unwrap();
assert_eq!(d.format, Format::Epub);
assert_eq!(d.metadata.title.as_deref(), Some("R.U.R."));
assert_eq!(d.metadata.authors, vec!["Karel Čapek"], "translators are not authors");
assert_eq!(d.metadata.language.as_deref(), Some("cs"));
assert_eq!(d.metadata.isbn.as_deref(), Some("9788020712479"));
assert_eq!(d.metadata.description.as_deref(), Some("A play about robots."));
assert_eq!(d.metadata.series.as_ref().map(|s| (s.name.as_str(), s.index)), Some(("Plays", Some(2.0))));
assert_eq!(d.toc.len(), 2);
assert_eq!(d.chapters[0].title.as_deref(), Some("Předmluva"));
assert_eq!(d.images.len(), 2);
assert!(d.chapters[0].xhtml.contains("data-img=\"0\""));
assert_eq!(d.cover, Some(1));
assert!(d.chapters[1].xhtml.contains("data-href=\"0\""));
}
#[test]
fn fb2_in_windows_1251_with_notes_and_images() {
let fb2 = format!(
r##"<?xml version="1.0" encoding="windows-1251"?>
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
<description><title-info><genre>sf</genre><author><first-name>Аркадий</first-name><last-name>Стругацкий</last-name></author>
<book-title>Пикник на обочине</book-title><lang>ru</lang><sequence name="Мир Полудня" number="3"/>
<coverpage><image l:href="#cover.png"/></coverpage></title-info>
<publish-info><isbn>978-0-441-17271-9</isbn></publish-info></description>
<body><title><p>Пикник</p><p>на обочине</p></title>
<section id="s1"><title><p>Глава 1</p></title><p>Текст с <emphasis>ударением</emphasis><a l:href="#n1" type="note">1</a>.</p>
<image l:href="#cover.png"/></section>
<section><title><p>Глава 2</p></title><p>Ещё текст.</p><empty-line/><poem><stanza><v>Строка</v></stanza></poem></section>
</body>
<body name="notes"><section id="n1"><title><p>1</p></title><p>Примечание.</p></section></body>
<binary id="cover.png" content-type="image/png">{}</binary>
</FictionBook>"##,
b64(PNG)
);
let (bytes, _, _) = encoding_rs::WINDOWS_1251.encode(&fb2);
let d = open(&bytes, Some("piknik.fb2"), &Limits::default()).unwrap();
assert_eq!(d.format, Format::Fb2);
assert_eq!(d.metadata.title.as_deref(), Some("Пикник на обочине"));
assert_eq!(d.metadata.authors, vec!["Аркадий Стругацкий"]);
assert_eq!(d.metadata.series.as_ref().map(|s| s.index), Some(Some(3.0)));
assert_eq!(d.metadata.isbn.as_deref(), Some("9780441172719"));
assert_eq!(d.chapters.len(), 4, "title page, two sections, notes");
assert_eq!(d.chapters[1].title.as_deref(), Some("Глава 1"));
assert!(d.chapters[1].xhtml.contains("<em>ударением</em>"));
let notes = d.chapters.len() - 1;
assert!(d.chapters[1].xhtml.contains(&format!("data-href=\"{notes}#n1\"")), "{}", d.chapters[1].xhtml);
assert!(d.footnotes.get(&format!("{notes}#n1")).is_some_and(|n| n.contains("Примечание")));
assert!(!d.chapters[notes].linear);
assert_eq!(d.images.len(), 1);
assert_eq!(d.cover, Some(0));
// The same book zipped.
let mut w = liber_format::zip::ZipWriter::new(Vec::new());
w.add("piknik.fb2", &bytes, true).unwrap();
let z = w.finish().unwrap();
let dz = open(&z, Some("piknik.fb2.zip"), &Limits::default()).unwrap();
assert_eq!(dz.format, Format::Fb2);
assert_eq!(dz.fingerprint(), d.fingerprint());
}
fn b64(d: &[u8]) -> String {
const A: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut s = String::new();
for c in d.chunks(3) {
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
for i in 0..4 {
if i <= c.len() {
s.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
s.push('=');
}
}
}
s
}
#[test]
fn txt_in_windows_1250_with_chapters() {
let text = "Title: Válka s mloky\r\nAuthor: Karel Čapek\r\n\r\nKAPITOLA I.\r\n\r\nKapitán van Toch šel\r\npo břehu.\r\n\r\nŘekl: „Ano.“\r\n\r\nKAPITOLA II.\r\n\r\nMloci přišli.\r\n";
let (bytes, _, _) = encoding_rs::WINDOWS_1250.encode(text);
let d = open(&bytes, Some("valka_s_mloky.txt"), &Limits::default()).unwrap();
assert_eq!(d.format, Format::Txt);
assert_eq!(d.metadata.title.as_deref(), Some("Válka s mloky"));
assert_eq!(d.metadata.authors, vec!["Karel Čapek"]);
assert_eq!(d.chapters.len(), 3, "front matter and two chapters");
assert_eq!(d.chapters[1].title.as_deref(), Some("KAPITOLA I."));
assert!(d.chapters[1].text().contains("Kapitán van Toch šel po břehu."), "hard wraps joined");
assert!(d.chapters[1].text().contains("„Ano.“"));
// Plain UTF-8 without headings: one chapter, the file name as title.
let d =
open("Just one line of text.\nAnd another.".as_bytes(), Some("C:\\books\\my_notes.txt"), &Limits::default())
.unwrap();
assert_eq!(d.chapters.len(), 1);
assert_eq!(d.metadata.title.as_deref(), Some("my notes"));
}
#[test]
fn mobi6_with_pagebreaks_images_and_exth() {
let mut m = Mobi::new(
"<html><head><guide></guide></head><body><h1>Jedna</h1><p>Příliš žluťoučký kůň.</p><img recindex=\"00001\"/>\
<mbp:pagebreak/><h1>Dvě</h1><p>Second <b>part</b>.<p>Unclosed para</body></html>",
);
m.images.push(PNG.to_vec());
m.exth.push((201, 0u32.to_be_bytes().to_vec()));
m.exth.push((503, b"Updated Title".to_vec()));
let d = open(&m.build(), Some("kun.mobi"), &Limits::default()).unwrap();
assert_eq!(d.format, Format::Mobi);
assert_eq!(d.metadata.title.as_deref(), Some("Updated Title"));
assert_eq!(d.metadata.authors, vec!["Karel Čapek"]);
assert_eq!(d.metadata.isbn.as_deref(), Some("9788020712479"));
assert_eq!(d.chapters.len(), 2);
assert_eq!(d.chapters[0].title.as_deref(), Some("Jedna"));
assert!(d.chapters[0].text().contains("Příliš žluťoučký kůň."));
assert!(d.chapters[0].xhtml.contains("data-img=\"0\""), "{}", d.chapters[0].xhtml);
assert!(d.chapters[1].xhtml.contains("<b>part</b>"));
assert_eq!(d.cover, Some(0));
// Uncompressed records read the same.
m.compression = 1;
let d1 = open(&m.build(), None, &Limits::default()).unwrap();
assert_eq!(d1.fingerprint(), d.fingerprint());
}
#[test]
fn azw3_splits_at_documents_and_reads_kindle_embed() {
let mut m = Mobi::new(
"<?xml version=\"1.0\"?><html><head></head><body aid=\"0\"></body></html><p>First file text.</p>\
<img src=\"kindle:embed:0001?mime=image/png\"/>\
<html><head></head><body aid=\"1\"></body></html><p>Second file text.</p>",
);
m.version = 8;
m.images.push(PNG.to_vec());
let d = open(&m.build(), Some("x.azw3"), &Limits::default()).unwrap();
assert_eq!(d.format, Format::Azw3);
assert_eq!(d.chapters.len(), 2);
assert!(d.chapters[0].text().contains("First file text."));
assert!(d.chapters[0].xhtml.contains("data-img=\"0\""));
assert!(d.chapters[1].text().contains("Second file text."));
}
#[test]
fn the_same_text_in_two_formats_has_one_fingerprint() {
let html = "<h1>Kapitola</h1><p>Stejný text, jiný formát.</p>";
let epub = open(&Epub::new("x").chapter("Kapitola", html).build(), None, &Limits::default()).unwrap();
let mobi =
open(&Mobi::new(&format!("<html><body>{html}</body></html>")).build(), None, &Limits::default()).unwrap();
assert_eq!(epub.fingerprint(), mobi.fingerprint());
let other =
open(&Epub::new("x").chapter("Kapitola", "<p>Jiný text.</p>").build(), None, &Limits::default()).unwrap();
assert_ne!(epub.fingerprint(), other.fingerprint());
}
#[test]
fn pdf_is_handed_to_the_pdf_view() {
assert_eq!(sniff(b"%PDF-1.7\n...", None), Some(Format::Pdf));
assert_eq!(open(b"%PDF-1.7\n...", None, &Limits::default()).unwrap_err(), FormatError::Pdf);
}
#[test]
fn binary_garbage_is_not_a_book() {
let junk: Vec<u8> = (0..10_000u32).map(|i| (i * 7 % 256) as u8).collect();
let r = open(&junk, Some("junk.bin"), &Limits::default());
assert!(r.is_err() || r.unwrap().chapters.len() <= 1);
}
+36
View File
@@ -0,0 +1,36 @@
//! Random mutations of valid books never panic and finish in bounded time.
mod common;
use common::*;
use liber_format::{Limits, open};
use proptest::prelude::*;
fn seeds() -> Vec<Vec<u8>> {
let mut m =
Mobi::new("<html><body><h1>A</h1><p>Text ž</p><img recindex=\"1\"/><mbp:pagebreak/><p>B</p></body></html>");
m.images.push(PNG.to_vec());
vec![
Epub::new("Fuzz").chapter("One", "<p>Hello <em>world</em> <a href=\"#x\">x</a></p><aside id=\"x\">n</aside>").file("OEBPS/a.png", PNG).build(),
m.build(),
br#"<?xml version="1.0"?><FictionBook><description><title-info><book-title>F</book-title></title-info></description><body><section><p>t</p></section></body></FictionBook>"#.to_vec(),
]
}
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
#[test]
fn mutations_never_panic(which in 0usize..3, flips in prop::collection::vec((any::<usize>(), any::<u8>()), 1..16), cut in any::<Option<usize>>()) {
let mut b = seeds().swap_remove(which);
for (at, v) in flips {
let i = at % b.len();
b[i] = v;
}
if let Some(c) = cut {
b.truncate(c % (b.len() + 1));
}
let limits = Limits { max_total: 16 << 20, max_entry: 8 << 20, max_xml: 4 << 20, max_text: 8 << 20, ..Limits::default() };
let t = std::time::Instant::now();
let _ = open(&b, None, &limits);
prop_assert!(t.elapsed().as_secs() < 5);
}
}
+389
View File
@@ -0,0 +1,389 @@
//! Mandatory test 1: hostile e-books (docs/FORMATS.md §3). Each is refused or sanitized; nothing is written
//! anywhere (the crate has no file-system or network code: `purity.rs`); no remote URL survives.
mod common;
use common::*;
use liber_format::{DRM_MESSAGE, FormatError, Limits, open};
fn epub_with(extra: Vec<Raw>) -> Vec<u8> {
let e = Epub::new("Hostile").chapter("One", "<p>Hello.</p>");
let mut entries = vec![
Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") },
Raw::file("META-INF/container.xml", CONTAINER.as_bytes()),
Raw::file("OEBPS/content.opf", e.opf().as_bytes()),
Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()),
Raw::file("OEBPS/text/ch0.xhtml", xhtml("<p>Hello.</p>").as_bytes()),
];
entries.extend(extra);
raw_zip(&entries)
}
fn err(bytes: &[u8]) -> FormatError {
open(bytes, Some("x.epub"), &Limits::default()).expect_err("must be refused")
}
#[test]
fn baseline_opens() {
let d = open(&epub_with(vec![]), None, &Limits::default()).unwrap();
assert_eq!(d.chapters[0].text(), "Hello.");
}
#[test]
fn zip_slip_is_refused_and_nothing_is_written() {
let marker = format!("liber-zipslip-{}.txt", std::process::id());
for name in [
format!("../../{marker}"),
format!("OEBPS/../../{marker}"),
format!("/tmp/{marker}"),
format!("C:{marker}"),
format!("..\\..\\{marker}"),
] {
let bytes = epub_with(vec![Raw::file(&name, b"pwned")]);
assert!(matches!(err(&bytes), FormatError::Unsafe(_)), "{name}");
}
for dir in [std::env::current_dir().unwrap(), std::env::temp_dir()] {
let mut d = dir.clone();
for _ in 0..3 {
assert!(!d.join(&marker).exists(), "{} exists", d.join(&marker).display());
d.pop();
}
}
}
#[test]
fn symlinks_are_refused() {
let link = Raw { unix_mode: 0o120777, deflate: false, ..Raw::file("OEBPS/link.xhtml", b"/etc/passwd") };
assert!(matches!(err(&epub_with(vec![link])), FormatError::Unsafe(_)));
}
#[test]
fn zip_bomb_stops_at_the_ratio_cap() {
// 256 MiB of zeros in about 250 kB (about 1000:1), declared as 10 bytes: stopped by the ratio cap.
let bomb = miniz_oxide::deflate::compress_to_vec(&vec![0u8; 256 << 20], 6);
assert!(bomb.len() < 400_000, "{}", bomb.len());
let bytes = replace_last_entry_body(&[], &bomb, 10);
let t = std::time::Instant::now();
let e = err(&bytes);
assert!(matches!(e, FormatError::TooLarge(_)), "{e:?}");
assert!(t.elapsed().as_secs() < 5);
}
#[test]
fn zip_bomb_under_the_ratio_stops_at_the_xml_cap() {
// 64 MiB of zeros at about 160:1 (fixed Huffman), under the ratio cap: stopped at max_xml for a chapter.
let bomb = deflate_zeros(64 << 20);
assert!(bomb.len() < 500_000, "{}", bomb.len());
let bytes = replace_last_entry_body(&[], &bomb, 10);
let t = std::time::Instant::now();
let e = err(&bytes);
assert!(matches!(e, FormatError::TooLarge(_)), "{e:?}");
assert!(t.elapsed().as_secs() < 5);
}
/// Rebuilds a raw zip whose last entry's deflated body is `body`, declaring `declared` bytes.
fn replace_last_entry_body(_old: &[u8], body: &[u8], declared: u32) -> Vec<u8> {
let e = Epub::new("Bomb").chapter("One", "<p>x</p>");
let mut out = raw_zip(&[
Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") },
Raw::file("META-INF/container.xml", CONTAINER.as_bytes()),
Raw::file("OEBPS/content.opf", e.opf().as_bytes()),
Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()),
]);
// Strip the EOCD and central directory of that archive, then append our own entry and directories.
let z = liber_format::zip::Zip::parse(&out, &Limits::default()).unwrap();
let n = z.entries().len();
drop(z);
let eocd = out.len() - 22;
let cd_off = u32::from_le_bytes(out[eocd + 16..eocd + 20].try_into().unwrap()) as usize;
let central = out[cd_off..eocd].to_vec();
out.truncate(cd_off);
let name = b"OEBPS/text/ch0.xhtml";
let off = out.len() as u32;
let crc = 0u32; // never reached: inflation stops at the cap first
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
out.extend_from_slice(&[20, 0, 0, 0, 8, 0, 0, 0, 0x21, 0]);
out.extend_from_slice(&crc.to_le_bytes());
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
out.extend_from_slice(&declared.to_le_bytes());
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(name);
out.extend_from_slice(body);
let mut cd = central;
cd.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
cd.extend_from_slice(&[0x14, 0x03, 20, 0, 0, 0, 8, 0, 0, 0, 0x21, 0]);
cd.extend_from_slice(&crc.to_le_bytes());
cd.extend_from_slice(&(body.len() as u32).to_le_bytes());
cd.extend_from_slice(&declared.to_le_bytes());
cd.extend_from_slice(&(name.len() as u16).to_le_bytes());
cd.extend_from_slice(&[0; 8]);
cd.extend_from_slice(&(0o100644u32 << 16).to_le_bytes());
cd.extend_from_slice(&off.to_le_bytes());
cd.extend_from_slice(name);
let new_cd = out.len() as u32;
out.extend_from_slice(&cd);
out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
out.extend_from_slice(&[0; 4]);
out.extend_from_slice(&((n + 1) as u16).to_le_bytes());
out.extend_from_slice(&((n + 1) as u16).to_le_bytes());
out.extend_from_slice(&(cd.len() as u32).to_le_bytes());
out.extend_from_slice(&new_cd.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out
}
#[test]
fn many_small_entries_stop_at_the_total_cap() {
let big = vec![b'a'; 900 * 1024];
let mut extra = Vec::new();
for i in 0..12 {
extra.push(Raw::file(&format!("OEBPS/img{i}.png"), &big));
}
let mut epub = Epub::new("Total").chapter("One", "");
let mut body = String::new();
for i in 0..12 {
body.push_str(&format!("<img src=\"../img{i}.png\"/>"));
}
epub.chapters[0].1 = body.clone();
let mut entries = vec![
Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") },
Raw::file("META-INF/container.xml", CONTAINER.as_bytes()),
Raw::file("OEBPS/content.opf", epub.opf().as_bytes()),
Raw::file("OEBPS/nav.xhtml", epub.nav().as_bytes()),
Raw::file("OEBPS/text/ch0.xhtml", xhtml(&format!("<p>x</p>{body}")).as_bytes()),
];
entries.extend(extra);
let bytes = raw_zip(&entries);
let limits = Limits { max_total: 4 << 20, ..Limits::default() };
// Images over the total cap are not loaded (and are not raster anyway); the book still opens, bounded.
let d = open(&bytes, None, &limits).unwrap();
assert_eq!(d.images.len(), 0);
// A chapter over the total cap refuses the book.
let limits = Limits { max_total: 1024, ..Limits::default() };
assert!(matches!(open(&bytes, None, &limits).unwrap_err(), FormatError::TooLarge(_)));
}
#[test]
fn too_many_entries() {
let mut extra = Vec::new();
for i in 0..50 {
extra.push(Raw::file(&format!("f{i}"), b"x"));
}
let limits = Limits { max_entries: 20, ..Limits::default() };
assert!(matches!(open(&epub_with(extra), None, &limits).unwrap_err(), FormatError::TooLarge(_)));
}
#[test]
fn xxe_and_billion_laughs_are_refused() {
let xxe_opf = r#"<?xml version="1.0"?><!DOCTYPE package [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><metadata><dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">&xxe;</dc:title></metadata>
<manifest><item id="c0" href="text/ch0.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="c0"/></spine></package>"#;
let mut e = Epub::new("x").chapter("One", "<p>Hi</p>");
e.opf_override = Some(xxe_opf.into());
assert!(matches!(err(&e.build()), FormatError::Unsafe(_)));
let laughs = "<?xml version=\"1.0\"?><!DOCTYPE html [<!ENTITY a \"aaaaaaaaaa\"><!ENTITY b \"&a;&a;&a;&a;&a;&a;&a;&a;\">\
<!ENTITY c \"&b;&b;&b;&b;&b;&b;&b;&b;\">]><html xmlns=\"http://www.w3.org/1999/xhtml\"><body><p>&c;</p></body></html>";
let mut e = Epub::new("x").chapter("One", "");
let mut entries = vec![
Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") },
Raw::file("META-INF/container.xml", CONTAINER.as_bytes()),
Raw::file("OEBPS/content.opf", e.opf().as_bytes()),
Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()),
];
entries.push(Raw::file("OEBPS/text/ch0.xhtml", laughs.as_bytes()));
e.extra.clear();
assert!(matches!(err(&raw_zip(&entries)), FormatError::Unsafe(_)));
// A plain external DTD reference is harmless: nothing is ever fetched, the book opens.
let dtd = "<?xml version=\"1.0\"?><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \
\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><body><p>Fine&nbsp;text</p></body></html>";
entries.pop();
entries.push(Raw::file("OEBPS/text/ch0.xhtml", dtd.as_bytes()));
let d = open(&raw_zip(&entries), None, &Limits::default()).unwrap();
assert_eq!(d.chapters[0].text(), "Fine\u{a0}text");
}
const NASTY: &str = r#"
<p onclick="steal()">Text <a href="javascript:alert(1)">js link</a> and <a href="https://evil.example/track">web</a>.</p>
<script>alert('x')</script><script src="https://evil.example/x.js"></script>
<img src="https://evil.example/pixel.png" onerror="alert(2)"/><img src="//evil.example/p.png"/>
<img src="data:image/png;base64,iVBORw0KGgo="/>
<iframe src="https://evil.example"></iframe><frame src="x"/><object data="x.swf"></object><embed src="x.swf"/>
<form action="https://evil.example"><input name="q"/><button>Go</button><textarea>t</textarea></form>
<style>@font-face { src: url(https://evil.example/f.woff) } body { background: url(https://evil.example/b.png) }</style>
<div style="background:url(https://evil.example/bg.png)" class="x" onmouseover="alert(3)">Styled</div>
<link rel="stylesheet" href="https://evil.example/s.css"/><base href="https://evil.example/"/>
<meta http-equiv="refresh" content="0;url=https://evil.example"/>
<svg xmlns="http://www.w3.org/2000/svg"><script>alert(4)</script><foreignObject><p>in svg</p></foreignObject></svg>
<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math>
<video src="https://evil.example/v.mp4"></video><audio src="a.mp3"></audio><template><p>t</p></template>
<p>Safe <em>emphasis</em> stays.</p>
"#;
#[test]
fn scripts_handlers_forms_and_remote_urls_are_stripped() {
let bytes = Epub::new("Nasty")
.chapter("One", NASTY)
.file("OEBPS/style.css", b"@import url(https://evil.example/i.css);")
.build();
let d = open(&bytes, None, &Limits::default()).unwrap();
let x = d.chapters[0].xhtml.replacen("<div xmlns=\"http://www.w3.org/1999/xhtml\">", "<div>", 1);
for bad in [
"<script",
"alert",
"onclick",
"onerror",
"onmouseover",
"javascript",
"<iframe",
"<frame",
"<object",
"<embed",
"<form",
"<input",
"<button",
"<textarea",
"<style",
"style=",
"class=",
"<link",
"<base",
"<meta",
"<svg",
"<math",
"<video",
"<audio",
"<template",
"http",
"//",
"src=",
"href=",
"url(",
"data:",
] {
assert!(!x.contains(bad), "{bad:?} survived in {x}");
}
assert!(x.contains("<em>emphasis</em>"));
assert!(x.contains("js link") && x.contains("web"), "link text stays: {x}");
assert!(d.images.is_empty());
for f in d.footnotes.values() {
assert!(!f.contains("http"));
}
}
#[test]
fn truncated_archives() {
let good = Epub::new("Cut").chapter("One", "<p>Hello there.</p>").build();
for cut in [good.len() / 2, good.len() - 10, 30, 0] {
let e = err(&good[..cut]);
assert!(matches!(e, FormatError::Malformed(_)), "cut at {cut}: {e:?}");
}
// A flipped byte in a deflated body fails its checksum or inflation, never yields garbage silently.
let mut flipped = good.clone();
let at = good.len() / 2;
flipped[at] ^= 0xff;
let r = open(&flipped, None, &Limits::default());
assert!(r.is_err() || r.as_ref().unwrap().chapters.iter().all(|c| !c.xhtml.contains("<script")));
}
#[test]
fn malformed_packages() {
let mut e = Epub::new("Bad").chapter("One", "<p>x</p>");
e.opf_override = Some("<package><metadata><dc:title>unclosed</metadata></package>".into());
assert!(matches!(err(&e.build()), FormatError::Malformed(_)));
e.opf_override = Some("<package xmlns=\"http://www.idpf.org/2007/opf\"><metadata/><manifest/></package>".into());
assert!(matches!(err(&e.build()), FormatError::Malformed(_)));
let no_opf = raw_zip(&[
Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") },
Raw::file("META-INF/container.xml", CONTAINER.as_bytes()),
]);
assert!(matches!(err(&no_opf), FormatError::Malformed(_)));
// A spine pointing at a missing chapter: the book opens without it only if another chapter has text.
e.opf_override = None;
let mut bytes_e = Epub::new("Missing");
bytes_e.chapters.push(("One".into(), "<p>x</p>".into()));
let ok = bytes_e.build();
assert!(open(&ok, None, &Limits::default()).is_ok());
}
#[test]
fn deep_nesting_does_not_overflow() {
let depth = 100_000;
let body = format!("{}deep{}", "<div>".repeat(depth), "</div>".repeat(depth));
// So repetitive it compresses past the ratio cap: allow it here, depth is what is tested.
let l = Limits { max_ratio: 100_000, ..Limits::default() };
let d = open(&Epub::new("Deep").chapter("One", &body).build(), None, &l).unwrap();
assert!(d.chapters[0].text().contains("deep"));
// Tag soup (not well-formed): through html5ever, still capped.
let soup = format!("{}soup<p>unclosed", "<div><span>".repeat(20_000));
let d = open(&Epub::new("Soup").chapter("One", &soup).build(), None, &l).unwrap();
assert!(d.chapters[0].text().contains("soup"));
}
#[test]
fn drm_is_refused_with_the_one_sentence() {
let rights =
epub_with(vec![Raw::file("META-INF/rights.xml", b"<adept:rights xmlns:adept=\"http://ns.adobe.com/adept\"/>")]);
let lcp = epub_with(vec![Raw::file("META-INF/license.lcpl", b"{}")]);
let fairplay = epub_with(vec![Raw::file("META-INF/sinf.xml", b"<fairplay/>")]);
let aes = epub_with(vec![Raw::file(
"META-INF/encryption.xml",
br#"<encryption xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:enc="http://www.w3.org/2001/04/xmlenc#">
<enc:EncryptedData><enc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc"/>
<enc:CipherData><enc:CipherReference URI="OEBPS/text/ch0.xhtml"/></enc:CipherData></enc:EncryptedData></encryption>"#,
)]);
for (what, b) in [("rights", rights), ("lcp", lcp), ("fairplay", fairplay), ("aes", aes)] {
let e = err(&b);
assert_eq!(e, FormatError::Drm, "{what}");
assert_eq!(e.message(), DRM_MESSAGE);
}
// Font obfuscation only: not DRM.
let fonts = epub_with(vec![Raw::file(
"META-INF/encryption.xml",
br#"<encryption xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:enc="http://www.w3.org/2001/04/xmlenc#">
<enc:EncryptedData><enc:EncryptionMethod Algorithm="http://www.idpf.org/2008/embedding"/>
<enc:CipherData><enc:CipherReference URI="OEBPS/fonts/a.otf"/></enc:CipherData></enc:EncryptedData></encryption>"#,
)]);
assert!(open(&fonts, None, &Limits::default()).is_ok());
// MOBI with Mobipocket DRM, KFX, Topaz.
let mut m = Mobi::new("<html><body><p>secret</p></body></html>");
m.encryption = 2;
assert_eq!(err(&m.build()), FormatError::Drm);
let mut kfx = b"\xeaDRMION\xee".to_vec();
kfx.extend_from_slice(&[0; 100]);
assert_eq!(err(&kfx), FormatError::Drm);
assert_eq!(err(b"TPZ0\x00\x00garbage"), FormatError::Drm);
}
#[test]
fn hostile_mobi() {
let good = Mobi::new("<html><body><p>Hello mobi.</p></body></html>").build();
assert!(open(&good, None, &Limits::default()).is_ok());
// A record offset past the end.
let mut b = good.clone();
b[78..82].copy_from_slice(&u32::MAX.to_be_bytes());
assert!(matches!(err(&b), FormatError::Malformed(_)));
// More text records than records.
let mut b = good.clone();
let r0 = u32::from_be_bytes(good[78..82].try_into().unwrap()) as usize;
b[r0 + 8..r0 + 10].copy_from_slice(&500u16.to_be_bytes());
assert!(matches!(err(&b), FormatError::Malformed(_)));
// A PalmDOC back-reference before the start of the record.
let mut m = Mobi::new("x");
m.compression = 1;
let mut b = m.build();
b[r0..r0 + 2].copy_from_slice(&2u16.to_be_bytes());
let r1 = u32::from_be_bytes(b[86..90].try_into().unwrap()) as usize;
b[r1] = 0x80;
b.push(0xff);
let _ = open(&b, None, &Limits::default());
// HUFF/CDIC compression with no HUFF records: refused cleanly.
let mut b = good.clone();
b[r0..r0 + 2].copy_from_slice(&17480u16.to_be_bytes());
assert!(matches!(err(&b), FormatError::Malformed(_)));
// Absurd text length is capped by max_text, not allocated.
let mut b = good.clone();
b[r0 + 4..r0 + 8].copy_from_slice(&u32::MAX.to_be_bytes());
assert!(open(&b, None, &Limits::default()).is_ok());
}
+161
View File
@@ -0,0 +1,161 @@
//! Mandatory test 2 (the core's half): a highlight's position survives re-rendering and re-import, and a changed
//! edition degrades to "approximate" or "lost", never to other text. Font size and theme do not exist here: they
//! never reach the tree (the app's test renders the same chapter under different settings).
mod common;
use common::*;
use liber_format::position::{Point, anchor, offset_of, point_at, resolve};
use liber_format::{Limits, Resolved, open};
const CH0: &str = "<h1>Prolog</h1><p>Úvodní slovo.</p>";
const CH1: &str = "<h1>Kapitola první</h1>\
<p>Bylo to v <em>temné a bouřlivé</em> noci, když 😀 robot poprvé promluvil.</p>\
<p>Druhý odstavec s <a href=\"#n1\" epub:type=\"noteref\">1</a> poznámkou.</p>\
<aside epub:type=\"footnote\" id=\"n1\"><p>Poznámka pod čarou.</p></aside>";
const CH2: &str = "<h1>Kapitola druhá</h1><p>Konec.</p>";
fn book(ch1: &str) -> Vec<u8> {
Epub::new("R.U.R.").chapter("Prolog", CH0).chapter("Kapitola první", ch1).chapter("Kapitola druhá", CH2).build()
}
fn find16(text: &str, needle: &str) -> (usize, usize) {
let b = text.find(needle).expect("needle");
let s = text[..b].encode_utf16().count();
(s, s + needle.encode_utf16().count())
}
fn quote_at(doc: &liber_format::Document, r: &Resolved) -> String {
match r {
Resolved::Exact { chapter, start, end } | Resolved::Approximate { chapter, start, end } => {
let t: Vec<u16> = doc.chapters[*chapter].text().encode_utf16().collect();
String::from_utf16(&t[*start..*end]).unwrap()
}
Resolved::Lost => String::new(),
}
}
#[test]
fn cfi_round_trips_on_every_text_offset() {
let d = open(&book(CH1), None, &Limits::default()).unwrap();
let ch = &d.chapters[1];
let n = ch.text_len;
for off in 0..=n {
for end in [false, true] {
let p = point_at(1, &ch.root, off, end);
let parsed = Point::parse(&p.to_cfi()).unwrap();
assert_eq!(parsed, p);
// Offsets inside a surrogate pair do not exist in the text; every other offset maps back.
let t = ch.text();
if liber_format::text::byte_at_utf16(&t, off).is_some() {
assert_eq!(offset_of(&ch.root, &parsed), Some(off), "offset {off} cfi {}", p.to_cfi());
}
}
}
}
#[test]
fn cfi_shape() {
let d = open(&book(CH1), None, &Limits::default()).unwrap();
let t = d.chapters[1].text();
let (s, e) = find16(&t, "temné a bouřlivé");
let a = anchor(&d, 1, s, e).unwrap();
// Chapter 1 → /6/4; root /4; the first <p> is the second element (after <h1>): /4; <em> is its first element: /2.
assert_eq!(a.start, "epubcfi(/6/4!/4/4/2/1:0)");
assert_eq!(a.end, "epubcfi(/6/4!/4/4/2/1:16)");
assert_eq!(a.quote.exact, "temné a bouřlivé");
assert_eq!(a.quote.prefix, "Kapitola prvníBylo to v ");
assert!(a.quote.suffix.starts_with(" noci, když 😀"));
}
#[test]
fn a_highlight_survives_reimport_of_the_same_file() {
let bytes = book(CH1);
let d1 = open(&bytes, None, &Limits::default()).unwrap();
let t = d1.chapters[1].text();
let (s, e) = find16(&t, "noci, když 😀 robot");
let a = anchor(&d1, 1, s, e).unwrap();
for _ in 0..3 {
let d2 = open(&bytes, None, &Limits::default()).unwrap();
assert_eq!(d2.chapters[1].xhtml, d1.chapters[1].xhtml, "the sanitizer is deterministic");
assert_eq!(resolve(&d2, &a), Resolved::Exact { chapter: 1, start: s, end: e });
}
}
#[test]
fn a_highlight_across_elements() {
let d = open(&book(CH1), None, &Limits::default()).unwrap();
let t = d.chapters[1].text();
let (s, e) = find16(&t, "v temné a bouřlivé noci");
let a = anchor(&d, 1, s, e).unwrap();
assert_ne!(Point::parse(&a.start).unwrap().steps, Point::parse(&a.end).unwrap().steps);
let r = resolve(&d, &a);
assert_eq!(r, Resolved::Exact { chapter: 1, start: s, end: e });
assert_eq!(quote_at(&d, &r), "v temné a bouřlivé noci");
}
#[test]
fn a_changed_edition_gives_approximate_at_the_same_words() {
let d1 = open(&book(CH1), None, &Limits::default()).unwrap();
let t = d1.chapters[1].text();
let (s, e) = find16(&t, "robot poprvé promluvil");
let a = anchor(&d1, 1, s, e).unwrap();
// The new edition adds a paragraph before it and re-wraps the emphasis.
let edited = CH1
.replace("<p>Bylo to", "<p>Nový úvodní odstavec.</p><p>Bylo to")
.replace("<em>temné a bouřlivé</em>", "temné a bouřlivé");
let d2 = open(&book(&edited), None, &Limits::default()).unwrap();
let r = resolve(&d2, &a);
assert!(matches!(r, Resolved::Approximate { chapter: 1, .. }), "{r:?}");
assert_eq!(quote_at(&d2, &r), "robot poprvé promluvil");
}
#[test]
fn a_moved_chapter_is_found_in_another_chapter() {
let d1 = open(&book(CH1), None, &Limits::default()).unwrap();
let t = d1.chapters[1].text();
let (s, e) = find16(&t, "Druhý odstavec");
let a = anchor(&d1, 1, s, e).unwrap();
let moved = Epub::new("R.U.R.")
.chapter("Kapitola první", CH1)
.chapter("Prolog", CH0)
.chapter("Kapitola druhá", CH2)
.build();
let d2 = open(&moved, None, &Limits::default()).unwrap();
let r = resolve(&d2, &a);
assert!(matches!(r, Resolved::Approximate { chapter: 0, .. }), "{r:?}");
assert_eq!(quote_at(&d2, &r), "Druhý odstavec");
}
#[test]
fn removed_text_is_lost_never_elsewhere() {
let d1 = open(&book(CH1), None, &Limits::default()).unwrap();
let t = d1.chapters[1].text();
let (s, e) = find16(&t, "robot poprvé promluvil");
let a = anchor(&d1, 1, s, e).unwrap();
// Same length, same structure, different words: the CFI still resolves, but to other text.
let reworded = CH1.replace("robot poprvé promluvil", "stroj zase mlčel dlouho");
let d2 = open(&book(&reworded), None, &Limits::default()).unwrap();
assert_eq!(resolve(&d2, &a), Resolved::Lost);
}
#[test]
fn an_ambiguous_quote_is_lost() {
let ch = "<p>ano ano</p><p>ano ano</p>";
let d1 = open(&Epub::new("A").chapter("A", ch).build(), None, &Limits::default()).unwrap();
let a = anchor(&d1, 0, 0, 3).unwrap();
// The same file: exact.
assert!(matches!(resolve(&d1, &a), Resolved::Exact { .. }));
// A new edition where the context no longer tells the occurrences apart.
let d2 =
open(&Epub::new("A").chapter("A", "<p>x</p><p>ano ano</p><p>ano ano</p>").build(), None, &Limits::default())
.unwrap();
let r = resolve(&d2, &a);
assert!(r == Resolved::Lost || quote_at(&d2, &r) == "ano", "{r:?}");
}
#[test]
fn footnotes_and_links() {
let d = open(&book(CH1), None, &Limits::default()).unwrap();
assert!(d.chapters[1].xhtml.contains("data-href=\"1#n1\""), "{}", d.chapters[1].xhtml);
assert_eq!(d.footnotes.get("1#n1").map(|s| s.contains("Poznámka pod čarou")), Some(true));
}
+65
View File
@@ -0,0 +1,65 @@
//! The core is pure: no file system, no network, no clock, no processes in either crate's sources, and no network
//! crate anywhere in Cargo.lock. This is the "network-blocked run" for a library that cannot open a socket at all.
use std::path::Path;
const FORBIDDEN: &[&str] = &[
"std::fs",
"std::net",
"TcpStream",
"UdpSocket",
"std::process",
"Command::new",
"SystemTime",
"Instant::now",
"File::open",
"File::create",
"env::var",
"std::env",
];
fn scan(dir: &Path, hits: &mut Vec<String>) {
for e in std::fs::read_dir(dir).unwrap() {
let p = e.unwrap().path();
if p.is_dir() {
scan(&p, hits);
} else if p.extension().is_some_and(|x| x == "rs") {
let s = std::fs::read_to_string(&p).unwrap();
for f in FORBIDDEN {
if s.contains(f) {
hits.push(format!("{}: {f}", p.display()));
}
}
}
}
}
#[test]
fn sources_have_no_io() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
let mut hits = Vec::new();
scan(&root.join("liber-format/src"), &mut hits);
scan(&root.join("liber-library/src"), &mut hits);
assert!(hits.is_empty(), "{hits:#?}");
}
#[test]
fn no_network_crate_in_the_lockfile() {
let lock = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../Cargo.lock")).unwrap();
for c in [
"reqwest",
"ureq",
"hyper",
"curl",
"tokio",
"isahc",
"attohttpc",
"native-tls",
"rustls",
"openssl",
"socket2",
"mio",
] {
assert!(!lock.contains(&format!("name = \"{c}\"")), "{c} is in Cargo.lock");
}
}