Files
Pictor-public/crates/doc/src/format.rs
T

449 lines
17 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The .pictor file: a zip with `document.json`, `assets/<id>.png` and `fonts/<sha256>.<ttf|otf>`
//! (docs/FORMATS.md, "The .pictor document"). Reading is strict: entries are read by known name with a size cap and
//! never extracted to disk, every name is checked, every referenced asset must be there and match its size, and a
//! newer format is refused before anything else is read.
use crate::model::*;
use serde::{Deserialize, Serialize};
use std::io::{Cursor, Read, Write};
#[derive(Debug, thiserror::Error)]
pub enum FormatError {
#[error("This is not a Pictor document (it is not a zip with document.json).")]
NotPictor,
#[error(
"This file was made by a newer Pictor (format {0}); this one reads format {FORMAT}. Update Pictor to open it."
)]
Newer(u32),
#[error("The document is damaged: {0}")]
Damaged(String),
#[error("The document is too large to open safely: {0}")]
TooLarge(String),
#[error("The document has an unsafe entry name: {0}")]
UnsafeName(String),
#[error("The document refers to a missing picture: {0}")]
MissingAsset(String),
#[error("Could not write the document: {0}")]
Write(String),
}
/// Caps for reading a .pictor from outside.
#[derive(Clone, Copy, Debug)]
pub struct Limits {
pub max_entries: usize,
pub max_json_bytes: u64,
pub max_entry_bytes: u64,
pub max_total_bytes: u64,
/// Uncompressed size ÷ compressed size, per entry.
pub max_ratio: u64,
pub max_pixels: u64,
pub max_total_pixels: u64,
pub max_page_side_pt: f32,
pub max_depth: usize,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_entries: 4096,
max_json_bytes: 64 << 20,
max_entry_bytes: 256 << 20,
max_total_bytes: 1 << 30,
max_ratio: 1000,
max_pixels: 100_000_000,
max_total_pixels: 400_000_000,
max_page_side_pt: 14_400.0,
max_depth: 32,
}
}
}
/// A font stored in a document.
#[derive(Clone, Debug, PartialEq)]
pub struct FontFile {
pub family: String,
pub weight: u16,
pub italic: bool,
pub data: Vec<u8>,
}
#[derive(Serialize, Deserialize)]
struct AssetEntry {
id: String,
width: u32,
height: u32,
}
#[derive(Serialize, Deserialize)]
struct FontEntry {
family: String,
weight: u16,
italic: bool,
file: String,
}
#[derive(Serialize, Deserialize)]
struct OnDisk {
#[serde(flatten)]
doc: Document,
#[serde(default)]
assets: Vec<AssetEntry>,
#[serde(default)]
fonts: Vec<FontEntry>,
}
#[derive(Deserialize)]
struct VersionOnly {
format: u32,
}
/// Asset ids are short letters, digits, `-` and `_` (they become file names).
pub fn valid_asset_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 80 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
pub fn write(doc: &Document, fonts: &[FontFile]) -> Result<Vec<u8>, FormatError> {
use sha2::Digest;
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
let deflate = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
let used = used_assets(doc);
let mut assets = Vec::new();
for (id, r) in &doc.assets {
if !used.contains(id) {
continue;
}
if !valid_asset_id(id) {
return Err(FormatError::Write(format!("asset id {id:?}")));
}
assets.push(AssetEntry { id: id.clone(), width: r.width, height: r.height });
let png = encode_png(r)?;
zip.start_file(format!("assets/{id}.png"), stored).map_err(|e| FormatError::Write(e.to_string()))?;
zip.write_all(&png).map_err(|e| FormatError::Write(e.to_string()))?;
}
let mut font_entries = Vec::new();
for f in fonts {
let ext = if f.data.get(0..4) == Some(b"OTTO") { "otf" } else { "ttf" };
let hex: String = sha2::Sha256::digest(&f.data).iter().map(|b| format!("{b:02x}")).collect();
let name = format!("fonts/{hex}.{ext}");
if !font_entries.iter().any(|e: &FontEntry| e.file == name) {
zip.start_file(name.clone(), deflate).map_err(|e| FormatError::Write(e.to_string()))?;
zip.write_all(&f.data).map_err(|e| FormatError::Write(e.to_string()))?;
}
font_entries.push(FontEntry { family: f.family.clone(), weight: f.weight, italic: f.italic, file: name });
}
let on_disk = OnDisk { doc: doc.clone(), assets, fonts: font_entries };
let json = serde_json::to_vec(&on_disk).map_err(|e| FormatError::Write(e.to_string()))?;
zip.start_file("document.json", deflate).map_err(|e| FormatError::Write(e.to_string()))?;
zip.write_all(&json).map_err(|e| FormatError::Write(e.to_string()))?;
let out = zip.finish().map_err(|e| FormatError::Write(e.to_string()))?;
Ok(out.into_inner())
}
pub fn encode_png(r: &Raster) -> Result<Vec<u8>, FormatError> {
use image::ImageEncoder;
let mut png = Vec::new();
image::codecs::png::PngEncoder::new_with_quality(
&mut png,
image::codecs::png::CompressionType::Fast,
image::codecs::png::FilterType::Adaptive,
)
.write_image(&r.rgba, r.width, r.height, image::ExtendedColorType::Rgba8)
.map_err(|e| FormatError::Write(e.to_string()))?;
Ok(png)
}
/// The asset ids the pages refer to.
pub fn used_assets(doc: &Document) -> std::collections::BTreeSet<String> {
let mut out = std::collections::BTreeSet::new();
fn objects(os: &[Object], out: &mut std::collections::BTreeSet<String>) {
for o in os {
match &o.shape {
Shape::Image { asset, .. } => {
out.insert(asset.clone());
}
Shape::Group { objects: g } => objects(g, out),
_ => {}
}
}
}
fn layers(ls: &[Layer], out: &mut std::collections::BTreeSet<String>) {
for l in ls {
match &l.kind {
LayerKind::Vector { objects: os } => objects(os, out),
LayerKind::Bitmap { asset, .. } => {
out.insert(asset.clone());
}
LayerKind::Group { layers: g } => layers(g, out),
}
}
}
for p in &doc.pages {
layers(&p.layers, &mut out);
}
out
}
fn safe_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 200
&& !name.starts_with('/')
&& !name.contains('\\')
&& !name.contains(':')
&& !name.split('/').any(|part| part.is_empty() || part == ".." || part == ".")
}
fn read_entry<R: Read + std::io::Seek>(
zip: &mut zip::ZipArchive<R>,
name: &str,
cap: u64,
limits: &Limits,
total: &mut u64,
) -> Result<Vec<u8>, FormatError> {
let mut f = zip.by_name(name).map_err(|_| FormatError::MissingAsset(name.to_string()))?;
let declared = f.size();
let compressed = f.compressed_size().max(1);
if declared > cap {
return Err(FormatError::TooLarge(format!("{name} is {declared} bytes")));
}
if declared / compressed > limits.max_ratio && declared > 1 << 20 {
return Err(FormatError::TooLarge(format!("{name} expands {}×", declared / compressed)));
}
let mut out = Vec::with_capacity(declared.min(cap) as usize);
(&mut f).take(cap + 1).read_to_end(&mut out).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
if out.len() as u64 > cap || out.len() as u64 != declared {
return Err(FormatError::TooLarge(format!("{name} is larger than it says")));
}
*total += out.len() as u64;
if *total > limits.max_total_bytes {
return Err(FormatError::TooLarge("the entries together".into()));
}
Ok(out)
}
/// Reads a .pictor. Fonts come back as data for the font book; the document's assets are decoded.
pub fn read(bytes: &[u8], limits: &Limits) -> Result<(Document, Vec<FontFile>), FormatError> {
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|_| FormatError::NotPictor)?;
if zip.len() > limits.max_entries {
return Err(FormatError::TooLarge(format!("{} entries", zip.len())));
}
for i in 0..zip.len() {
let f = zip.by_index_raw(i).map_err(|e| FormatError::Damaged(e.to_string()))?;
let name = f.name().to_string();
if !safe_name(&name) {
return Err(FormatError::UnsafeName(name));
}
if f.is_dir() || f.is_symlink() {
return Err(FormatError::UnsafeName(name));
}
}
if zip.index_for_name("document.json").is_none() {
return Err(FormatError::NotPictor);
}
let mut total = 0u64;
let json = read_entry(&mut zip, "document.json", limits.max_json_bytes, limits, &mut total)?;
// The version first: a newer document is refused before its schema is trusted.
let v: VersionOnly =
serde_json::from_slice(&json).map_err(|e| FormatError::Damaged(format!("document.json: {e}")))?;
if v.format > FORMAT {
return Err(FormatError::Newer(v.format));
}
if v.format == 0 {
return Err(FormatError::Damaged("format 0".into()));
}
let on_disk: OnDisk =
serde_json::from_slice(&json).map_err(|e| FormatError::Damaged(format!("document.json: {e}")))?;
let mut doc = on_disk.doc;
validate(&doc, limits)?;
let used = used_assets(&doc);
let mut pixels = 0u64;
for a in &on_disk.assets {
if !valid_asset_id(&a.id) {
return Err(FormatError::UnsafeName(a.id.clone()));
}
let px = a.width as u64 * a.height as u64;
if px == 0 || px > limits.max_pixels {
return Err(FormatError::TooLarge(format!("picture {} is {}×{}", a.id, a.width, a.height)));
}
pixels += px;
if pixels > limits.max_total_pixels {
return Err(FormatError::TooLarge("the pictures together".into()));
}
let name = format!("assets/{}.png", a.id);
let png = read_entry(&mut zip, &name, limits.max_entry_bytes, limits, &mut total)?;
let raster =
decode_png(&png, a.width, a.height, limits).map_err(|e| FormatError::Damaged(format!("{name}: {e}")))?;
doc.assets.insert(a.id.clone(), raster);
}
for id in &used {
if !doc.assets.contains_key(id) {
return Err(FormatError::MissingAsset(id.clone()));
}
}
let mut fonts = Vec::new();
for f in &on_disk.fonts {
if !safe_name(&f.file) || !f.file.starts_with("fonts/") {
return Err(FormatError::UnsafeName(f.file.clone()));
}
let data = read_entry(&mut zip, &f.file, limits.max_entry_bytes, limits, &mut total)?;
if ttf_parser::Face::parse(&data, 0).is_err() {
return Err(FormatError::Damaged(format!("{} is not a font", f.file)));
}
fonts.push(FontFile { family: f.family.clone(), weight: f.weight, italic: f.italic, data });
}
Ok((doc, fonts))
}
pub fn decode_png(png: &[u8], width: u32, height: u32, limits: &Limits) -> Result<Raster, String> {
let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png);
let mut l = image::Limits::default();
l.max_image_width = Some(width);
l.max_image_height = Some(height);
l.max_alloc = Some((limits.max_pixels * 8).min(u64::MAX / 2));
reader.limits(l);
let img = reader.decode().map_err(|e| e.to_string())?;
if img.width() != width || img.height() != height {
return Err(format!("is {}×{}, not {width}×{height}", img.width(), img.height()));
}
Ok(Raster { width, height, rgba: img.into_rgba8().into_raw() })
}
/// Structural checks of a parsed document: sizes, numbers, ids, paths, depth.
pub fn validate(doc: &Document, limits: &Limits) -> Result<(), FormatError> {
let bad = |s: String| Err(FormatError::Damaged(s));
if doc.pages.is_empty() {
return bad("no pages".into());
}
let mut ids = std::collections::HashSet::new();
let mut check_id = |id: Id| -> Result<(), FormatError> {
if id == 0 || id >= doc.next_id || !ids.insert(id) {
return Err(FormatError::Damaged(format!("id {id} is repeated or out of range")));
}
Ok(())
};
let fin = |v: f32, what: &str| -> Result<(), FormatError> {
if v.is_finite() && v.abs() <= 1e6 { Ok(()) } else { Err(FormatError::Damaged(format!("{what} is {v}"))) }
};
fn obj(
o: &Object,
depth: usize,
limits: &Limits,
check_id: &mut dyn FnMut(Id) -> Result<(), FormatError>,
fin: &dyn Fn(f32, &str) -> Result<(), FormatError>,
) -> Result<(), FormatError> {
if depth > limits.max_depth {
return Err(FormatError::TooLarge("groups nested too deep".into()));
}
check_id(o.id)?;
for v in o.transform {
fin(v, "a transform")?;
}
if !(0.0..=1.0).contains(&o.opacity) {
return Err(FormatError::Damaged(format!("opacity {}", o.opacity)));
}
if let Some(s) = &o.stroke {
fin(s.width, "a stroke width")?;
if s.dash.len() > 64 {
return Err(FormatError::Damaged("a dash pattern is too long".into()));
}
}
match &o.shape {
Shape::Rect { w, h, radius } => {
fin(*w, "a width")?;
fin(*h, "a height")?;
fin(*radius, "a radius")?
}
Shape::Ellipse { w, h } => {
fin(*w, "a width")?;
fin(*h, "a height")?
}
Shape::Line { x1, y1, x2, y2, .. } => {
for v in [x1, y1, x2, y2] {
fin(*v, "a line end")?;
}
}
Shape::Path { d } => {
let segs = crate::path::parse(d).map_err(|e| FormatError::Damaged(e.to_string()))?;
if !matches!(segs.first(), None | Some(crate::path::Seg::Move(..))) {
return Err(FormatError::Damaged("a path starts with M".into()));
}
}
Shape::Text { w, text, style } => {
fin(*w, "a text width")?;
if text.len() > 1 << 20 {
return Err(FormatError::TooLarge("a text box".into()));
}
if !(0.5..=2000.0).contains(&style.size) || !(0.5..=10.0).contains(&style.line_height) {
return Err(FormatError::Damaged("a text size".into()));
}
fin(style.letter_spacing, "letter spacing")?;
}
Shape::Image { asset, w, h, crop } => {
if !valid_asset_id(asset) {
return Err(FormatError::UnsafeName(asset.clone()));
}
for v in [w, h, &crop.x, &crop.y, &crop.w, &crop.h] {
fin(*v, "an image frame")?;
}
}
Shape::Group { objects } => {
for c in objects {
obj(c, depth + 1, limits, check_id, fin)?;
}
}
}
Ok(())
}
fn layers(
ls: &[Layer],
depth: usize,
limits: &Limits,
check_id: &mut dyn FnMut(Id) -> Result<(), FormatError>,
fin: &dyn Fn(f32, &str) -> Result<(), FormatError>,
) -> Result<(), FormatError> {
if depth > limits.max_depth {
return Err(FormatError::TooLarge("layers nested too deep".into()));
}
for l in ls {
check_id(l.id)?;
if !(0.0..=1.0).contains(&l.opacity) {
return Err(FormatError::Damaged(format!("opacity {}", l.opacity)));
}
match &l.kind {
LayerKind::Vector { objects } => {
for o in objects {
obj(o, depth + 1, limits, check_id, fin)?;
}
}
LayerKind::Bitmap { asset, x, y, w, h } => {
if !valid_asset_id(asset) {
return Err(FormatError::UnsafeName(asset.clone()));
}
for v in [x, y, w, h] {
fin(*v, "a layer's place")?;
}
}
LayerKind::Group { layers: g } => layers(g, depth + 1, limits, check_id, fin)?,
}
}
Ok(())
}
for p in &doc.pages {
check_id(p.id)?;
if !(p.width >= 1.0
&& p.width <= limits.max_page_side_pt
&& p.height >= 1.0
&& p.height <= limits.max_page_side_pt)
{
return bad(format!("a page is {} × {} pt", p.width, p.height));
}
for m in p.margins {
fin(m, "a margin")?;
}
if p.guides.len() > 1000 {
return bad("too many guides".into());
}
layers(&p.layers, 0, limits, &mut check_id, &fin)?;
}
Ok(())
}