[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,356 @@
|
||||
//! Fixture builders: every test book is generated here, so no binary is ever committed.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use liber_format::zip::ZipWriter;
|
||||
|
||||
pub const CONTAINER: &str = r#"<?xml version="1.0"?>
|
||||
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
|
||||
<rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles>
|
||||
</container>"#;
|
||||
|
||||
pub fn xhtml(body: &str) -> String {
|
||||
format!(
|
||||
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html>\n<html xmlns=\"http://www.w3.org/1999/xhtml\" \
|
||||
xmlns:epub=\"http://www.idpf.org/2007/ops\"><head><title>t</title>\
|
||||
<link rel=\"stylesheet\" href=\"style.css\"/></head><body>{body}</body></html>"
|
||||
)
|
||||
}
|
||||
|
||||
/// An EPUB 3 with the given chapter bodies (`(title, body)`), plus extra files.
|
||||
pub struct Epub {
|
||||
pub title: String,
|
||||
pub chapters: Vec<(String, String)>,
|
||||
pub extra: Vec<(String, Vec<u8>)>,
|
||||
pub extra_manifest: String,
|
||||
pub metadata_extra: String,
|
||||
pub opf_override: Option<String>,
|
||||
}
|
||||
|
||||
impl Epub {
|
||||
pub fn new(title: &str) -> Epub {
|
||||
Epub {
|
||||
title: title.into(),
|
||||
chapters: vec![],
|
||||
extra: vec![],
|
||||
extra_manifest: String::new(),
|
||||
metadata_extra: String::new(),
|
||||
opf_override: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn chapter(mut self, title: &str, body: &str) -> Epub {
|
||||
self.chapters.push((title.into(), body.into()));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn file(mut self, name: &str, data: &[u8]) -> Epub {
|
||||
self.extra.push((name.into(), data.to_vec()));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn opf(&self) -> String {
|
||||
if let Some(o) = &self.opf_override {
|
||||
return o.clone();
|
||||
}
|
||||
let mut manifest =
|
||||
String::from(r#"<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>"#);
|
||||
let mut spine = String::new();
|
||||
for (i, _) in self.chapters.iter().enumerate() {
|
||||
manifest
|
||||
.push_str(&format!(r#"<item id="c{i}" href="text/ch{i}.xhtml" media-type="application/xhtml+xml"/>"#));
|
||||
spine.push_str(&format!(r#"<itemref idref="c{i}"/>"#));
|
||||
}
|
||||
manifest.push_str(&self.extra_manifest);
|
||||
format!(
|
||||
r##"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id">
|
||||
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<dc:title>{}</dc:title><dc:creator id="a1">Karel Čapek</dc:creator>
|
||||
<meta refines="#a1" property="role">aut</meta>
|
||||
<dc:creator id="t1">Some Translator</dc:creator><meta refines="#t1" property="role">trl</meta>
|
||||
<dc:language>cs</dc:language><dc:identifier id="id">urn:isbn:978-80-207-1247-9</dc:identifier>
|
||||
<dc:description><p>A <b>play</b> about robots.</p></dc:description>
|
||||
<dc:subject>Drama</dc:subject>
|
||||
<meta property="belongs-to-collection" id="s1">Plays</meta>
|
||||
<meta refines="#s1" property="collection-type">series</meta><meta refines="#s1" property="group-position">2</meta>
|
||||
{}
|
||||
</metadata>
|
||||
<manifest>{manifest}</manifest>
|
||||
<spine>{spine}</spine>
|
||||
</package>"##,
|
||||
self.title, self.metadata_extra
|
||||
)
|
||||
}
|
||||
|
||||
pub fn nav(&self) -> String {
|
||||
let mut li = String::new();
|
||||
for (i, (t, _)) in self.chapters.iter().enumerate() {
|
||||
li.push_str(&format!(r#"<li><a href="text/ch{i}.xhtml">{t}</a></li>"#));
|
||||
}
|
||||
xhtml(&format!(r#"<nav epub:type="toc"><ol>{li}</ol></nav>"#))
|
||||
}
|
||||
|
||||
pub fn build(&self) -> Vec<u8> {
|
||||
let mut w = ZipWriter::new(Vec::new());
|
||||
w.add("mimetype", b"application/epub+zip", false).unwrap();
|
||||
w.add("META-INF/container.xml", CONTAINER.as_bytes(), true).unwrap();
|
||||
w.add("OEBPS/content.opf", self.opf().as_bytes(), true).unwrap();
|
||||
w.add("OEBPS/nav.xhtml", self.nav().as_bytes(), true).unwrap();
|
||||
for (i, (_, body)) in self.chapters.iter().enumerate() {
|
||||
w.add(&format!("OEBPS/text/ch{i}.xhtml"), xhtml(body).as_bytes(), true).unwrap();
|
||||
}
|
||||
for (n, d) in &self.extra {
|
||||
w.add(n, d, true).unwrap();
|
||||
}
|
||||
w.finish().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of a hand-made zip, for archives the safe writer refuses to make.
|
||||
pub struct Raw {
|
||||
pub name: String,
|
||||
pub data: Vec<u8>,
|
||||
pub deflate: bool,
|
||||
pub unix_mode: u32,
|
||||
/// Overrides the declared uncompressed size.
|
||||
pub declared: Option<u32>,
|
||||
}
|
||||
|
||||
impl Raw {
|
||||
pub fn file(name: &str, data: &[u8]) -> Raw {
|
||||
Raw { name: name.into(), data: data.to_vec(), deflate: true, unix_mode: 0o100644, declared: None }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn raw_zip(entries: &[Raw]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut central = Vec::new();
|
||||
for e in entries {
|
||||
let crc = crc32(&e.data);
|
||||
let body = if e.deflate { deflate(&e.data) } else { e.data.clone() };
|
||||
let method: u16 = if e.deflate { 8 } else { 0 };
|
||||
let usize = e.declared.unwrap_or(e.data.len() as u32);
|
||||
let off = out.len() as u32;
|
||||
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
|
||||
out.extend_from_slice(&20u16.to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(&method.to_le_bytes());
|
||||
out.extend_from_slice(&[0, 0, 0x21, 0]);
|
||||
out.extend_from_slice(&crc.to_le_bytes());
|
||||
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&usize.to_le_bytes());
|
||||
out.extend_from_slice(&(e.name.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(e.name.as_bytes());
|
||||
out.extend_from_slice(&body);
|
||||
central.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
|
||||
central.extend_from_slice(&0x0314u16.to_le_bytes());
|
||||
central.extend_from_slice(&20u16.to_le_bytes());
|
||||
central.extend_from_slice(&0u16.to_le_bytes());
|
||||
central.extend_from_slice(&method.to_le_bytes());
|
||||
central.extend_from_slice(&[0, 0, 0x21, 0]);
|
||||
central.extend_from_slice(&crc.to_le_bytes());
|
||||
central.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
central.extend_from_slice(&usize.to_le_bytes());
|
||||
central.extend_from_slice(&(e.name.len() as u16).to_le_bytes());
|
||||
central.extend_from_slice(&[0; 8]);
|
||||
central.extend_from_slice(&(e.unix_mode << 16).to_le_bytes());
|
||||
central.extend_from_slice(&off.to_le_bytes());
|
||||
central.extend_from_slice(e.name.as_bytes());
|
||||
}
|
||||
let cd_off = out.len() as u32;
|
||||
out.extend_from_slice(¢ral);
|
||||
out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
|
||||
out.extend_from_slice(&[0; 4]);
|
||||
out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&(entries.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&(central.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&cd_off.to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
pub fn crc32(d: &[u8]) -> u32 {
|
||||
let mut c: u32 = 0xffff_ffff;
|
||||
for &b in d {
|
||||
c ^= b as u32;
|
||||
for _ in 0..8 {
|
||||
c = if c & 1 != 0 { (c >> 1) ^ 0xedb8_8320 } else { c >> 1 };
|
||||
}
|
||||
}
|
||||
!c
|
||||
}
|
||||
|
||||
/// Raw deflate with stored blocks only (enough for fixtures; the bomb uses `deflate_zeros`).
|
||||
pub fn deflate(d: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let chunks: Vec<&[u8]> = if d.is_empty() { vec![&[][..]] } else { d.chunks(65_535).collect() };
|
||||
for (i, c) in chunks.iter().enumerate() {
|
||||
out.push(if i + 1 == chunks.len() { 1 } else { 0 });
|
||||
out.extend_from_slice(&(c.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&(!(c.len() as u16)).to_le_bytes());
|
||||
out.extend_from_slice(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A raw deflate stream of `n` zero bytes, tiny (fixed Huffman, length-258 back-references): a bomb.
|
||||
pub fn deflate_zeros(n: usize) -> Vec<u8> {
|
||||
struct Bits {
|
||||
out: Vec<u8>,
|
||||
acc: u32,
|
||||
n: u32,
|
||||
}
|
||||
impl Bits {
|
||||
fn put(&mut self, v: u32, len: u32) {
|
||||
self.acc |= v << self.n;
|
||||
self.n += len;
|
||||
while self.n >= 8 {
|
||||
self.out.push(self.acc as u8);
|
||||
self.acc >>= 8;
|
||||
self.n -= 8;
|
||||
}
|
||||
}
|
||||
fn put_rev(&mut self, code: u32, len: u32) {
|
||||
let mut r = 0;
|
||||
for i in 0..len {
|
||||
r |= ((code >> i) & 1) << (len - 1 - i);
|
||||
}
|
||||
self.put(r, len);
|
||||
}
|
||||
}
|
||||
let mut b = Bits { out: vec![], acc: 0, n: 0 };
|
||||
b.put(1, 1); // final
|
||||
b.put(1, 2); // fixed Huffman
|
||||
// literal 0: code 0x30 (8 bits)
|
||||
b.put_rev(0x30, 8);
|
||||
let mut left = n - 1;
|
||||
while left >= 258 {
|
||||
// length 258: code 285 → 7-bit code 285-256 = 29 → 0b0011101 (codes 256..279 are 7 bits from 0)... 285 is
|
||||
// in 280..287: 8 bits, 0xC0 + (285 - 280).
|
||||
b.put_rev(0xC0 + 5, 8);
|
||||
// distance 1: code 0 (5 bits), no extra bits
|
||||
b.put_rev(0, 5);
|
||||
left -= 258;
|
||||
}
|
||||
for _ in 0..left {
|
||||
b.put_rev(0x30, 8);
|
||||
}
|
||||
b.put_rev(0, 7); // end of block (256)
|
||||
if b.n > 0 {
|
||||
b.out.push(b.acc as u8);
|
||||
}
|
||||
b.out
|
||||
}
|
||||
|
||||
/// A PalmDB MOBI 6 (or KF8 with `version = 8`) around `html`, uncompressed (1) or PalmDOC literals (2).
|
||||
pub struct Mobi {
|
||||
pub html: String,
|
||||
pub compression: u16,
|
||||
pub encryption: u16,
|
||||
pub version: u32,
|
||||
pub images: Vec<Vec<u8>>,
|
||||
pub exth: Vec<(u32, Vec<u8>)>,
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
impl Mobi {
|
||||
pub fn new(html: &str) -> Mobi {
|
||||
Mobi {
|
||||
html: html.into(),
|
||||
compression: 2,
|
||||
encryption: 0,
|
||||
version: 6,
|
||||
images: vec![],
|
||||
exth: vec![],
|
||||
title: "Mobi Title".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build(&self) -> Vec<u8> {
|
||||
let text = self.html.as_bytes();
|
||||
let mut text_recs: Vec<Vec<u8>> = Vec::new();
|
||||
for chunk in text.chunks(4096) {
|
||||
text_recs.push(match self.compression {
|
||||
2 => palmdoc_literals(chunk),
|
||||
_ => chunk.to_vec(),
|
||||
});
|
||||
}
|
||||
let mut exth = Vec::new();
|
||||
let mut entries = self.exth.clone();
|
||||
entries.push((100, "Karel Čapek".as_bytes().to_vec()));
|
||||
entries.push((104, b"9788020712479".to_vec()));
|
||||
exth.extend_from_slice(b"EXTH");
|
||||
let body_len: usize = entries.iter().map(|(_, v)| 8 + v.len()).sum();
|
||||
exth.extend_from_slice(&((12 + body_len) as u32).to_be_bytes());
|
||||
exth.extend_from_slice(&(entries.len() as u32).to_be_bytes());
|
||||
for (t, v) in &entries {
|
||||
exth.extend_from_slice(&t.to_be_bytes());
|
||||
exth.extend_from_slice(&((8 + v.len()) as u32).to_be_bytes());
|
||||
exth.extend_from_slice(v);
|
||||
}
|
||||
let header_len: u32 = 0xe8;
|
||||
let mut r0 = vec![0u8; 16 + header_len as usize];
|
||||
r0[0..2].copy_from_slice(&self.compression.to_be_bytes());
|
||||
r0[4..8].copy_from_slice(&(text.len() as u32).to_be_bytes());
|
||||
r0[8..10].copy_from_slice(&(text_recs.len() as u16).to_be_bytes());
|
||||
r0[10..12].copy_from_slice(&4096u16.to_be_bytes());
|
||||
r0[12..14].copy_from_slice(&self.encryption.to_be_bytes());
|
||||
r0[16..20].copy_from_slice(b"MOBI");
|
||||
r0[20..24].copy_from_slice(&header_len.to_be_bytes());
|
||||
r0[24..28].copy_from_slice(&2u32.to_be_bytes());
|
||||
r0[28..32].copy_from_slice(&65001u32.to_be_bytes());
|
||||
r0[36..40].copy_from_slice(&self.version.to_be_bytes());
|
||||
let first_image = 1 + text_recs.len() as u32;
|
||||
r0[0x6c..0x70].copy_from_slice(&first_image.to_be_bytes());
|
||||
r0[0x80..0x84].copy_from_slice(&0x40u32.to_be_bytes());
|
||||
r0.extend_from_slice(&exth);
|
||||
let name_off = r0.len() as u32;
|
||||
r0[84..88].copy_from_slice(&name_off.to_be_bytes());
|
||||
r0[88..92].copy_from_slice(&(self.title.len() as u32).to_be_bytes());
|
||||
r0.extend_from_slice(self.title.as_bytes());
|
||||
r0.extend_from_slice(&[0, 0]);
|
||||
let mut recs = vec![r0];
|
||||
recs.extend(text_recs);
|
||||
recs.extend(self.images.iter().cloned());
|
||||
let mut out = vec![0u8; 78 + recs.len() * 8 + 2];
|
||||
out[..10].copy_from_slice(b"liber-test");
|
||||
out[60..68].copy_from_slice(b"BOOKMOBI");
|
||||
out[76..78].copy_from_slice(&(recs.len() as u16).to_be_bytes());
|
||||
let mut off = out.len();
|
||||
for (i, r) in recs.iter().enumerate() {
|
||||
out[78 + i * 8..82 + i * 8].copy_from_slice(&(off as u32).to_be_bytes());
|
||||
off += r.len();
|
||||
}
|
||||
for r in recs {
|
||||
out.extend_from_slice(&r);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// PalmDOC with literal runs only: bytes 0x09–0x7f as themselves, others in 1–8 byte literal runs.
|
||||
pub fn palmdoc_literals(d: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < d.len() {
|
||||
let b = d[i];
|
||||
if (0x09..=0x7f).contains(&b) || b == 0 {
|
||||
out.push(b);
|
||||
i += 1;
|
||||
} else {
|
||||
let n = (d.len() - i).min(8);
|
||||
out.push(n as u8);
|
||||
out.extend_from_slice(&d[i..i + n]);
|
||||
i += n;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A 1×1 PNG.
|
||||
pub const PNG: &[u8] = &[
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6,
|
||||
0, 0, 0, 0x1f, 0x15, 0xc4, 0x89, 0, 0, 0, 13, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0,
|
||||
0x1f, 0, 5, 0, 1, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0, 0, 0, 0, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
|
||||
];
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Opens every file `fixtures-fetch/fetch.mjs` put in `fixtures/fetched/` (none by default): no panic, bounded
|
||||
//! time, nothing active or remote in the output.
|
||||
|
||||
#[test]
|
||||
fn fetched_corpus() {
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched");
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { return };
|
||||
for e in entries.flatten() {
|
||||
let bytes = std::fs::read(e.path()).unwrap();
|
||||
let t = std::time::Instant::now();
|
||||
if let Ok(d) = liber_format::open(&bytes, e.file_name().to_str(), &liber_format::Limits::default()) {
|
||||
for c in &d.chapters {
|
||||
let x = c.xhtml.replacen("http://www.w3.org/1999/xhtml", "", 1);
|
||||
assert!(!x.contains("<script") && !x.contains("http"), "{}", e.path().display());
|
||||
}
|
||||
}
|
||||
assert!(t.elapsed().as_secs() < 30, "{}", e.path().display());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! Every format opens into the same model.
|
||||
|
||||
mod common;
|
||||
use common::*;
|
||||
use liber_format::{Format, FormatError, Limits, open, sniff};
|
||||
|
||||
#[test]
|
||||
fn epub_metadata_toc_images_cover() {
|
||||
let mut e = Epub::new("R.U.R.")
|
||||
.chapter("Předmluva", "<p>První <img src=\"../images/a.png\" alt=\"obr\"/> text.</p>")
|
||||
.chapter("Druhá", "<h2>Heading two</h2><p>Text <a href=\"ch0.xhtml\">back</a>.</p>")
|
||||
.file("OEBPS/images/a.png", PNG)
|
||||
.file("OEBPS/images/cover.png", PNG);
|
||||
e.extra_manifest =
|
||||
r#"<item id="cover" href="images/cover.png" media-type="image/png" properties="cover-image"/>"#.into();
|
||||
let d = open(&e.build(), Some("rur.epub"), &Limits::default()).unwrap();
|
||||
assert_eq!(d.format, Format::Epub);
|
||||
assert_eq!(d.metadata.title.as_deref(), Some("R.U.R."));
|
||||
assert_eq!(d.metadata.authors, vec!["Karel Čapek"], "translators are not authors");
|
||||
assert_eq!(d.metadata.language.as_deref(), Some("cs"));
|
||||
assert_eq!(d.metadata.isbn.as_deref(), Some("9788020712479"));
|
||||
assert_eq!(d.metadata.description.as_deref(), Some("A play about robots."));
|
||||
assert_eq!(d.metadata.series.as_ref().map(|s| (s.name.as_str(), s.index)), Some(("Plays", Some(2.0))));
|
||||
assert_eq!(d.toc.len(), 2);
|
||||
assert_eq!(d.chapters[0].title.as_deref(), Some("Předmluva"));
|
||||
assert_eq!(d.images.len(), 2);
|
||||
assert!(d.chapters[0].xhtml.contains("data-img=\"0\""));
|
||||
assert_eq!(d.cover, Some(1));
|
||||
assert!(d.chapters[1].xhtml.contains("data-href=\"0\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fb2_in_windows_1251_with_notes_and_images() {
|
||||
let fb2 = format!(
|
||||
r##"<?xml version="1.0" encoding="windows-1251"?>
|
||||
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
|
||||
<description><title-info><genre>sf</genre><author><first-name>Аркадий</first-name><last-name>Стругацкий</last-name></author>
|
||||
<book-title>Пикник на обочине</book-title><lang>ru</lang><sequence name="Мир Полудня" number="3"/>
|
||||
<coverpage><image l:href="#cover.png"/></coverpage></title-info>
|
||||
<publish-info><isbn>978-0-441-17271-9</isbn></publish-info></description>
|
||||
<body><title><p>Пикник</p><p>на обочине</p></title>
|
||||
<section id="s1"><title><p>Глава 1</p></title><p>Текст с <emphasis>ударением</emphasis><a l:href="#n1" type="note">1</a>.</p>
|
||||
<image l:href="#cover.png"/></section>
|
||||
<section><title><p>Глава 2</p></title><p>Ещё текст.</p><empty-line/><poem><stanza><v>Строка</v></stanza></poem></section>
|
||||
</body>
|
||||
<body name="notes"><section id="n1"><title><p>1</p></title><p>Примечание.</p></section></body>
|
||||
<binary id="cover.png" content-type="image/png">{}</binary>
|
||||
</FictionBook>"##,
|
||||
b64(PNG)
|
||||
);
|
||||
let (bytes, _, _) = encoding_rs::WINDOWS_1251.encode(&fb2);
|
||||
let d = open(&bytes, Some("piknik.fb2"), &Limits::default()).unwrap();
|
||||
assert_eq!(d.format, Format::Fb2);
|
||||
assert_eq!(d.metadata.title.as_deref(), Some("Пикник на обочине"));
|
||||
assert_eq!(d.metadata.authors, vec!["Аркадий Стругацкий"]);
|
||||
assert_eq!(d.metadata.series.as_ref().map(|s| s.index), Some(Some(3.0)));
|
||||
assert_eq!(d.metadata.isbn.as_deref(), Some("9780441172719"));
|
||||
assert_eq!(d.chapters.len(), 4, "title page, two sections, notes");
|
||||
assert_eq!(d.chapters[1].title.as_deref(), Some("Глава 1"));
|
||||
assert!(d.chapters[1].xhtml.contains("<em>ударением</em>"));
|
||||
let notes = d.chapters.len() - 1;
|
||||
assert!(d.chapters[1].xhtml.contains(&format!("data-href=\"{notes}#n1\"")), "{}", d.chapters[1].xhtml);
|
||||
assert!(d.footnotes.get(&format!("{notes}#n1")).is_some_and(|n| n.contains("Примечание")));
|
||||
assert!(!d.chapters[notes].linear);
|
||||
assert_eq!(d.images.len(), 1);
|
||||
assert_eq!(d.cover, Some(0));
|
||||
|
||||
// The same book zipped.
|
||||
let mut w = liber_format::zip::ZipWriter::new(Vec::new());
|
||||
w.add("piknik.fb2", &bytes, true).unwrap();
|
||||
let z = w.finish().unwrap();
|
||||
let dz = open(&z, Some("piknik.fb2.zip"), &Limits::default()).unwrap();
|
||||
assert_eq!(dz.format, Format::Fb2);
|
||||
assert_eq!(dz.fingerprint(), d.fingerprint());
|
||||
}
|
||||
|
||||
fn b64(d: &[u8]) -> String {
|
||||
const A: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut s = String::new();
|
||||
for c in d.chunks(3) {
|
||||
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
|
||||
for i in 0..4 {
|
||||
if i <= c.len() {
|
||||
s.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);
|
||||
} else {
|
||||
s.push('=');
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn txt_in_windows_1250_with_chapters() {
|
||||
let text = "Title: Válka s mloky\r\nAuthor: Karel Čapek\r\n\r\nKAPITOLA I.\r\n\r\nKapitán van Toch šel\r\npo břehu.\r\n\r\nŘekl: „Ano.“\r\n\r\nKAPITOLA II.\r\n\r\nMloci přišli.\r\n";
|
||||
let (bytes, _, _) = encoding_rs::WINDOWS_1250.encode(text);
|
||||
let d = open(&bytes, Some("valka_s_mloky.txt"), &Limits::default()).unwrap();
|
||||
assert_eq!(d.format, Format::Txt);
|
||||
assert_eq!(d.metadata.title.as_deref(), Some("Válka s mloky"));
|
||||
assert_eq!(d.metadata.authors, vec!["Karel Čapek"]);
|
||||
assert_eq!(d.chapters.len(), 3, "front matter and two chapters");
|
||||
assert_eq!(d.chapters[1].title.as_deref(), Some("KAPITOLA I."));
|
||||
assert!(d.chapters[1].text().contains("Kapitán van Toch šel po břehu."), "hard wraps joined");
|
||||
assert!(d.chapters[1].text().contains("„Ano.“"));
|
||||
// Plain UTF-8 without headings: one chapter, the file name as title.
|
||||
let d =
|
||||
open("Just one line of text.\nAnd another.".as_bytes(), Some("C:\\books\\my_notes.txt"), &Limits::default())
|
||||
.unwrap();
|
||||
assert_eq!(d.chapters.len(), 1);
|
||||
assert_eq!(d.metadata.title.as_deref(), Some("my notes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mobi6_with_pagebreaks_images_and_exth() {
|
||||
let mut m = Mobi::new(
|
||||
"<html><head><guide></guide></head><body><h1>Jedna</h1><p>Příliš žluťoučký kůň.</p><img recindex=\"00001\"/>\
|
||||
<mbp:pagebreak/><h1>Dvě</h1><p>Second <b>part</b>.<p>Unclosed para</body></html>",
|
||||
);
|
||||
m.images.push(PNG.to_vec());
|
||||
m.exth.push((201, 0u32.to_be_bytes().to_vec()));
|
||||
m.exth.push((503, b"Updated Title".to_vec()));
|
||||
let d = open(&m.build(), Some("kun.mobi"), &Limits::default()).unwrap();
|
||||
assert_eq!(d.format, Format::Mobi);
|
||||
assert_eq!(d.metadata.title.as_deref(), Some("Updated Title"));
|
||||
assert_eq!(d.metadata.authors, vec!["Karel Čapek"]);
|
||||
assert_eq!(d.metadata.isbn.as_deref(), Some("9788020712479"));
|
||||
assert_eq!(d.chapters.len(), 2);
|
||||
assert_eq!(d.chapters[0].title.as_deref(), Some("Jedna"));
|
||||
assert!(d.chapters[0].text().contains("Příliš žluťoučký kůň."));
|
||||
assert!(d.chapters[0].xhtml.contains("data-img=\"0\""), "{}", d.chapters[0].xhtml);
|
||||
assert!(d.chapters[1].xhtml.contains("<b>part</b>"));
|
||||
assert_eq!(d.cover, Some(0));
|
||||
// Uncompressed records read the same.
|
||||
m.compression = 1;
|
||||
let d1 = open(&m.build(), None, &Limits::default()).unwrap();
|
||||
assert_eq!(d1.fingerprint(), d.fingerprint());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn azw3_splits_at_documents_and_reads_kindle_embed() {
|
||||
let mut m = Mobi::new(
|
||||
"<?xml version=\"1.0\"?><html><head></head><body aid=\"0\"></body></html><p>First file text.</p>\
|
||||
<img src=\"kindle:embed:0001?mime=image/png\"/>\
|
||||
<html><head></head><body aid=\"1\"></body></html><p>Second file text.</p>",
|
||||
);
|
||||
m.version = 8;
|
||||
m.images.push(PNG.to_vec());
|
||||
let d = open(&m.build(), Some("x.azw3"), &Limits::default()).unwrap();
|
||||
assert_eq!(d.format, Format::Azw3);
|
||||
assert_eq!(d.chapters.len(), 2);
|
||||
assert!(d.chapters[0].text().contains("First file text."));
|
||||
assert!(d.chapters[0].xhtml.contains("data-img=\"0\""));
|
||||
assert!(d.chapters[1].text().contains("Second file text."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_text_in_two_formats_has_one_fingerprint() {
|
||||
let html = "<h1>Kapitola</h1><p>Stejný text, jiný formát.</p>";
|
||||
let epub = open(&Epub::new("x").chapter("Kapitola", html).build(), None, &Limits::default()).unwrap();
|
||||
let mobi =
|
||||
open(&Mobi::new(&format!("<html><body>{html}</body></html>")).build(), None, &Limits::default()).unwrap();
|
||||
assert_eq!(epub.fingerprint(), mobi.fingerprint());
|
||||
let other =
|
||||
open(&Epub::new("x").chapter("Kapitola", "<p>Jiný text.</p>").build(), None, &Limits::default()).unwrap();
|
||||
assert_ne!(epub.fingerprint(), other.fingerprint());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_is_handed_to_the_pdf_view() {
|
||||
assert_eq!(sniff(b"%PDF-1.7\n...", None), Some(Format::Pdf));
|
||||
assert_eq!(open(b"%PDF-1.7\n...", None, &Limits::default()).unwrap_err(), FormatError::Pdf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_garbage_is_not_a_book() {
|
||||
let junk: Vec<u8> = (0..10_000u32).map(|i| (i * 7 % 256) as u8).collect();
|
||||
let r = open(&junk, Some("junk.bin"), &Limits::default());
|
||||
assert!(r.is_err() || r.unwrap().chapters.len() <= 1);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Random mutations of valid books never panic and finish in bounded time.
|
||||
|
||||
mod common;
|
||||
use common::*;
|
||||
use liber_format::{Limits, open};
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn seeds() -> Vec<Vec<u8>> {
|
||||
let mut m =
|
||||
Mobi::new("<html><body><h1>A</h1><p>Text ž</p><img recindex=\"1\"/><mbp:pagebreak/><p>B</p></body></html>");
|
||||
m.images.push(PNG.to_vec());
|
||||
vec![
|
||||
Epub::new("Fuzz").chapter("One", "<p>Hello <em>world</em> <a href=\"#x\">x</a></p><aside id=\"x\">n</aside>").file("OEBPS/a.png", PNG).build(),
|
||||
m.build(),
|
||||
br#"<?xml version="1.0"?><FictionBook><description><title-info><book-title>F</book-title></title-info></description><body><section><p>t</p></section></body></FictionBook>"#.to_vec(),
|
||||
]
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||
#[test]
|
||||
fn mutations_never_panic(which in 0usize..3, flips in prop::collection::vec((any::<usize>(), any::<u8>()), 1..16), cut in any::<Option<usize>>()) {
|
||||
let mut b = seeds().swap_remove(which);
|
||||
for (at, v) in flips {
|
||||
let i = at % b.len();
|
||||
b[i] = v;
|
||||
}
|
||||
if let Some(c) = cut {
|
||||
b.truncate(c % (b.len() + 1));
|
||||
}
|
||||
let limits = Limits { max_total: 16 << 20, max_entry: 8 << 20, max_xml: 4 << 20, max_text: 8 << 20, ..Limits::default() };
|
||||
let t = std::time::Instant::now();
|
||||
let _ = open(&b, None, &limits);
|
||||
prop_assert!(t.elapsed().as_secs() < 5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
//! Mandatory test 1: hostile e-books (docs/FORMATS.md §3). Each is refused or sanitized; nothing is written
|
||||
//! anywhere (the crate has no file-system or network code: `purity.rs`); no remote URL survives.
|
||||
|
||||
mod common;
|
||||
use common::*;
|
||||
use liber_format::{DRM_MESSAGE, FormatError, Limits, open};
|
||||
|
||||
fn epub_with(extra: Vec<Raw>) -> Vec<u8> {
|
||||
let e = Epub::new("Hostile").chapter("One", "<p>Hello.</p>");
|
||||
let mut entries = vec![
|
||||
Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") },
|
||||
Raw::file("META-INF/container.xml", CONTAINER.as_bytes()),
|
||||
Raw::file("OEBPS/content.opf", e.opf().as_bytes()),
|
||||
Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()),
|
||||
Raw::file("OEBPS/text/ch0.xhtml", xhtml("<p>Hello.</p>").as_bytes()),
|
||||
];
|
||||
entries.extend(extra);
|
||||
raw_zip(&entries)
|
||||
}
|
||||
|
||||
fn err(bytes: &[u8]) -> FormatError {
|
||||
open(bytes, Some("x.epub"), &Limits::default()).expect_err("must be refused")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baseline_opens() {
|
||||
let d = open(&epub_with(vec![]), None, &Limits::default()).unwrap();
|
||||
assert_eq!(d.chapters[0].text(), "Hello.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip_slip_is_refused_and_nothing_is_written() {
|
||||
let marker = format!("liber-zipslip-{}.txt", std::process::id());
|
||||
for name in [
|
||||
format!("../../{marker}"),
|
||||
format!("OEBPS/../../{marker}"),
|
||||
format!("/tmp/{marker}"),
|
||||
format!("C:{marker}"),
|
||||
format!("..\\..\\{marker}"),
|
||||
] {
|
||||
let bytes = epub_with(vec![Raw::file(&name, b"pwned")]);
|
||||
assert!(matches!(err(&bytes), FormatError::Unsafe(_)), "{name}");
|
||||
}
|
||||
for dir in [std::env::current_dir().unwrap(), std::env::temp_dir()] {
|
||||
let mut d = dir.clone();
|
||||
for _ in 0..3 {
|
||||
assert!(!d.join(&marker).exists(), "{} exists", d.join(&marker).display());
|
||||
d.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symlinks_are_refused() {
|
||||
let link = Raw { unix_mode: 0o120777, deflate: false, ..Raw::file("OEBPS/link.xhtml", b"/etc/passwd") };
|
||||
assert!(matches!(err(&epub_with(vec![link])), FormatError::Unsafe(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip_bomb_stops_at_the_ratio_cap() {
|
||||
// 256 MiB of zeros in about 250 kB (about 1000:1), declared as 10 bytes: stopped by the ratio cap.
|
||||
let bomb = miniz_oxide::deflate::compress_to_vec(&vec![0u8; 256 << 20], 6);
|
||||
assert!(bomb.len() < 400_000, "{}", bomb.len());
|
||||
let bytes = replace_last_entry_body(&[], &bomb, 10);
|
||||
let t = std::time::Instant::now();
|
||||
let e = err(&bytes);
|
||||
assert!(matches!(e, FormatError::TooLarge(_)), "{e:?}");
|
||||
assert!(t.elapsed().as_secs() < 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip_bomb_under_the_ratio_stops_at_the_xml_cap() {
|
||||
// 64 MiB of zeros at about 160:1 (fixed Huffman), under the ratio cap: stopped at max_xml for a chapter.
|
||||
let bomb = deflate_zeros(64 << 20);
|
||||
assert!(bomb.len() < 500_000, "{}", bomb.len());
|
||||
let bytes = replace_last_entry_body(&[], &bomb, 10);
|
||||
let t = std::time::Instant::now();
|
||||
let e = err(&bytes);
|
||||
assert!(matches!(e, FormatError::TooLarge(_)), "{e:?}");
|
||||
assert!(t.elapsed().as_secs() < 5);
|
||||
}
|
||||
|
||||
/// Rebuilds a raw zip whose last entry's deflated body is `body`, declaring `declared` bytes.
|
||||
fn replace_last_entry_body(_old: &[u8], body: &[u8], declared: u32) -> Vec<u8> {
|
||||
let e = Epub::new("Bomb").chapter("One", "<p>x</p>");
|
||||
let mut out = raw_zip(&[
|
||||
Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") },
|
||||
Raw::file("META-INF/container.xml", CONTAINER.as_bytes()),
|
||||
Raw::file("OEBPS/content.opf", e.opf().as_bytes()),
|
||||
Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()),
|
||||
]);
|
||||
// Strip the EOCD and central directory of that archive, then append our own entry and directories.
|
||||
let z = liber_format::zip::Zip::parse(&out, &Limits::default()).unwrap();
|
||||
let n = z.entries().len();
|
||||
drop(z);
|
||||
let eocd = out.len() - 22;
|
||||
let cd_off = u32::from_le_bytes(out[eocd + 16..eocd + 20].try_into().unwrap()) as usize;
|
||||
let central = out[cd_off..eocd].to_vec();
|
||||
out.truncate(cd_off);
|
||||
let name = b"OEBPS/text/ch0.xhtml";
|
||||
let off = out.len() as u32;
|
||||
let crc = 0u32; // never reached: inflation stops at the cap first
|
||||
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
|
||||
out.extend_from_slice(&[20, 0, 0, 0, 8, 0, 0, 0, 0x21, 0]);
|
||||
out.extend_from_slice(&crc.to_le_bytes());
|
||||
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&declared.to_le_bytes());
|
||||
out.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out.extend_from_slice(name);
|
||||
out.extend_from_slice(body);
|
||||
let mut cd = central;
|
||||
cd.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
|
||||
cd.extend_from_slice(&[0x14, 0x03, 20, 0, 0, 0, 8, 0, 0, 0, 0x21, 0]);
|
||||
cd.extend_from_slice(&crc.to_le_bytes());
|
||||
cd.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
cd.extend_from_slice(&declared.to_le_bytes());
|
||||
cd.extend_from_slice(&(name.len() as u16).to_le_bytes());
|
||||
cd.extend_from_slice(&[0; 8]);
|
||||
cd.extend_from_slice(&(0o100644u32 << 16).to_le_bytes());
|
||||
cd.extend_from_slice(&off.to_le_bytes());
|
||||
cd.extend_from_slice(name);
|
||||
let new_cd = out.len() as u32;
|
||||
out.extend_from_slice(&cd);
|
||||
out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
|
||||
out.extend_from_slice(&[0; 4]);
|
||||
out.extend_from_slice(&((n + 1) as u16).to_le_bytes());
|
||||
out.extend_from_slice(&((n + 1) as u16).to_le_bytes());
|
||||
out.extend_from_slice(&(cd.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&new_cd.to_le_bytes());
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_small_entries_stop_at_the_total_cap() {
|
||||
let big = vec![b'a'; 900 * 1024];
|
||||
let mut extra = Vec::new();
|
||||
for i in 0..12 {
|
||||
extra.push(Raw::file(&format!("OEBPS/img{i}.png"), &big));
|
||||
}
|
||||
let mut epub = Epub::new("Total").chapter("One", "");
|
||||
let mut body = String::new();
|
||||
for i in 0..12 {
|
||||
body.push_str(&format!("<img src=\"../img{i}.png\"/>"));
|
||||
}
|
||||
epub.chapters[0].1 = body.clone();
|
||||
let mut entries = vec![
|
||||
Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") },
|
||||
Raw::file("META-INF/container.xml", CONTAINER.as_bytes()),
|
||||
Raw::file("OEBPS/content.opf", epub.opf().as_bytes()),
|
||||
Raw::file("OEBPS/nav.xhtml", epub.nav().as_bytes()),
|
||||
Raw::file("OEBPS/text/ch0.xhtml", xhtml(&format!("<p>x</p>{body}")).as_bytes()),
|
||||
];
|
||||
entries.extend(extra);
|
||||
let bytes = raw_zip(&entries);
|
||||
let limits = Limits { max_total: 4 << 20, ..Limits::default() };
|
||||
// Images over the total cap are not loaded (and are not raster anyway); the book still opens, bounded.
|
||||
let d = open(&bytes, None, &limits).unwrap();
|
||||
assert_eq!(d.images.len(), 0);
|
||||
// A chapter over the total cap refuses the book.
|
||||
let limits = Limits { max_total: 1024, ..Limits::default() };
|
||||
assert!(matches!(open(&bytes, None, &limits).unwrap_err(), FormatError::TooLarge(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_entries() {
|
||||
let mut extra = Vec::new();
|
||||
for i in 0..50 {
|
||||
extra.push(Raw::file(&format!("f{i}"), b"x"));
|
||||
}
|
||||
let limits = Limits { max_entries: 20, ..Limits::default() };
|
||||
assert!(matches!(open(&epub_with(extra), None, &limits).unwrap_err(), FormatError::TooLarge(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xxe_and_billion_laughs_are_refused() {
|
||||
let xxe_opf = r#"<?xml version="1.0"?><!DOCTYPE package [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
|
||||
<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><metadata><dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">&xxe;</dc:title></metadata>
|
||||
<manifest><item id="c0" href="text/ch0.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="c0"/></spine></package>"#;
|
||||
let mut e = Epub::new("x").chapter("One", "<p>Hi</p>");
|
||||
e.opf_override = Some(xxe_opf.into());
|
||||
assert!(matches!(err(&e.build()), FormatError::Unsafe(_)));
|
||||
|
||||
let laughs = "<?xml version=\"1.0\"?><!DOCTYPE html [<!ENTITY a \"aaaaaaaaaa\"><!ENTITY b \"&a;&a;&a;&a;&a;&a;&a;&a;\">\
|
||||
<!ENTITY c \"&b;&b;&b;&b;&b;&b;&b;&b;\">]><html xmlns=\"http://www.w3.org/1999/xhtml\"><body><p>&c;</p></body></html>";
|
||||
let mut e = Epub::new("x").chapter("One", "");
|
||||
let mut entries = vec![
|
||||
Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") },
|
||||
Raw::file("META-INF/container.xml", CONTAINER.as_bytes()),
|
||||
Raw::file("OEBPS/content.opf", e.opf().as_bytes()),
|
||||
Raw::file("OEBPS/nav.xhtml", e.nav().as_bytes()),
|
||||
];
|
||||
entries.push(Raw::file("OEBPS/text/ch0.xhtml", laughs.as_bytes()));
|
||||
e.extra.clear();
|
||||
assert!(matches!(err(&raw_zip(&entries)), FormatError::Unsafe(_)));
|
||||
|
||||
// A plain external DTD reference is harmless: nothing is ever fetched, the book opens.
|
||||
let dtd = "<?xml version=\"1.0\"?><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \
|
||||
\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><body><p>Fine text</p></body></html>";
|
||||
entries.pop();
|
||||
entries.push(Raw::file("OEBPS/text/ch0.xhtml", dtd.as_bytes()));
|
||||
let d = open(&raw_zip(&entries), None, &Limits::default()).unwrap();
|
||||
assert_eq!(d.chapters[0].text(), "Fine\u{a0}text");
|
||||
}
|
||||
|
||||
const NASTY: &str = r#"
|
||||
<p onclick="steal()">Text <a href="javascript:alert(1)">js link</a> and <a href="https://evil.example/track">web</a>.</p>
|
||||
<script>alert('x')</script><script src="https://evil.example/x.js"></script>
|
||||
<img src="https://evil.example/pixel.png" onerror="alert(2)"/><img src="//evil.example/p.png"/>
|
||||
<img src="data:image/png;base64,iVBORw0KGgo="/>
|
||||
<iframe src="https://evil.example"></iframe><frame src="x"/><object data="x.swf"></object><embed src="x.swf"/>
|
||||
<form action="https://evil.example"><input name="q"/><button>Go</button><textarea>t</textarea></form>
|
||||
<style>@font-face { src: url(https://evil.example/f.woff) } body { background: url(https://evil.example/b.png) }</style>
|
||||
<div style="background:url(https://evil.example/bg.png)" class="x" onmouseover="alert(3)">Styled</div>
|
||||
<link rel="stylesheet" href="https://evil.example/s.css"/><base href="https://evil.example/"/>
|
||||
<meta http-equiv="refresh" content="0;url=https://evil.example"/>
|
||||
<svg xmlns="http://www.w3.org/2000/svg"><script>alert(4)</script><foreignObject><p>in svg</p></foreignObject></svg>
|
||||
<math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math>
|
||||
<video src="https://evil.example/v.mp4"></video><audio src="a.mp3"></audio><template><p>t</p></template>
|
||||
<p>Safe <em>emphasis</em> stays.</p>
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn scripts_handlers_forms_and_remote_urls_are_stripped() {
|
||||
let bytes = Epub::new("Nasty")
|
||||
.chapter("One", NASTY)
|
||||
.file("OEBPS/style.css", b"@import url(https://evil.example/i.css);")
|
||||
.build();
|
||||
let d = open(&bytes, None, &Limits::default()).unwrap();
|
||||
let x = d.chapters[0].xhtml.replacen("<div xmlns=\"http://www.w3.org/1999/xhtml\">", "<div>", 1);
|
||||
for bad in [
|
||||
"<script",
|
||||
"alert",
|
||||
"onclick",
|
||||
"onerror",
|
||||
"onmouseover",
|
||||
"javascript",
|
||||
"<iframe",
|
||||
"<frame",
|
||||
"<object",
|
||||
"<embed",
|
||||
"<form",
|
||||
"<input",
|
||||
"<button",
|
||||
"<textarea",
|
||||
"<style",
|
||||
"style=",
|
||||
"class=",
|
||||
"<link",
|
||||
"<base",
|
||||
"<meta",
|
||||
"<svg",
|
||||
"<math",
|
||||
"<video",
|
||||
"<audio",
|
||||
"<template",
|
||||
"http",
|
||||
"//",
|
||||
"src=",
|
||||
"href=",
|
||||
"url(",
|
||||
"data:",
|
||||
] {
|
||||
assert!(!x.contains(bad), "{bad:?} survived in {x}");
|
||||
}
|
||||
assert!(x.contains("<em>emphasis</em>"));
|
||||
assert!(x.contains("js link") && x.contains("web"), "link text stays: {x}");
|
||||
assert!(d.images.is_empty());
|
||||
for f in d.footnotes.values() {
|
||||
assert!(!f.contains("http"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_archives() {
|
||||
let good = Epub::new("Cut").chapter("One", "<p>Hello there.</p>").build();
|
||||
for cut in [good.len() / 2, good.len() - 10, 30, 0] {
|
||||
let e = err(&good[..cut]);
|
||||
assert!(matches!(e, FormatError::Malformed(_)), "cut at {cut}: {e:?}");
|
||||
}
|
||||
// A flipped byte in a deflated body fails its checksum or inflation, never yields garbage silently.
|
||||
let mut flipped = good.clone();
|
||||
let at = good.len() / 2;
|
||||
flipped[at] ^= 0xff;
|
||||
let r = open(&flipped, None, &Limits::default());
|
||||
assert!(r.is_err() || r.as_ref().unwrap().chapters.iter().all(|c| !c.xhtml.contains("<script")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_packages() {
|
||||
let mut e = Epub::new("Bad").chapter("One", "<p>x</p>");
|
||||
e.opf_override = Some("<package><metadata><dc:title>unclosed</metadata></package>".into());
|
||||
assert!(matches!(err(&e.build()), FormatError::Malformed(_)));
|
||||
e.opf_override = Some("<package xmlns=\"http://www.idpf.org/2007/opf\"><metadata/><manifest/></package>".into());
|
||||
assert!(matches!(err(&e.build()), FormatError::Malformed(_)));
|
||||
let no_opf = raw_zip(&[
|
||||
Raw { deflate: false, ..Raw::file("mimetype", b"application/epub+zip") },
|
||||
Raw::file("META-INF/container.xml", CONTAINER.as_bytes()),
|
||||
]);
|
||||
assert!(matches!(err(&no_opf), FormatError::Malformed(_)));
|
||||
// A spine pointing at a missing chapter: the book opens without it only if another chapter has text.
|
||||
e.opf_override = None;
|
||||
let mut bytes_e = Epub::new("Missing");
|
||||
bytes_e.chapters.push(("One".into(), "<p>x</p>".into()));
|
||||
let ok = bytes_e.build();
|
||||
assert!(open(&ok, None, &Limits::default()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_nesting_does_not_overflow() {
|
||||
let depth = 100_000;
|
||||
let body = format!("{}deep{}", "<div>".repeat(depth), "</div>".repeat(depth));
|
||||
// So repetitive it compresses past the ratio cap: allow it here, depth is what is tested.
|
||||
let l = Limits { max_ratio: 100_000, ..Limits::default() };
|
||||
let d = open(&Epub::new("Deep").chapter("One", &body).build(), None, &l).unwrap();
|
||||
assert!(d.chapters[0].text().contains("deep"));
|
||||
// Tag soup (not well-formed): through html5ever, still capped.
|
||||
let soup = format!("{}soup<p>unclosed", "<div><span>".repeat(20_000));
|
||||
let d = open(&Epub::new("Soup").chapter("One", &soup).build(), None, &l).unwrap();
|
||||
assert!(d.chapters[0].text().contains("soup"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drm_is_refused_with_the_one_sentence() {
|
||||
let rights =
|
||||
epub_with(vec![Raw::file("META-INF/rights.xml", b"<adept:rights xmlns:adept=\"http://ns.adobe.com/adept\"/>")]);
|
||||
let lcp = epub_with(vec![Raw::file("META-INF/license.lcpl", b"{}")]);
|
||||
let fairplay = epub_with(vec![Raw::file("META-INF/sinf.xml", b"<fairplay/>")]);
|
||||
let aes = epub_with(vec![Raw::file(
|
||||
"META-INF/encryption.xml",
|
||||
br#"<encryption xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:enc="http://www.w3.org/2001/04/xmlenc#">
|
||||
<enc:EncryptedData><enc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc"/>
|
||||
<enc:CipherData><enc:CipherReference URI="OEBPS/text/ch0.xhtml"/></enc:CipherData></enc:EncryptedData></encryption>"#,
|
||||
)]);
|
||||
for (what, b) in [("rights", rights), ("lcp", lcp), ("fairplay", fairplay), ("aes", aes)] {
|
||||
let e = err(&b);
|
||||
assert_eq!(e, FormatError::Drm, "{what}");
|
||||
assert_eq!(e.message(), DRM_MESSAGE);
|
||||
}
|
||||
// Font obfuscation only: not DRM.
|
||||
let fonts = epub_with(vec![Raw::file(
|
||||
"META-INF/encryption.xml",
|
||||
br#"<encryption xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:enc="http://www.w3.org/2001/04/xmlenc#">
|
||||
<enc:EncryptedData><enc:EncryptionMethod Algorithm="http://www.idpf.org/2008/embedding"/>
|
||||
<enc:CipherData><enc:CipherReference URI="OEBPS/fonts/a.otf"/></enc:CipherData></enc:EncryptedData></encryption>"#,
|
||||
)]);
|
||||
assert!(open(&fonts, None, &Limits::default()).is_ok());
|
||||
// MOBI with Mobipocket DRM, KFX, Topaz.
|
||||
let mut m = Mobi::new("<html><body><p>secret</p></body></html>");
|
||||
m.encryption = 2;
|
||||
assert_eq!(err(&m.build()), FormatError::Drm);
|
||||
let mut kfx = b"\xeaDRMION\xee".to_vec();
|
||||
kfx.extend_from_slice(&[0; 100]);
|
||||
assert_eq!(err(&kfx), FormatError::Drm);
|
||||
assert_eq!(err(b"TPZ0\x00\x00garbage"), FormatError::Drm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_mobi() {
|
||||
let good = Mobi::new("<html><body><p>Hello mobi.</p></body></html>").build();
|
||||
assert!(open(&good, None, &Limits::default()).is_ok());
|
||||
// A record offset past the end.
|
||||
let mut b = good.clone();
|
||||
b[78..82].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
assert!(matches!(err(&b), FormatError::Malformed(_)));
|
||||
// More text records than records.
|
||||
let mut b = good.clone();
|
||||
let r0 = u32::from_be_bytes(good[78..82].try_into().unwrap()) as usize;
|
||||
b[r0 + 8..r0 + 10].copy_from_slice(&500u16.to_be_bytes());
|
||||
assert!(matches!(err(&b), FormatError::Malformed(_)));
|
||||
// A PalmDOC back-reference before the start of the record.
|
||||
let mut m = Mobi::new("x");
|
||||
m.compression = 1;
|
||||
let mut b = m.build();
|
||||
b[r0..r0 + 2].copy_from_slice(&2u16.to_be_bytes());
|
||||
let r1 = u32::from_be_bytes(b[86..90].try_into().unwrap()) as usize;
|
||||
b[r1] = 0x80;
|
||||
b.push(0xff);
|
||||
let _ = open(&b, None, &Limits::default());
|
||||
// HUFF/CDIC compression with no HUFF records: refused cleanly.
|
||||
let mut b = good.clone();
|
||||
b[r0..r0 + 2].copy_from_slice(&17480u16.to_be_bytes());
|
||||
assert!(matches!(err(&b), FormatError::Malformed(_)));
|
||||
// Absurd text length is capped by max_text, not allocated.
|
||||
let mut b = good.clone();
|
||||
b[r0 + 4..r0 + 8].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
assert!(open(&b, None, &Limits::default()).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! Mandatory test 2 (the core's half): a highlight's position survives re-rendering and re-import, and a changed
|
||||
//! edition degrades to "approximate" or "lost", never to other text. Font size and theme do not exist here: they
|
||||
//! never reach the tree (the app's test renders the same chapter under different settings).
|
||||
|
||||
mod common;
|
||||
use common::*;
|
||||
use liber_format::position::{Point, anchor, offset_of, point_at, resolve};
|
||||
use liber_format::{Limits, Resolved, open};
|
||||
|
||||
const CH0: &str = "<h1>Prolog</h1><p>Úvodní slovo.</p>";
|
||||
const CH1: &str = "<h1>Kapitola první</h1>\
|
||||
<p>Bylo to v <em>temné a bouřlivé</em> noci, když 😀 robot poprvé promluvil.</p>\
|
||||
<p>Druhý odstavec s <a href=\"#n1\" epub:type=\"noteref\">1</a> poznámkou.</p>\
|
||||
<aside epub:type=\"footnote\" id=\"n1\"><p>Poznámka pod čarou.</p></aside>";
|
||||
const CH2: &str = "<h1>Kapitola druhá</h1><p>Konec.</p>";
|
||||
|
||||
fn book(ch1: &str) -> Vec<u8> {
|
||||
Epub::new("R.U.R.").chapter("Prolog", CH0).chapter("Kapitola první", ch1).chapter("Kapitola druhá", CH2).build()
|
||||
}
|
||||
|
||||
fn find16(text: &str, needle: &str) -> (usize, usize) {
|
||||
let b = text.find(needle).expect("needle");
|
||||
let s = text[..b].encode_utf16().count();
|
||||
(s, s + needle.encode_utf16().count())
|
||||
}
|
||||
|
||||
fn quote_at(doc: &liber_format::Document, r: &Resolved) -> String {
|
||||
match r {
|
||||
Resolved::Exact { chapter, start, end } | Resolved::Approximate { chapter, start, end } => {
|
||||
let t: Vec<u16> = doc.chapters[*chapter].text().encode_utf16().collect();
|
||||
String::from_utf16(&t[*start..*end]).unwrap()
|
||||
}
|
||||
Resolved::Lost => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cfi_round_trips_on_every_text_offset() {
|
||||
let d = open(&book(CH1), None, &Limits::default()).unwrap();
|
||||
let ch = &d.chapters[1];
|
||||
let n = ch.text_len;
|
||||
for off in 0..=n {
|
||||
for end in [false, true] {
|
||||
let p = point_at(1, &ch.root, off, end);
|
||||
let parsed = Point::parse(&p.to_cfi()).unwrap();
|
||||
assert_eq!(parsed, p);
|
||||
// Offsets inside a surrogate pair do not exist in the text; every other offset maps back.
|
||||
let t = ch.text();
|
||||
if liber_format::text::byte_at_utf16(&t, off).is_some() {
|
||||
assert_eq!(offset_of(&ch.root, &parsed), Some(off), "offset {off} cfi {}", p.to_cfi());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cfi_shape() {
|
||||
let d = open(&book(CH1), None, &Limits::default()).unwrap();
|
||||
let t = d.chapters[1].text();
|
||||
let (s, e) = find16(&t, "temné a bouřlivé");
|
||||
let a = anchor(&d, 1, s, e).unwrap();
|
||||
// Chapter 1 → /6/4; root /4; the first <p> is the second element (after <h1>): /4; <em> is its first element: /2.
|
||||
assert_eq!(a.start, "epubcfi(/6/4!/4/4/2/1:0)");
|
||||
assert_eq!(a.end, "epubcfi(/6/4!/4/4/2/1:16)");
|
||||
assert_eq!(a.quote.exact, "temné a bouřlivé");
|
||||
assert_eq!(a.quote.prefix, "Kapitola prvníBylo to v ");
|
||||
assert!(a.quote.suffix.starts_with(" noci, když 😀"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_highlight_survives_reimport_of_the_same_file() {
|
||||
let bytes = book(CH1);
|
||||
let d1 = open(&bytes, None, &Limits::default()).unwrap();
|
||||
let t = d1.chapters[1].text();
|
||||
let (s, e) = find16(&t, "noci, když 😀 robot");
|
||||
let a = anchor(&d1, 1, s, e).unwrap();
|
||||
for _ in 0..3 {
|
||||
let d2 = open(&bytes, None, &Limits::default()).unwrap();
|
||||
assert_eq!(d2.chapters[1].xhtml, d1.chapters[1].xhtml, "the sanitizer is deterministic");
|
||||
assert_eq!(resolve(&d2, &a), Resolved::Exact { chapter: 1, start: s, end: e });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_highlight_across_elements() {
|
||||
let d = open(&book(CH1), None, &Limits::default()).unwrap();
|
||||
let t = d.chapters[1].text();
|
||||
let (s, e) = find16(&t, "v temné a bouřlivé noci");
|
||||
let a = anchor(&d, 1, s, e).unwrap();
|
||||
assert_ne!(Point::parse(&a.start).unwrap().steps, Point::parse(&a.end).unwrap().steps);
|
||||
let r = resolve(&d, &a);
|
||||
assert_eq!(r, Resolved::Exact { chapter: 1, start: s, end: e });
|
||||
assert_eq!(quote_at(&d, &r), "v temné a bouřlivé noci");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_edition_gives_approximate_at_the_same_words() {
|
||||
let d1 = open(&book(CH1), None, &Limits::default()).unwrap();
|
||||
let t = d1.chapters[1].text();
|
||||
let (s, e) = find16(&t, "robot poprvé promluvil");
|
||||
let a = anchor(&d1, 1, s, e).unwrap();
|
||||
// The new edition adds a paragraph before it and re-wraps the emphasis.
|
||||
let edited = CH1
|
||||
.replace("<p>Bylo to", "<p>Nový úvodní odstavec.</p><p>Bylo to")
|
||||
.replace("<em>temné a bouřlivé</em>", "temné a bouřlivé");
|
||||
let d2 = open(&book(&edited), None, &Limits::default()).unwrap();
|
||||
let r = resolve(&d2, &a);
|
||||
assert!(matches!(r, Resolved::Approximate { chapter: 1, .. }), "{r:?}");
|
||||
assert_eq!(quote_at(&d2, &r), "robot poprvé promluvil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_chapter_is_found_in_another_chapter() {
|
||||
let d1 = open(&book(CH1), None, &Limits::default()).unwrap();
|
||||
let t = d1.chapters[1].text();
|
||||
let (s, e) = find16(&t, "Druhý odstavec");
|
||||
let a = anchor(&d1, 1, s, e).unwrap();
|
||||
let moved = Epub::new("R.U.R.")
|
||||
.chapter("Kapitola první", CH1)
|
||||
.chapter("Prolog", CH0)
|
||||
.chapter("Kapitola druhá", CH2)
|
||||
.build();
|
||||
let d2 = open(&moved, None, &Limits::default()).unwrap();
|
||||
let r = resolve(&d2, &a);
|
||||
assert!(matches!(r, Resolved::Approximate { chapter: 0, .. }), "{r:?}");
|
||||
assert_eq!(quote_at(&d2, &r), "Druhý odstavec");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_text_is_lost_never_elsewhere() {
|
||||
let d1 = open(&book(CH1), None, &Limits::default()).unwrap();
|
||||
let t = d1.chapters[1].text();
|
||||
let (s, e) = find16(&t, "robot poprvé promluvil");
|
||||
let a = anchor(&d1, 1, s, e).unwrap();
|
||||
// Same length, same structure, different words: the CFI still resolves, but to other text.
|
||||
let reworded = CH1.replace("robot poprvé promluvil", "stroj zase mlčel dlouho");
|
||||
let d2 = open(&book(&reworded), None, &Limits::default()).unwrap();
|
||||
assert_eq!(resolve(&d2, &a), Resolved::Lost);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ambiguous_quote_is_lost() {
|
||||
let ch = "<p>ano ano</p><p>ano ano</p>";
|
||||
let d1 = open(&Epub::new("A").chapter("A", ch).build(), None, &Limits::default()).unwrap();
|
||||
let a = anchor(&d1, 0, 0, 3).unwrap();
|
||||
// The same file: exact.
|
||||
assert!(matches!(resolve(&d1, &a), Resolved::Exact { .. }));
|
||||
// A new edition where the context no longer tells the occurrences apart.
|
||||
let d2 =
|
||||
open(&Epub::new("A").chapter("A", "<p>x</p><p>ano ano</p><p>ano ano</p>").build(), None, &Limits::default())
|
||||
.unwrap();
|
||||
let r = resolve(&d2, &a);
|
||||
assert!(r == Resolved::Lost || quote_at(&d2, &r) == "ano", "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footnotes_and_links() {
|
||||
let d = open(&book(CH1), None, &Limits::default()).unwrap();
|
||||
assert!(d.chapters[1].xhtml.contains("data-href=\"1#n1\""), "{}", d.chapters[1].xhtml);
|
||||
assert_eq!(d.footnotes.get("1#n1").map(|s| s.contains("Poznámka pod čarou")), Some(true));
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! The core is pure: no file system, no network, no clock, no processes in either crate's sources, and no network
|
||||
//! crate anywhere in Cargo.lock. This is the "network-blocked run" for a library that cannot open a socket at all.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
const FORBIDDEN: &[&str] = &[
|
||||
"std::fs",
|
||||
"std::net",
|
||||
"TcpStream",
|
||||
"UdpSocket",
|
||||
"std::process",
|
||||
"Command::new",
|
||||
"SystemTime",
|
||||
"Instant::now",
|
||||
"File::open",
|
||||
"File::create",
|
||||
"env::var",
|
||||
"std::env",
|
||||
];
|
||||
|
||||
fn scan(dir: &Path, hits: &mut Vec<String>) {
|
||||
for e in std::fs::read_dir(dir).unwrap() {
|
||||
let p = e.unwrap().path();
|
||||
if p.is_dir() {
|
||||
scan(&p, hits);
|
||||
} else if p.extension().is_some_and(|x| x == "rs") {
|
||||
let s = std::fs::read_to_string(&p).unwrap();
|
||||
for f in FORBIDDEN {
|
||||
if s.contains(f) {
|
||||
hits.push(format!("{}: {f}", p.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sources_have_no_io() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
|
||||
let mut hits = Vec::new();
|
||||
scan(&root.join("liber-format/src"), &mut hits);
|
||||
scan(&root.join("liber-library/src"), &mut hits);
|
||||
assert!(hits.is_empty(), "{hits:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_network_crate_in_the_lockfile() {
|
||||
let lock = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../Cargo.lock")).unwrap();
|
||||
for c in [
|
||||
"reqwest",
|
||||
"ureq",
|
||||
"hyper",
|
||||
"curl",
|
||||
"tokio",
|
||||
"isahc",
|
||||
"attohttpc",
|
||||
"native-tls",
|
||||
"rustls",
|
||||
"openssl",
|
||||
"socket2",
|
||||
"mio",
|
||||
] {
|
||||
assert!(!lock.contains(&format!("name = \"{c}\"")), "{c} is in Cargo.lock");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user