mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge pull request #9922 from dotCooCoo/fix/ai-private-data-streamed
.ai import: editing data whose streams pass 256 MiB opens with its layers
This commit is contained in:
13 files changed
+555
-83
No files matched your search
@@ -268,16 +268,26 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions)
|
||||
if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data {
|
||||
return None;
|
||||
}
|
||||
let private = opened.illustrator_data()?;
|
||||
Some(editing_copy_alone(&private, opts))
|
||||
Some(editing_copy_alone(&decoded_copy(opened)?, opts))
|
||||
}
|
||||
|
||||
/// [`from_editing_data_alone`] of `private`, the editor's copy already read.
|
||||
fn editing_copy_alone(private: &[u8], opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
vectorcraft_eps::ai_alone_with(private, opts.legacy_names)
|
||||
/// [`from_editing_data_alone`] of `decoded`, the editor's copy already read and decoded, or why it
|
||||
/// can't be decoded.
|
||||
fn editing_copy_alone(decoded: &std::result::Result<Vec<u8>, String>, opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
decoded
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
.and_then(|data| vectorcraft_eps::ai_alone_decoded(data, opts.legacy_names))
|
||||
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
|
||||
}
|
||||
|
||||
/// The editor's own copy of its art that `opened` carries, read from its streams one after the
|
||||
/// other and decoded as it is read ([`vectorcraft_eps::decode_ai_private`]): the decoded data or why
|
||||
/// it can't be decoded, `None` as for [`vectorcraft_pdf::Opened::illustrator_data`].
|
||||
fn decoded_copy(opened: &vectorcraft_pdf::Opened) -> Option<std::result::Result<Vec<u8>, String>> {
|
||||
opened.read_illustrator_data(|private| vectorcraft_eps::decode_ai_private(private))
|
||||
}
|
||||
|
||||
/// Does a file opened with `opts` read the editor's own copy of its art: no pages picked, and
|
||||
/// layers and the editing data on?
|
||||
fn reads_editing_copy(opts: &LoadOptions) -> bool {
|
||||
@@ -292,10 +302,10 @@ fn reads_layers_alone(opts: &LoadOptions) -> bool {
|
||||
reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines
|
||||
}
|
||||
|
||||
/// The editor's own copy of its art that `opened` carries (as [`vectorcraft_pdf::illustrator_data`]
|
||||
/// reads it), when `opts` read it ([`reads_editing_copy`]).
|
||||
fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<Vec<u8>> {
|
||||
reads_editing_copy(opts).then(|| opened.illustrator_data()).flatten()
|
||||
/// The editor's own copy of its art that `opened` carries, decoded ([`decoded_copy`]), when `opts`
|
||||
/// read it ([`reads_editing_copy`]).
|
||||
fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option<std::result::Result<Vec<u8>, String>> {
|
||||
reads_editing_copy(opts).then(|| decoded_copy(opened)).flatten()
|
||||
}
|
||||
|
||||
/// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's
|
||||
@@ -307,8 +317,12 @@ fn without_pdf_part(bytes: &[u8], opts: &LoadOptions, e: EngineError) -> Result<
|
||||
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
|
||||
return Err(e);
|
||||
}
|
||||
let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part(bytes, opts.password.as_deref())
|
||||
.and_then(|private| private.map(|p| vectorcraft_eps::ai_alone_on_page(&p.data, p.trim, p.user_unit, opts.legacy_names)).transpose());
|
||||
let read = vectorcraft_pdf::read_illustrator_data_without_pdf_part_with(bytes, opts.password.as_deref(), |private| {
|
||||
vectorcraft_eps::decode_ai_private(private)
|
||||
})
|
||||
.and_then(|private| {
|
||||
private.map(|p| p.data.and_then(|data| vectorcraft_eps::ai_alone_on_page_decoded(&data, p.trim, p.user_unit, opts.legacy_names))).transpose()
|
||||
});
|
||||
match read {
|
||||
Ok(Some((doc, warnings))) => {
|
||||
let notes =
|
||||
@@ -466,7 +480,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
|
||||
{
|
||||
let pages = o.trim_pages();
|
||||
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names) {
|
||||
match vectorcraft_eps::ai_layers_alone_decoded(private, &pages.sizes, pages.user_unit, opts.legacy_names) {
|
||||
Ok((mut doc, warnings)) => {
|
||||
doc.setup.bleed = pages.bleed;
|
||||
editing_data = true;
|
||||
@@ -502,7 +516,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
let (doc, warnings, read) = match alone {
|
||||
Some((doc, warnings)) => (doc, warnings, true),
|
||||
None => {
|
||||
let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode));
|
||||
let layers = layers.or_else(|| private.map(vectorcraft_eps::AiLayers::decoded));
|
||||
through_editing_data(layers, opts, r.document, r.warnings, r.user_unit)
|
||||
}
|
||||
};
|
||||
@@ -530,9 +544,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
// A restored document opens on the artboard that the editing copy beside it names as
|
||||
// active, as a file read from that copy does (the restored document never holds one).
|
||||
if read.2
|
||||
&& let Some(private) = opened.as_ref().ok().and_then(|o| o.illustrator_data())
|
||||
&& let Some(Ok(data)) = opened.as_ref().ok().and_then(decoded_copy)
|
||||
{
|
||||
read.0.opened_artboard = vectorcraft_eps::ai_opened_artboard(&private, &read.0);
|
||||
read.0.opened_artboard = vectorcraft_eps::ai_opened_artboard_decoded(&data, &read.0);
|
||||
}
|
||||
read
|
||||
}
|
||||
|
||||
@@ -82,6 +82,60 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() {
|
||||
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]);
|
||||
}
|
||||
|
||||
/// The sample `.ai` with its private data `private` cut into streams of `size` bytes, each
|
||||
/// deflated on its own, and `content` more in its page's content stream dictionary.
|
||||
fn deflated_streams(private: &[u8], size: usize, content: &str) -> Vec<u8> {
|
||||
let parts: Vec<Vec<u8>> = private
|
||||
.chunks(size)
|
||||
.map(|part| {
|
||||
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
e.write_all(part).unwrap();
|
||||
e.finish().unwrap()
|
||||
})
|
||||
.collect();
|
||||
let parts: Vec<&[u8]> = parts.iter().map(Vec::as_slice).collect();
|
||||
ai::ai_with_parts(&parts, ai::page_pdf(), content, "/Filter /FlateDecode ")
|
||||
}
|
||||
|
||||
/// A `.ai` whose private data streams are cut inside the compression's marker and inside the
|
||||
/// compressed data opens with its layers.
|
||||
#[test]
|
||||
fn ai_private_data_cut_anywhere_opens_with_its_layers() {
|
||||
let private = compressed(&ai::sample_data());
|
||||
for size in [7, 1000] {
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "art.ai", &deflated_streams(&private, size, ""), json!({})).unwrap();
|
||||
assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("weren't read")), "{r}");
|
||||
check_sample(&s);
|
||||
}
|
||||
}
|
||||
|
||||
/// A `.ai` whose private data streams hold more than 256 MiB, once their own compression is undone,
|
||||
/// opens with its layers when the editing data they hold is within the limit on it, also when its
|
||||
/// PDF part can't be read (#4366): the streams are read one after the other as the data is
|
||||
/// decoded, without a limit of their own.
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
#[test]
|
||||
fn ai_private_data_past_256_mib_opens_with_its_layers() {
|
||||
let data = ai::sample_data();
|
||||
let at = data.windows(13).position(|w| w == b"%%PageTrailer").unwrap();
|
||||
// A comment line the reader skips, so the data stays valid while it grows past 256 MiB.
|
||||
let mut program = Vec::with_capacity(data.len() + (257 << 20));
|
||||
program.extend_from_slice(&data[..at]);
|
||||
program.push(b'%');
|
||||
program.resize(at + (257 << 20), b'x');
|
||||
program.push(b'\n');
|
||||
program.extend_from_slice(&data[at..]);
|
||||
for content in ["", REFUSED_CONTENT] {
|
||||
let file = deflated_streams(&program, 64 << 20, content);
|
||||
assert!(file.len() < 4 << 20, "the filler deflates");
|
||||
let mut s = Session::new();
|
||||
let r = open(&mut s, "art.ai", &file, json!({})).unwrap();
|
||||
assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("weren't read")), "{content}: {r}");
|
||||
check_sample(&s);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opening a `.ai` or a PDF whose PDF part reads, or a `.ai` saved without PDF compatibility,
|
||||
/// reads and checks the file once, on any thread, for the document it may carry, its pages, its
|
||||
/// editing data and its File Info, with pages picked or not.
|
||||
|
||||
@@ -4913,6 +4913,53 @@ proptest! {
|
||||
prop_assert!(!opened);
|
||||
}
|
||||
|
||||
/// A `.ai` whose private data is cut into streams anywhere, each deflated or not and some
|
||||
/// damaged, opens or is refused without a panic, and its streams read one after the other give
|
||||
/// what joining them gives.
|
||||
#[test]
|
||||
fn ai_private_data_cut_into_streams_anywhere_never_panics(
|
||||
sizes in prop::collection::vec(1usize..400, 1..6),
|
||||
damage in prop::collection::vec((0usize..4_000, any::<u8>()), 0..4),
|
||||
deflate in any::<bool>(),
|
||||
) {
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&editing_text())].concat();
|
||||
let mut parts: Vec<Vec<u8>> = vec![];
|
||||
let mut rest = private.as_slice();
|
||||
for size in sizes.iter().cycle() {
|
||||
if rest.is_empty() {
|
||||
break;
|
||||
}
|
||||
let (part, after) = rest.split_at((*size).min(rest.len()));
|
||||
parts.push(if deflate { deflated(part) } else { part.to_vec() });
|
||||
rest = after;
|
||||
}
|
||||
let total: usize = parts.iter().map(Vec::len).sum();
|
||||
for (at, b) in damage {
|
||||
let mut at = at % total.max(1);
|
||||
for part in &mut parts {
|
||||
if let Some(x) = part.get_mut(at) {
|
||||
*x = b;
|
||||
break;
|
||||
}
|
||||
at -= part.len();
|
||||
}
|
||||
}
|
||||
let parts: Vec<&[u8]> = parts.iter().map(Vec::as_slice).collect();
|
||||
let filter = if deflate { "/Filter /FlateDecode " } else { "" };
|
||||
let bytes = vectorcraft_testkit::ai::ai_with_parts(&parts, vectorcraft_testkit::ai::page_pdf(), "", filter);
|
||||
let read_all = |r: &mut dyn std::io::Read| {
|
||||
let mut data = vec![];
|
||||
r.read_to_end(&mut data).map(|_| data).map_err(|e| e.to_string())
|
||||
};
|
||||
let (joined, streamed) = catch_quiet(|| {
|
||||
let opened = vectorcraft_pdf::open_pdf(&bytes, None).ok();
|
||||
(opened.as_ref().and_then(|o| o.illustrator_data()), opened.as_ref().and_then(|o| o.read_illustrator_data(read_all)))
|
||||
})
|
||||
.expect("the private data read panicked");
|
||||
prop_assert_eq!(streamed, joined.map(Ok));
|
||||
survive("a .ai whose private data is cut into streams", || vectorcraft_engine::cmd::fileio::load("x.ai", &bytes).ok().map(|l| l.doc))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose strokes have any width (0, which draws a hairline, negative, huge, not a number) on a
|
||||
/// path, on a gradient-filled path that `1 BB` strokes and on type in any rendering mode,
|
||||
/// damaged or hostile.
|
||||
|
||||
@@ -103,7 +103,10 @@ pub(crate) use ai::{
|
||||
parsed_type_color, read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number,
|
||||
};
|
||||
pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version};
|
||||
pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from};
|
||||
pub use native::{
|
||||
AiLayers, ai_alone, ai_alone_decoded, ai_alone_on_page, ai_alone_on_page_decoded, ai_alone_with, ai_layers_alone, ai_layers_alone_decoded,
|
||||
ai_opened_artboard, ai_opened_artboard_decoded, decode_ai_private, is_loss, layered_ai, layered_ai_from,
|
||||
};
|
||||
pub(crate) use native::{MAX_TEXT, MAX_WRAP_WORK, scale_document, scale_symbols};
|
||||
pub use text::family_style;
|
||||
pub(crate) use text::{document_font, postscript_face};
|
||||
|
||||
+108
-23
@@ -6,8 +6,8 @@
|
||||
//! `%AI24_DataStream` (Zstandard) or `%AI9_DataStream` (zlib) and the compressed data as ASCII85
|
||||
//! on comment lines, up to `%AI9_PrivateDataEnd`. Data that isn't compressed follows the header
|
||||
//! as it is.
|
||||
//! - In a `.ai` file the streams joined start with `%AI24_ZStandard_Data` (Zstandard) or
|
||||
//! `%AI12_CompressedData` (zlib), else are the data itself ([`decode_private`]).
|
||||
//! - In a `.ai` file the streams, read one after the other, start with `%AI24_ZStandard_Data`
|
||||
//! (Zstandard) or `%AI12_CompressedData` (zlib), else are the data itself ([`decode_private_from`]).
|
||||
//!
|
||||
//! The data is a PostScript-like program of the legacy Illustrator format's operators (layers,
|
||||
//! groups, paths, colours, gradients, images) with newer ones (transparency, hidden objects) and
|
||||
@@ -174,25 +174,89 @@ fn eps_section(section: &[u8]) -> Result<Vec<u8>, String> {
|
||||
}
|
||||
let packed = ps::ascii85_decode(&text).ok_or_else(|| damaged("its ASCII85 encoding"))?;
|
||||
let mut data = header;
|
||||
data.extend(codec.decode(&packed, max_data().saturating_sub(data.len() as u64))?);
|
||||
data.extend(codec.decode(packed.as_slice(), max_data().saturating_sub(data.len() as u64))?);
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// The editing data of a `.ai` file: its `AIPrivateData` streams joined (`raw`), decompressed. The
|
||||
/// compressed data may follow header comments that aren't.
|
||||
/// The markers the compressed editing data of a `.ai` file follows, with its compression.
|
||||
const PRIVATE_MARKERS: [(&[u8], Codec); 2] = [(b"%AI24_ZStandard_Data", Codec::Zstd), (b"%AI12_CompressedData", Codec::Zlib)];
|
||||
|
||||
/// The editing data of a `.ai` file: its `AIPrivateData` streams joined (`raw`), decompressed, as
|
||||
/// [`decode_private_from`] reads them.
|
||||
pub fn decode_private(raw: &[u8]) -> Result<Vec<u8>, String> {
|
||||
if raw.len() as u64 > max_data() {
|
||||
decode_private_from(raw)
|
||||
}
|
||||
|
||||
/// The editing data of a `.ai` file, read from its `AIPrivateData` streams one after the other
|
||||
/// (`raw`) and decompressed as it is read: the streams are never joined in memory. The compressed
|
||||
/// data follows the first [`PRIVATE_MARKERS`] marker, which may follow header comments that aren't
|
||||
/// compressed; without a marker the streams are the data itself. The data decompresses to at most
|
||||
/// [`max_data`] bytes, and at most [`max_encoded`] bytes are read from `raw`.
|
||||
pub fn decode_private_from(raw: impl std::io::Read) -> Result<Vec<u8>, String> {
|
||||
decode_private_within(raw, max_encoded())
|
||||
}
|
||||
|
||||
/// [`decode_private_from`], reading at most `most` bytes of `raw`.
|
||||
fn decode_private_within(raw: impl std::io::Read, most: u64) -> Result<Vec<u8>, String> {
|
||||
let mut counted = Counted { inner: raw.take(most + 1), read: 0 };
|
||||
let data = private_from(&mut counted);
|
||||
if counted.read > most {
|
||||
return Err(too_large());
|
||||
}
|
||||
for (marker, codec) in [(&b"%AI24_ZStandard_Data"[..], Codec::Zstd), (b"%AI12_CompressedData", Codec::Zlib)] {
|
||||
if let Some(at) = find(raw, marker) {
|
||||
let (header, body) = raw.split_at(at);
|
||||
let mut data = header.to_vec();
|
||||
data.extend(codec.decode(body.get(marker.len()..).unwrap_or_default(), max_data().saturating_sub(header.len() as u64))?);
|
||||
data
|
||||
}
|
||||
|
||||
/// Most bytes of a `.ai` file's editing data streams read ([`decode_private_from`]): [`max_data`]
|
||||
/// and a sixteenth more. Compressed data that decompresses to at most [`max_data`] bytes takes no
|
||||
/// more than that: the compression's own block headers add a few bytes in 64 KiB, and only zero
|
||||
/// padding or blocks that hold nothing would go past it.
|
||||
fn max_encoded() -> u64 {
|
||||
max_data().saturating_add(max_data() >> 4)
|
||||
}
|
||||
|
||||
/// [`decode_private_from`] of `raw`, with no limit on what it reads of `raw`.
|
||||
fn private_from(raw: impl std::io::Read) -> Result<Vec<u8>, String> {
|
||||
use std::io::BufRead as _;
|
||||
let longest = PRIVATE_MARKERS.iter().map(|(m, _)| m.len()).max().unwrap_or(0);
|
||||
let mut src = std::io::BufReader::with_capacity(64 << 10, raw);
|
||||
let mut data = Vec::new();
|
||||
loop {
|
||||
let buf = src.fill_buf().map_err(|e| e.to_string())?;
|
||||
if buf.is_empty() {
|
||||
return Ok(data);
|
||||
}
|
||||
let (read, from) = (buf.len(), data.len().saturating_sub(longest - 1));
|
||||
data.extend_from_slice(buf);
|
||||
src.consume(read);
|
||||
let tail = data.get(from..).unwrap_or_default();
|
||||
let marker = PRIVATE_MARKERS.iter().filter_map(|&(m, codec)| Some((from + find(tail, m)?, m.len(), codec))).min_by_key(|&(at, ..)| at);
|
||||
if let Some((at, len, codec)) = marker {
|
||||
if at as u64 > max_data() {
|
||||
return Err(too_large());
|
||||
}
|
||||
let body = data.split_off(at + len);
|
||||
data.truncate(at);
|
||||
data.extend(codec.decode(std::io::Cursor::new(body).chain(src), max_data() - at as u64)?);
|
||||
return Ok(data);
|
||||
}
|
||||
if data.len() as u64 > max_data() {
|
||||
return Err(too_large());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A reader that counts the bytes read from `inner`.
|
||||
struct Counted<R> {
|
||||
inner: R,
|
||||
read: u64,
|
||||
}
|
||||
|
||||
impl<R: std::io::Read> std::io::Read for Counted<R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let n = self.inner.read(buf)?;
|
||||
self.read = self.read.saturating_add(n as u64);
|
||||
Ok(n)
|
||||
}
|
||||
Ok(raw.to_vec())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -203,7 +267,8 @@ enum Codec {
|
||||
|
||||
impl Codec {
|
||||
/// `data` decompressed, at most `max` bytes.
|
||||
fn decode(self, data: &[u8], max: u64) -> Result<Vec<u8>, String> {
|
||||
fn decode(self, data: impl std::io::Read, max: u64) -> Result<Vec<u8>, String> {
|
||||
use std::io::BufRead as _;
|
||||
let mut out = Vec::new();
|
||||
match self {
|
||||
Codec::Zlib => {
|
||||
@@ -212,24 +277,44 @@ impl Codec {
|
||||
Codec::Zstd => {
|
||||
// The data may be several frames one after the other, padded with zeros. A frame
|
||||
// can itself end in a zero byte, so the padding is what is left after the last frame.
|
||||
let mut src = data;
|
||||
let zstd_damaged = || damaged("its Zstandard compression");
|
||||
let mut src = std::io::BufReader::new(data);
|
||||
let mut frames = 0usize;
|
||||
while src.iter().any(|b| {
|
||||
#[cfg(test)]
|
||||
PADDING_LOOKS.set(PADDING_LOOKS.get().saturating_add(1));
|
||||
*b != 0
|
||||
}) {
|
||||
loop {
|
||||
// Zeros before a frame aren't padding: the frame that would start there is damaged.
|
||||
let mut after_zeros = false;
|
||||
loop {
|
||||
let buf = src.fill_buf().map_err(|_| zstd_damaged())?;
|
||||
let Some(&first) = buf.first() else { break };
|
||||
#[cfg(test)]
|
||||
PADDING_LOOKS.set(PADDING_LOOKS.get().saturating_add(1));
|
||||
if first != 0 {
|
||||
break;
|
||||
}
|
||||
let zeros = buf.iter().position(|b| *b != 0);
|
||||
#[cfg(test)]
|
||||
PADDING_LOOKS.set(PADDING_LOOKS.get().saturating_add(zeros.unwrap_or(buf.len()) as u64));
|
||||
// (Zeros that end a buffer may go on in the next one, or end the data.)
|
||||
after_zeros = true;
|
||||
let n = zeros.unwrap_or(buf.len());
|
||||
src.consume(n);
|
||||
}
|
||||
if src.fill_buf().map_err(|_| zstd_damaged())?.is_empty() {
|
||||
break;
|
||||
}
|
||||
frames += 1;
|
||||
if frames > MAX_FRAMES {
|
||||
return Err(damaged("its Zstandard compression"));
|
||||
return Err(zstd_damaged());
|
||||
}
|
||||
let left = (max + 1).saturating_sub(out.len() as u64);
|
||||
if left == 0 {
|
||||
break;
|
||||
}
|
||||
let d = ruzstd::decoding::StreamingDecoder::new_with_max_window_size(&mut src, MAX_ZSTD_WINDOW)
|
||||
.map_err(|_| damaged("its Zstandard compression"))?;
|
||||
d.take(left).read_to_end(&mut out).map_err(|_| damaged("its Zstandard compression"))?;
|
||||
if after_zeros {
|
||||
return Err(zstd_damaged());
|
||||
}
|
||||
let d = ruzstd::decoding::StreamingDecoder::new_with_max_window_size(&mut src, MAX_ZSTD_WINDOW).map_err(|_| zstd_damaged())?;
|
||||
d.take(left).read_to_end(&mut out).map_err(|_| zstd_damaged())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6618,6 +6618,72 @@ fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A reader that gives at most `.1` bytes of `.0` at a time, as private data streams read one after
|
||||
/// the other give them.
|
||||
struct Trickle<'a>(&'a [u8], usize);
|
||||
|
||||
impl std::io::Read for Trickle<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let n = buf.len().min(self.1).min(self.0.len());
|
||||
let (now, rest) = self.0.split_at(n);
|
||||
buf[..n].copy_from_slice(now);
|
||||
self.0 = rest;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
/// The editing data decoded as it is read gives what decoding it whole gives, whatever the size of
|
||||
/// the reads: the compression's marker, its header and its frames may be split between them.
|
||||
#[test]
|
||||
fn editing_data_decoded_as_it_is_read_is_the_data_decoded_whole() {
|
||||
let body = stream(&layer(""));
|
||||
let body = body.as_bytes();
|
||||
let header = b"%%BoundingBox: 0 0 1 1\r\n";
|
||||
let frame = [0x28, 0xB5, 0x2F, 0xFD, 0x20, 3, 0x19, 0, 0, b'a', b'b', 0];
|
||||
for raw in [
|
||||
[&b"%AI24_ZStandard_Data"[..], &zstd(body)].concat(),
|
||||
[&header[..], b"%AI12_CompressedData", &crate::ps::deflate(body)].concat(),
|
||||
[&b"%AI24_ZStandard_Data"[..], &frame, &frame, &[0; 64]].concat(),
|
||||
body.to_vec(),
|
||||
] {
|
||||
let whole = decode_private(&raw).unwrap();
|
||||
for step in [1, 3, 7, 19, 64 << 10] {
|
||||
assert_eq!(decode_private_from(Trickle(&raw, step)).unwrap(), whole, "{step} bytes at a time");
|
||||
}
|
||||
}
|
||||
let zeros_between = [&b"%AI24_ZStandard_Data"[..], &frame, &[0; 4], &frame].concat();
|
||||
for damaged in [&b"%AI12_CompressedDataxx"[..], &zeros_between] {
|
||||
assert!(decode_private(damaged).is_err());
|
||||
for step in 1..=damaged.len() {
|
||||
assert!(decode_private_from(Trickle(damaged, step)).is_err(), "{step} bytes at a time");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first marker read is the one the compressed data follows: the other marker's bytes after it
|
||||
/// are not a marker.
|
||||
#[test]
|
||||
fn editing_data_is_decoded_after_the_first_marker() {
|
||||
let body = stream(&layer(""));
|
||||
let mut raw = [&b"%AI12_CompressedData"[..], &crate::ps::deflate(body.as_bytes())].concat();
|
||||
let data = decode_private(&raw).unwrap();
|
||||
// Bytes after the end of the zlib data aren't read.
|
||||
raw.extend_from_slice(b"%AI24_ZStandard_Data");
|
||||
assert_eq!(decode_private(&raw).unwrap(), data);
|
||||
}
|
||||
|
||||
/// Of the editing data's streams, no more is read than the limit: data that goes on past it is
|
||||
/// refused as too large, even where all it holds past the limit is zero padding.
|
||||
#[test]
|
||||
fn no_more_of_the_private_data_streams_is_read_than_the_limit() {
|
||||
let frame = [0x28, 0xB5, 0x2F, 0xFD, 0x20, 3, 0x19, 0, 0, b'a', b'b', 0];
|
||||
let raw = [&b"%AI24_ZStandard_Data"[..], &frame, &[0; 100]].concat();
|
||||
let most = raw.len() as u64;
|
||||
assert_eq!(decode_private_within(raw.as_slice(), most).unwrap(), b"ab\0");
|
||||
assert_eq!(decode_private_within(raw.as_slice(), most - 1), Err(too_large()));
|
||||
assert_eq!(max_encoded(), max_data() + max_data() / 16);
|
||||
}
|
||||
|
||||
/// A `]` without its `[` looks at a few operand stack slots, not at every slot below it: hundreds
|
||||
/// of thousands of them look at no more than four slots each.
|
||||
#[test]
|
||||
|
||||
@@ -58,7 +58,10 @@ pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols};
|
||||
use compare::{
|
||||
MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour,
|
||||
};
|
||||
pub use layers::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, layered_ai, layered_ai_from};
|
||||
pub use layers::{
|
||||
AiLayers, ai_alone, ai_alone_decoded, ai_alone_on_page, ai_alone_on_page_decoded, ai_alone_with, ai_layers_alone, ai_layers_alone_decoded,
|
||||
ai_opened_artboard, ai_opened_artboard_decoded, decode_ai_private, layered_ai, layered_ai_from,
|
||||
};
|
||||
pub(super) use layers::{layered, program_alone};
|
||||
pub(crate) use slots::MAX_TEXT;
|
||||
pub use slots::is_loss;
|
||||
|
||||
@@ -246,7 +246,18 @@ fn holds_type_envelope(nodes: &[Arc<Node>]) -> bool {
|
||||
/// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part
|
||||
/// is imported. `names`: the encoding of names that aren't UTF-8.
|
||||
pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec<String>), AiLayers> {
|
||||
let data = match ai::decode_private(private) {
|
||||
ai_layers_alone_decoded(ai::decode_private(private), pages, unit, names)
|
||||
}
|
||||
|
||||
/// [`ai_layers_alone`] of an editing copy already decoded (`decoded`, as [`decode_ai_private`]
|
||||
/// gives it, or why it can't be).
|
||||
pub fn ai_layers_alone_decoded(
|
||||
decoded: Result<Vec<u8>, String>,
|
||||
pages: &[(f64, f64)],
|
||||
unit: f64,
|
||||
names: ai::NameEncoding,
|
||||
) -> Result<(Document, Vec<String>), AiLayers> {
|
||||
let data = match decoded {
|
||||
Ok(data) => data,
|
||||
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }),
|
||||
};
|
||||
@@ -291,8 +302,21 @@ pub struct AiLayers {
|
||||
impl AiLayers {
|
||||
/// The editing copy `private` (as [`layered_ai`] takes it), decoded.
|
||||
pub fn decode(private: &[u8]) -> Self {
|
||||
Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default() }
|
||||
Self::decoded(ai::decode_private(private))
|
||||
}
|
||||
|
||||
/// An editing copy already decoded (`decoded`, as [`decode_ai_private`] gives it, or why it
|
||||
/// can't be).
|
||||
pub fn decoded(decoded: Result<Vec<u8>, String>) -> Self {
|
||||
Self { data: decoded, structure: None, alone: None, text: Box::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// A `.ai`'s editing copy read from its `AIPrivateData` or `AIPDFPrivateData` streams one after the
|
||||
/// other (`private`), decoded as it is read: the streams aren't joined first, so they are under the
|
||||
/// limits of the decoded data alone.
|
||||
pub fn decode_ai_private(private: impl std::io::Read) -> Result<Vec<u8>, String> {
|
||||
ai::decode_private_from(private)
|
||||
}
|
||||
|
||||
/// The id of the artboard of `doc` that the editing copy `private` (as [`layered_ai`] takes it)
|
||||
@@ -300,8 +324,13 @@ impl AiLayers {
|
||||
/// restored from the document a `.ai` file carries beside that copy: `None` when the copy names
|
||||
/// the first artboard, names none, can't be decoded, or names an artboard `doc` doesn't have.
|
||||
pub fn ai_opened_artboard(private: &[u8], doc: &Document) -> Option<u32> {
|
||||
let data = ai::decode_private(private).ok()?;
|
||||
active_page(ai::active_artboard(&data), doc)
|
||||
ai_opened_artboard_decoded(&ai::decode_private(private).ok()?, doc)
|
||||
}
|
||||
|
||||
/// [`ai_opened_artboard`] of an editing copy already decoded (`data`, as [`decode_ai_private`]
|
||||
/// gives it).
|
||||
pub fn ai_opened_artboard_decoded(data: &[u8], doc: &Document) -> Option<u32> {
|
||||
active_page(ai::active_artboard(data), doc)
|
||||
}
|
||||
|
||||
/// `doc` (a file read as its page or PDF part, in place of its layers) with the variables, data
|
||||
@@ -586,8 +615,12 @@ pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec<String>), String> {
|
||||
|
||||
/// [`ai_alone`], with the names that aren't UTF-8 read in `names`.
|
||||
pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
|
||||
let data = ai::decode_private(private)?;
|
||||
build_from(ai::read_in(&data, true, names)?, &data, None, Page::Artboard, false, false, 1.0)
|
||||
ai_alone_decoded(&ai::decode_private(private)?, names)
|
||||
}
|
||||
|
||||
/// [`ai_alone_with`] of an editing copy already decoded (`data`, as [`decode_ai_private`] gives it).
|
||||
pub fn ai_alone_decoded(data: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
|
||||
build_from(ai::read_in(data, true, names)?, data, None, Page::Artboard, false, false, 1.0)
|
||||
}
|
||||
|
||||
/// [`ai_alone`] for a `.ai` whose PDF part can't be read, its first page `page` (width and height)
|
||||
@@ -596,8 +629,13 @@ pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Documen
|
||||
/// large, as [`layered_ai`] reads it. A page turned a quarter (`/Rotate 90`) is measured either
|
||||
/// way round. `names`: the encoding of names that aren't UTF-8.
|
||||
pub fn ai_alone_on_page(private: &[u8], page: (f64, f64), unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
|
||||
let data = ai::decode_private(private)?;
|
||||
build_on_page(&data, page, unit, names)
|
||||
ai_alone_on_page_decoded(&ai::decode_private(private)?, page, unit, names)
|
||||
}
|
||||
|
||||
/// [`ai_alone_on_page`] of an editing copy already decoded (`data`, as [`decode_ai_private`] gives
|
||||
/// it).
|
||||
pub fn ai_alone_on_page_decoded(data: &[u8], page: (f64, f64), unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
|
||||
build_on_page(data, page, unit, names)
|
||||
}
|
||||
|
||||
/// Does the editing data (or a program in the legacy format) have layers?
|
||||
|
||||
@@ -52,8 +52,9 @@ pub use ai_editing::{AiEditingOptions, AiEditingOutput, CREATOR_VERSION, export_
|
||||
#[cfg(any(test, feature = "work-count"))]
|
||||
pub use import::blend_work;
|
||||
pub use import::{
|
||||
AiLayers, Imported, NameEncoding, POSTSCRIPT_ERRORS, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard,
|
||||
family_style, import, import_ai, import_names, import_trusting, import_with, is_loss, layered_ai, layered_ai_from, page,
|
||||
AiLayers, Imported, NameEncoding, POSTSCRIPT_ERRORS, ai_alone, ai_alone_decoded, ai_alone_on_page, ai_alone_on_page_decoded, ai_alone_with,
|
||||
ai_layers_alone, ai_layers_alone_decoded, ai_opened_artboard, ai_opened_artboard_decoded, decode_ai_private, family_style, import, import_ai,
|
||||
import_names, import_trusting, import_with, is_loss, layered_ai, layered_ai_from, page,
|
||||
};
|
||||
pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai, writes_image_mask};
|
||||
pub use print::{PrintFonts, PrintJob, PrintPage, print};
|
||||
|
||||
@@ -92,7 +92,7 @@ pub use output::ActiveProfiles;
|
||||
pub use pages::reads_of;
|
||||
pub use pages::{
|
||||
IllustratorData, Opened, PageInfo, PdfInfo, TrimPages, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info,
|
||||
is_postscript, open_pdf, read_illustrator_data_without_pdf_part,
|
||||
is_postscript, open_pdf, read_illustrator_data_without_pdf_part, read_illustrator_data_without_pdf_part_with,
|
||||
};
|
||||
pub use piece_info::{PRIVATE_CHUNK, PrivateData};
|
||||
pub use post::{THUMBNAIL_SIZE, Thumbnail};
|
||||
|
||||
+137
-28
@@ -278,6 +278,14 @@ impl Opened {
|
||||
private_data(&self.pdf)
|
||||
}
|
||||
|
||||
/// What `read` returns, given the private data of an Illustrator `.ai` as one reader over its
|
||||
/// streams in order, each decoded as it is read and none joined to the others: no limit on its
|
||||
/// size applies but the one `read` keeps. `None` as for [`illustrator_data`](Self::illustrator_data),
|
||||
/// also when a stream turns out not to be readable after `read` has started.
|
||||
pub fn read_illustrator_data<T>(&self, read: impl FnOnce(&mut dyn std::io::Read) -> T) -> Option<T> {
|
||||
streamed_private_data(&self.pdf, read).ok().flatten()
|
||||
}
|
||||
|
||||
/// Does the first page carry an editor's copy of the art, as [`has_illustrator_data`] says?
|
||||
pub fn has_illustrator_data(&self) -> bool {
|
||||
has_private_data_keys(&self.pdf)
|
||||
@@ -502,9 +510,10 @@ pub fn illustrator_data(bytes: &[u8], password: Option<&str>) -> Option<Vec<u8>>
|
||||
/// The private data of a file whose PDF part can't be read ([`illustrator_data_without_pdf_part`]),
|
||||
/// with the size of its first page.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct IllustratorData {
|
||||
/// The private data, as [`illustrator_data`] reads it.
|
||||
pub data: Vec<u8>,
|
||||
pub struct IllustratorData<T = Vec<u8>> {
|
||||
/// The private data, as [`illustrator_data`] reads it, or what was read from it
|
||||
/// ([`read_illustrator_data_without_pdf_part_with`]).
|
||||
pub data: T,
|
||||
/// The size in points of a unit of the first page's user space (its `UserUnit`).
|
||||
pub user_unit: f64,
|
||||
/// The first page's trim box (its crop box when it has none) in points, rotated as the page
|
||||
@@ -526,10 +535,29 @@ pub fn illustrator_data_without_pdf_part(bytes: &[u8], password: Option<&str>) -
|
||||
pub fn read_illustrator_data_without_pdf_part(bytes: &[u8], password: Option<&str>) -> Result<Option<IllustratorData>, String> {
|
||||
let Ok(pdf) = open_structural_with_options(bytes, password, &open_options()) else { return Ok(None) };
|
||||
let Some(data) = read_private_data(&pdf)? else { return Ok(None) };
|
||||
let Some(page) = pdf.pages().first() else { return Ok(None) };
|
||||
Ok(with_first_page(&pdf, data))
|
||||
}
|
||||
|
||||
/// [`read_illustrator_data_without_pdf_part`] with the private data given to `read` as
|
||||
/// [`Opened::read_illustrator_data`] gives it, in place of joined: what `read` returns, with the
|
||||
/// size of the first page. `Err` with why a stream can't be read when one can't, even after `read`
|
||||
/// has started.
|
||||
pub fn read_illustrator_data_without_pdf_part_with<T>(
|
||||
bytes: &[u8],
|
||||
password: Option<&str>,
|
||||
read: impl FnOnce(&mut dyn std::io::Read) -> T,
|
||||
) -> Result<Option<IllustratorData<T>>, String> {
|
||||
let Ok(pdf) = open_structural_with_options(bytes, password, &open_options()) else { return Ok(None) };
|
||||
let Some(data) = streamed_private_data(&pdf, read)? else { return Ok(None) };
|
||||
Ok(with_first_page(&pdf, data))
|
||||
}
|
||||
|
||||
/// `data` read from `pdf`'s private data, with the size of its first page: `None` without a page.
|
||||
fn with_first_page<T>(pdf: &Pdf, data: T) -> Option<IllustratorData<T>> {
|
||||
let page = pdf.pages().first()?;
|
||||
// (The page transform is in points: it applies the `UserUnit`.)
|
||||
let trim = frame(page, CropTo::Trim).1;
|
||||
Ok(Some(IllustratorData { data, user_unit: f64::from(page.user_unit()), trim: (trim.width(), trim.height()) }))
|
||||
Some(IllustratorData { data, user_unit: f64::from(page.user_unit()), trim: (trim.width(), trim.height()) })
|
||||
}
|
||||
|
||||
/// The private data of `pdf`'s first page, as [`illustrator_data`] reads it.
|
||||
@@ -537,24 +565,94 @@ fn private_data(pdf: &Pdf) -> Option<Vec<u8>> {
|
||||
read_private_data(pdf).ok().flatten()
|
||||
}
|
||||
|
||||
/// The dictionary that holds `pdf`'s private data streams (its first page's `PieceInfo`), with the
|
||||
/// key they are numbered after: `AIPrivateData`, else `AIPDFPrivateData`.
|
||||
fn private_streams<'a>(pdf: &'a Pdf) -> Option<(Dict<'a>, &'static str)> {
|
||||
let private = pdf.pages().first()?.raw().get::<Dict<'_>>(b"PieceInfo")?.get::<Dict<'_>>(PRIVATE_DATA_OWNER)?.get::<Dict<'_>>(b"Private")?;
|
||||
let key = if private.contains_key(b"AIPrivateData1") { "AIPrivateData" } else { "AIPDFPrivateData" };
|
||||
Some((private, key))
|
||||
}
|
||||
|
||||
/// Most private data streams read.
|
||||
const MAX_PRIVATE_STREAMS: u32 = 100_000;
|
||||
|
||||
/// [`private_data`], with why a private data stream can't be read ([`inflated`]).
|
||||
fn read_private_data(pdf: &Pdf) -> Result<Option<Vec<u8>>, String> {
|
||||
let Some(private) = pdf
|
||||
.pages()
|
||||
.first()
|
||||
.and_then(|page| page.raw().get::<Dict<'_>>(b"PieceInfo")?.get::<Dict<'_>>(PRIVATE_DATA_OWNER)?.get::<Dict<'_>>(b"Private"))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let key = if private.contains_key(b"AIPrivateData1") { "AIPrivateData" } else { "AIPDFPrivateData" };
|
||||
let Some((private, key)) = private_streams(pdf) else { return Ok(None) };
|
||||
let mut data = vec![];
|
||||
for n in 1..=100_000u32 {
|
||||
for n in 1..=MAX_PRIVATE_STREAMS {
|
||||
let Some(stream) = private.get::<Stream<'_>>(format!("{key}{n}").as_bytes()) else { break };
|
||||
data.extend_from_slice(&inflated(&stream, MAX_PRIVATE - data.len()).map_err(|why| why.to_string())?);
|
||||
}
|
||||
Ok((!data.is_empty()).then_some(data))
|
||||
}
|
||||
|
||||
/// What `read` returns, given the private data of `pdf`'s first page as one reader over its
|
||||
/// streams in order ([`PrivateStreams`]): `Ok(None)` without private data or when its streams hold
|
||||
/// nothing, as [`read_private_data`] gives, and `Err` with why a stream can't be read when one
|
||||
/// can't (in place of what `read` returned).
|
||||
fn streamed_private_data<T>(pdf: &Pdf, read: impl FnOnce(&mut dyn std::io::Read) -> T) -> Result<Option<T>, String> {
|
||||
use std::io::BufRead as _;
|
||||
let Some((private, key)) = private_streams(pdf) else { return Ok(None) };
|
||||
let mut streams = PrivateStreams { private, key, next: 1, current: None, error: None };
|
||||
let mut src = std::io::BufReader::new(&mut streams);
|
||||
let read = match src.fill_buf() {
|
||||
Ok(first) if !first.is_empty() => Some(read(&mut src)),
|
||||
_ => None,
|
||||
};
|
||||
drop(src);
|
||||
match streams.error {
|
||||
Some(why) => Err(why),
|
||||
None => Ok(read),
|
||||
}
|
||||
}
|
||||
|
||||
/// A reader over a `.ai`'s private data streams in order (`{key}1`, `{key}2`, … in `private`, as
|
||||
/// [`read_private_data`] takes them), each checked ([`stream_form`]) and decoded as it is reached.
|
||||
/// Once a stream can't be read, `error` says why and every read fails.
|
||||
struct PrivateStreams<'a> {
|
||||
private: Dict<'a>,
|
||||
key: &'static str,
|
||||
/// The number of the next stream.
|
||||
next: u32,
|
||||
/// The stream being read, decoded.
|
||||
current: Option<Box<dyn std::io::Read + 'a>>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
impl std::io::Read for PrivateStreams<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if buf.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
loop {
|
||||
if let Some(why) = &self.error {
|
||||
return Err(std::io::Error::other(why.clone()));
|
||||
}
|
||||
if let Some(current) = &mut self.current {
|
||||
match current.read(buf) {
|
||||
Ok(0) => self.current = None,
|
||||
Ok(n) => return Ok(n),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
// (Only a deflated stream's decoder fails.)
|
||||
Err(_) => self.error = Some("its zlib compression is damaged".to_string()),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if self.next > MAX_PRIVATE_STREAMS {
|
||||
return Ok(0);
|
||||
}
|
||||
let Some(stream) = self.private.get::<Stream<'_>>(format!("{}{}", self.key, self.next).as_bytes()) else { return Ok(0) };
|
||||
self.next += 1;
|
||||
match stream_form(&stream) {
|
||||
Ok(true) => self.current = Some(Box::new(flate2::read::ZlibDecoder::new(std::io::Cursor::new(stream.raw_data())))),
|
||||
Ok(false) => self.current = Some(Box::new(std::io::Cursor::new(stream.raw_data()))),
|
||||
Err(why) => self.error = Some(why),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does the PDF's first page carry an editor's copy of the art: a PDF-compatible `.ai`
|
||||
/// (`AIPrivateData` keys) or a PDF saved with its editing data (`AIPDFPrivateData`, #1345)? Without
|
||||
/// reading the data. Either's trim boxes are its editor's artboards.
|
||||
@@ -574,8 +672,29 @@ fn has_private_data_keys(pdf: &Pdf) -> bool {
|
||||
/// doesn't know counts as another filter.
|
||||
fn inflated(stream: &Stream<'_>, most: usize) -> Result<Vec<u8>, String> {
|
||||
use std::io::Read;
|
||||
let unread = || "it is stored in a form that isn't read".to_string();
|
||||
let too_large = || format!("it is larger than {} MB", MAX_PRIVATE >> 20);
|
||||
let deflated = stream_form(stream)?;
|
||||
let raw = stream.raw_data();
|
||||
let mut out = vec![];
|
||||
let limit = u64::try_from(most).ok().and_then(|m| m.checked_add(1)).ok_or_else(too_large)?;
|
||||
if deflated {
|
||||
flate2::read::ZlibDecoder::new(&*raw).take(limit).read_to_end(&mut out).map_err(|_| "its zlib compression is damaged".to_string())?;
|
||||
} else if raw.len() <= most {
|
||||
out.extend_from_slice(&raw);
|
||||
} else {
|
||||
return Err(too_large());
|
||||
}
|
||||
if out.len() > most {
|
||||
return Err(too_large());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Is the private data stream `stream` deflated (`true`) or plain (`false`)? `Err` with why it
|
||||
/// isn't read when it is in another form: with decode parameters, or with a filter the reader
|
||||
/// doesn't know (which counts as another filter).
|
||||
fn stream_form(stream: &Stream<'_>) -> Result<bool, String> {
|
||||
let unread = || "it is stored in a form that isn't read".to_string();
|
||||
let dict = stream.dict();
|
||||
let named = |key: &[u8]| match dict.get::<Object<'_>>(key) {
|
||||
None | Some(Object::Null(_)) => Some(0),
|
||||
@@ -596,21 +715,11 @@ fn inflated(stream: &Stream<'_>, most: usize) -> Result<Vec<u8>, String> {
|
||||
if named(b"Filter").zip(named(b"F")).is_none_or(|(a, b)| a.max(b) != filters.len()) {
|
||||
return Err(unread());
|
||||
}
|
||||
let raw = stream.raw_data();
|
||||
let mut out = vec![];
|
||||
let limit = u64::try_from(most).ok().and_then(|m| m.checked_add(1)).ok_or_else(too_large)?;
|
||||
match filters.as_slice() {
|
||||
[] if raw.len() <= most => out.extend_from_slice(&raw),
|
||||
[] => return Err(too_large()),
|
||||
[craft::pdf::syntax::Filter::FlateDecode] => {
|
||||
flate2::read::ZlibDecoder::new(&*raw).take(limit).read_to_end(&mut out).map_err(|_| "its zlib compression is damaged".to_string())?;
|
||||
}
|
||||
_ => return Err(unread()),
|
||||
[] => Ok(false),
|
||||
[craft::pdf::syntax::Filter::FlateDecode] => Ok(true),
|
||||
_ => Err(unread()),
|
||||
}
|
||||
if out.len() > most {
|
||||
return Err(too_large());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Does `page` carry an editor's private data (`PieceInfo` keys starting with `AIPrivateData`)?
|
||||
|
||||
@@ -458,6 +458,43 @@ fn private_data_reads_without_a_pdf_part_that_cant_be_read() {
|
||||
assert_eq!(read_illustrator_data_without_pdf_part(b"not a pdf", None), Ok(None));
|
||||
}
|
||||
|
||||
/// The private data streams read one after the other, each decoded as it is reached, give what
|
||||
/// joining them gives, with the same refusals: a stream in a form that isn't read, or with damaged
|
||||
/// zlib data, stops the read with why (also after the streams before it were read), and streams
|
||||
/// that hold nothing are no private data.
|
||||
#[test]
|
||||
fn private_data_streams_read_one_after_the_other_as_when_joined() {
|
||||
let (a, b) = (first_extra(1), first_extra(1) + 1);
|
||||
let page = PdfPage {
|
||||
entries: format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {a} 0 R /AIPrivateData2 {b} 0 R /NumBlock 2 >> >> >>"),
|
||||
..PdfPage::new(100.0, 100.0, "1 0 0 rg 10 10 30 30 re f")
|
||||
};
|
||||
let file = |streams: &[&str]| pdf_with_catalog(std::slice::from_ref(&page), streams, "", None);
|
||||
let read_all = |r: &mut dyn std::io::Read| {
|
||||
let mut data = vec![];
|
||||
r.read_to_end(&mut data).map(|_| data).map_err(|e| e.to_string())
|
||||
};
|
||||
let streamed = |pdf: &[u8]| read_illustrator_data_without_pdf_part_with(pdf, None, read_all);
|
||||
// (A file the import refuses has no PDF part to read the data of.)
|
||||
let opened = |pdf: &[u8]| open_pdf(pdf, None).ok().and_then(|o| o.read_illustrator_data(read_all));
|
||||
let (one, two) = (stream("", "%AI24_ZStandard_Data first "), stream("", "second"));
|
||||
let whole = file(&[&one, &two]);
|
||||
let joined = b"%AI24_ZStandard_Data first second".to_vec();
|
||||
assert_eq!(streamed(&whole), Ok(Some(IllustratorData { data: Ok(joined.clone()), user_unit: 1.0, trim: (100.0, 100.0) })));
|
||||
assert_eq!(opened(&whole), Some(Ok(joined)));
|
||||
assert_eq!(streamed(b"not a pdf"), Ok(None));
|
||||
for odd in ["/Filter /Bogus", "/DecodeParms << /Predictor 12 /Columns 0 >>"] {
|
||||
let pdf = file(&[&one, &stream(odd, "second")]);
|
||||
assert_eq!(streamed(&pdf), Err("it is stored in a form that isn't read".to_string()), "{odd}");
|
||||
assert_eq!(opened(&pdf), None, "{odd}");
|
||||
}
|
||||
let damaged = file(&[&one, &stream("/Filter /FlateDecode", "not zlib")]);
|
||||
assert_eq!(streamed(&damaged), Err("its zlib compression is damaged".to_string()));
|
||||
assert_eq!(opened(&damaged), None);
|
||||
let empty = file(&[&stream("", ""), &stream("", "")]);
|
||||
assert_eq!((illustrator_data(&empty, None), streamed(&empty), opened(&empty)), (None, Ok(None), None));
|
||||
}
|
||||
|
||||
/// Art in ordinary tags nested inside a layer's sequence goes to that layer; the group is kept
|
||||
/// with each level, not searched for through the tags for each object.
|
||||
#[test]
|
||||
|
||||
@@ -344,6 +344,14 @@ pub fn ai_with_private_streams(private: &[u8], page: &str, content: &str, stream
|
||||
with_private_streams(private, page, "AIPrivateData", "", content, streams)
|
||||
}
|
||||
|
||||
/// [`ai`] with its private data in `parts`, one stream each in order (`AIPrivateData1`,
|
||||
/// `AIPrivateData2`, …), each written as given with `streams` more in its dictionary
|
||||
/// (`/Filter /FlateDecode ` for parts already deflated), and `content` more in the dictionary of
|
||||
/// the page's content stream, as [`ai_with_content`].
|
||||
pub fn ai_with_parts(parts: &[&[u8]], page: &str, content: &str, streams: &str) -> Vec<u8> {
|
||||
with_parts(parts, page, "AIPrivateData", "", content, streams)
|
||||
}
|
||||
|
||||
/// A PDF saved with Illustrator's editing data: [`ai`]'s file with the two streams under
|
||||
/// `AIPDFPrivateData1` and `AIPDFPrivateData2`. These key names were seen in the PDF attached to
|
||||
/// #868, and nothing else of that file is used; ExifTool's PDF tag table lists them too
|
||||
@@ -366,25 +374,32 @@ fn with_private(private: &[u8], page: &str, key: &str, entries: &str, content: &
|
||||
/// [`with_private`] with `streams` more in each private data stream's dictionary.
|
||||
fn with_private_streams(private: &[u8], page: &str, key: &str, entries: &str, content: &str, streams: &str) -> Vec<u8> {
|
||||
let (first, second) = private.split_at(private.len() / 2);
|
||||
with_parts(&[first, second], page, key, entries, content, streams)
|
||||
}
|
||||
|
||||
/// [`with_private_streams`] with the private data in `parts`, one stream each, under `{key}1`,
|
||||
/// `{key}2`, ….
|
||||
fn with_parts(parts: &[&[u8]], page: &str, key: &str, entries: &str, content: &str, streams: &str) -> Vec<u8> {
|
||||
let stream = |part: &[u8], more: &str| {
|
||||
let mut s = format!("<< /Length {} {more}>>\nstream\n", part.len()).into_bytes();
|
||||
s.extend_from_slice(part);
|
||||
s.extend_from_slice(b"\nendstream");
|
||||
s
|
||||
};
|
||||
let objects: Vec<Vec<u8>> = vec![
|
||||
let refs: String = (0..parts.len()).map(|i| format!("/{key}{} {} 0 R ", i + 1, i + 5)).collect();
|
||||
let mut objects: Vec<Vec<u8>> = vec![
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
|
||||
format!(
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] {entries} /Contents 4 0 R \
|
||||
/Resources << /Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >> >> \
|
||||
/PieceInfo << /{PIECE} << /Private << /{key}1 5 0 R /{key}2 6 0 R /NumBlock 2 >> >> >> >>"
|
||||
/PieceInfo << /{PIECE} << /Private << {refs}/NumBlock {} >> >> >> >>",
|
||||
parts.len()
|
||||
)
|
||||
.into_bytes(),
|
||||
stream(page.as_bytes(), content),
|
||||
stream(first, streams),
|
||||
stream(second, streams),
|
||||
];
|
||||
objects.extend(parts.iter().map(|part| stream(part, streams)));
|
||||
let mut out = b"%PDF-1.5\n".to_vec();
|
||||
let mut offsets = vec![];
|
||||
for (i, o) in objects.iter().enumerate() {
|
||||
|
||||
Reference in new issue
Block a user