[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:
@@ -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(()) }
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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(" ", " ")
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace(""", "\"");
|
||||
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
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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![],
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' if attr => out.push_str("""),
|
||||
// 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(" "),
|
||||
'\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
|
||||
}
|
||||
@@ -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})");
|
||||
}
|
||||
}
|
||||
@@ -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![],
|
||||
})
|
||||
}
|
||||
@@ -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& A&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(_)));
|
||||
}
|
||||
}
|
||||
@@ -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(¢ral)?;
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user