mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 02:09:00 +00:00
craft-cdr: refuse previews that preview cannot read whole
preview now reads a DISP chunk only when its first 4 bytes are 08 00 00 00 (every DISP chunk in the sample files starts so) and its bitmap has a 40-byte info header, a plane count of 1 and uncompressed pixels: compression 0 at 1, 4, 8, 16, 24 or 32 bits, or compression 3 (color masks) at 16 or 32 bits, as the bitmap info header page states. A color table may not hold more than 2^bit count colors, and the image size must be 0 or the rows' size, as in every sample. Other bit counts with those compressions fail as damaged; other header lengths and compressions are refused as unsupported. A DISP chunk of another kind, or a bitmap with another header length or compression, is passed over, and a file with no later DISP bitmap that preview reads is refused as unsupported. Before this, a bit count of 0, compression 6 or a header of another length gave a BMP file whose pixel offset was wrong, and the rows were checked only for compressions 0 and 3. The row size is now computed in 64 bits, so 32-bit targets accept the same bitmaps as 64-bit ones. The BMP file ends with the last row: bytes after it in the chunk are left out, and the file's memory is reserved fallibly. A RIFF file without a DISP bitmap now gives Ok(None) only when its last chunk ends where the form's length says, inside the file. A chunk that runs past the form, a partial chunk header at the end, a file cut short or a form length too short for the form type fails as damaged, since the missing bytes may hold the picture. A file cut short still gives a DISP chunk it holds whole. A version 2 file keeps a 1-bit picture (R40) that preview does not read, so preview refuses it as unsupported instead of reporting no picture. Version 1 still gives Ok(None). Tests cover each of these cases, a package that holds both thumbnail members, and the package member count limit. The hostile-input property tests in tests/it/read.rs now also run preview, including deflated thumbnail members and a compressed list before the DISP chunk, and check that a package without a picture member gives Ok(None) whatever its damaged drawing holds. The README and the preview doc comment say that preview does not check the drawing's version. PROVENANCE.md row R76 records that no sample package's RIFF stream has a DISP chunk, and the crate description mentions the preview.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-cdr"
|
||||
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers"
|
||||
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -24,7 +24,7 @@ Sources:
|
||||
https://pronom.nationalarchives.gov.uk/fmt/467.xml,
|
||||
https://pronom.nationalarchives.gov.uk/fmt/466.xml and
|
||||
https://pronom.nationalarchives.gov.uk/fmt/465.xml
|
||||
- **G**: the Windows GDI reference pages for the BMP file header and the bitmap info header,
|
||||
- **G**: the reference pages for the BMP file header and the bitmap info header,
|
||||
https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapfileheader and
|
||||
https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader
|
||||
- **S**: own inspection of the bytes of public sample files, checked against the picture each file
|
||||
@@ -91,8 +91,8 @@ file is committed.
|
||||
| R24 | ZIP: the end of central directory record (signature `PK\5\6`, 22 bytes and a comment of up to 65,535 bytes) gives the member count and where the central directory lies; each central directory entry (46 bytes, then name, extra field and comment) gives the flags, method, CRC-32, sizes and its local header; a local header is 30 bytes, then its name and extra field, then the member's bytes. Flag bit 0 marks an encrypted member; method 0 is stored and 8 deflated; 0xFFFF and 0xFFFFFFFF mark ZIP64 fields, and a ZIP64 locator (`PK\6\7`, 20 bytes) precedes the end record of a ZIP64 archive; disk numbers other than 0 mark an archive split across files | Z 4.3.7, 4.3.12, 4.3.15, 4.3.16, 4.4.1.4, 4.4.4, 4.4.5, 4.4.7, 4.4.8, 4.4.13 | public-spec |
|
||||
| R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30 | public-spec |
|
||||
| R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180 | public-spec |
|
||||
| R75 | `DISP`, a chunk of the RIFF form itself, holds the picture of the drawing: 4 bytes, then a bitmap info header (its own length u32, width, height, planes u16, bit count u16, compression u32, image size, two resolutions, the colors used u32, the important colors), then the color table or color masks and the pixels, to the end of the chunk. A BMP file is that bitmap after a 14-byte file header: `BM`, the file length u32, 4 reserved bytes of 0 and the offset of the pixels u32. The color table holds the colors used, or 2^bit count colors when that is 0 at 8 bits or fewer; compression 3 after a 40-byte header puts three u32 masks before the pixels. Uncompressed pixels (compression 0 or 3) are one row for each line of the height, each the width times the bit count rounded up to whole 32-bit words | K L231, L280-L306; G (both pages); S: every RIFF file of versions 4 to 13 in TP, UC, LT, NR, DM and TDF (469 files) has one `DISP`, starting with the bytes `08 00 00 00` and a 40-byte header of 1, 4 or 8 bits, compression 0 and a positive height, whose color table and rows fill the rest of the chunk; the files of version 3 (TP, 9) have none | public-spec (the 4 bytes and where the chunk lies: sample; other header lengths and bit counts: unconfirmed, as no sample has one, and a wrong guess gives a picture that fails to decode) |
|
||||
| R76 | The package holds the picture of the drawing as `metadata/thumbnails/thumbnail.bmp`, a BMP file, in versions 14 to 16, and as `previews/thumbnail.png`, a PNG file, from version 17; each page's picture is beside it (`page1.bmp`, `page1.png` ...) | S: every package of versions 14 to 16 (62) and of 17 to 25 (231) in LT, TP and TDF | sample |
|
||||
| R75 | `DISP`, a chunk of the RIFF form itself, holds the picture of the drawing: 4 bytes, then a bitmap info header (its own length u32, width, height, planes u16, bit count u16, compression u32, image size, two resolutions, the colors used u32, the important colors), then the color table or color masks and the pixels, to the end of the chunk. A BMP file is that bitmap after a 14-byte file header: `BM`, the file length u32, 4 reserved bytes of 0 and the offset of the pixels u32. The color table holds the colors used, at most 2^bit count, or 2^bit count colors when that is 0 at 8 bits or fewer; compression 3 (valid at 16 and 32 bits) puts three u32 masks after the header, before the pixels. The plane count is 1, and the image size is 0 or the rows' size. Uncompressed pixels (compression 0 or 3) are one row for each line of the height, each the width times the bit count rounded up to whole 32-bit words. The reader takes only a `DISP` chunk whose 4 bytes are `08 00 00 00`, with a 40-byte header and compression 0 or 3, and refuses other header lengths and compressions | K L231, L280-L306; G (both pages); S: every RIFF file of versions 4 to 13 in TP, UC, LT, NR, DM and TDF (469 files) has one `DISP`, starting with the bytes `08 00 00 00` and a 40-byte header of 1 plane and 1, 4 or 8 bits, compression 0, a positive height and an image size equal to the rows' size, whose color table and rows fill the rest of the chunk; the files of version 3 (TP, 9) have none | public-spec (the 4 bytes and where the chunk lies: sample; bit counts above 8 and compression 3: unconfirmed, as no sample has one, and a wrong guess gives a picture that fails to decode) |
|
||||
| R76 | The package holds the picture of the drawing as `metadata/thumbnails/thumbnail.bmp`, a BMP file, in versions 14 to 16, and as `previews/thumbnail.png`, a PNG file, from version 17; each page's picture is beside it (`page1.bmp`, `page1.png` ...) ; the package's RIFF stream has no `DISP` chunk | S: every package of versions 14 to 16 (62) and of 17 to 25 (231) in LT, TP and TDF | sample |
|
||||
| R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193 | public-spec |
|
||||
| R28 | Templates have the form type `CDT` and a letter of their own; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | none: no sample template | unconfirmed (a template is read as a drawing of the version its `vrsn` chunk names, and one without that chunk is refused) |
|
||||
| R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; S: LT `square_blackfill_nooutline_roundedcorners_cdr<version>.cdr` of `testset/15` to `testset/25` (flag clear, a share of 0.25) | public-spec (radius share with the flag clear: sample; that the scale is not applied: unconfirmed, as every sample has a scale of 1, and a wrong guess changes only the corners' size) |
|
||||
|
||||
+11
-2
@@ -63,8 +63,17 @@ not a `.cdr` drawing.
|
||||
R75 and R76). In versions 4 to 13 the picture is the `DISP` chunk, returned as a BMP file. In versions
|
||||
14 to 16 it is the package member `metadata/thumbnails/thumbnail.bmp`, and from version 17 on it
|
||||
is `previews/thumbnail.png`. The package's drawing stream is not read, so a package that holds
|
||||
both members gives the PNG. Files of versions 1 to 3 keep no picture. The bytes are returned still
|
||||
encoded, so the caller decodes them within its own image limits.
|
||||
both members gives the PNG. Files of versions 1 and 3 keep no picture. A version 2 file keeps a
|
||||
1-bit picture (R40) that `preview` does not read, so it refuses the file. `preview` does not check
|
||||
the drawing's version, so a RIFF file that `read` refuses for its version, such as one that names a
|
||||
version before 3, still gives its `DISP` picture.
|
||||
|
||||
A `DISP` bitmap must start with the 4 bytes `08 00 00 00`, have a 40-byte info header and be
|
||||
uncompressed (compression 0, or 3 with color masks at 16 or 32 bits). A `DISP` chunk of another
|
||||
kind, or a bitmap with another header length or compression, is passed over without checking the
|
||||
rest of its bytes, and a file with no other `DISP` chunk is refused. A RIFF file without a `DISP` bitmap is refused as damaged when its last chunk does not end
|
||||
where the form's length says the form ends, which includes a file cut short. The bytes are returned
|
||||
still encoded, so the caller decodes them within its own image limits.
|
||||
|
||||
## `.cmx` files
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! packages of versions 14 on with their data streams, then pages, layers, guidelines, groups,
|
||||
//! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. It also reads
|
||||
//! `.cmx` exchange files with 32-bit coordinates ([`read_cmx`]): their pages, layers, groups and
|
||||
//! curves with uniform fills and outlines. [`preview`] gives the picture a `.cdr` file keeps of its
|
||||
//! curves with uniform fills and outlines. [`preview()`] gives the picture a `.cdr` file keeps of its
|
||||
//! drawing, without reading the drawing.
|
||||
//!
|
||||
//! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source
|
||||
@@ -64,7 +64,9 @@ pub enum Error {
|
||||
/// Past one of the [`Limits`].
|
||||
Limit(&'static str),
|
||||
/// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that
|
||||
/// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates.
|
||||
/// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates; a
|
||||
/// `DISP` preview that is not an uncompressed bitmap with a 40-byte header; a version 2 file's
|
||||
/// picture.
|
||||
Unsupported(&'static str),
|
||||
}
|
||||
|
||||
|
||||
+211
-33
@@ -17,6 +17,12 @@ const INFO_LEN: usize = 40;
|
||||
/// (R75).
|
||||
const RGB: u32 = 0;
|
||||
const BITFIELDS: u32 = 3;
|
||||
const COMPRESSED: &str = "compressed previews";
|
||||
const WL_PICTURE: &str = "pictures of version 2 files";
|
||||
const OTHER_HEADER: &str = "preview bitmap headers of other lengths";
|
||||
const OTHER_DISP: &str = "previews of other kinds than a bitmap";
|
||||
/// The lead bytes of every `DISP` chunk in the sample files, before a bitmap (R75).
|
||||
const DISP_BITMAP: [u8; DISP_LEAD] = [8, 0, 0, 0];
|
||||
/// A BMP file header: `BM`, the file length, 4 reserved bytes and where the pixels start (R75).
|
||||
const FILE_HEADER_LEN: usize = 14;
|
||||
/// The package members that hold the drawing's picture (R76), in the order they are looked for.
|
||||
@@ -47,8 +53,12 @@ pub struct Preview<'a> {
|
||||
/// `previews/thumbnail.png` when the package has one (versions 17 on), else
|
||||
/// `metadata/thumbnails/thumbnail.bmp` (versions 14 to 16). The package's drawing stream is not
|
||||
/// read, so the member is chosen by its name, not by the drawing's version. `None` when the file
|
||||
/// keeps no picture, as versions 1 to 3 do. A package member is read within the member and inflate
|
||||
/// limits, and its CRC-32 is checked.
|
||||
/// keeps no picture, as versions 1 and 3 do; the 1-bit picture of a version 2 file is not read, and
|
||||
/// such a file is refused. The drawing's version is not checked, so a RIFF file
|
||||
/// that [`read`](crate::read) refuses for its version still gives its `DISP` picture. A `DISP`
|
||||
/// chunk that is not a bitmap, and a bitmap that is compressed or has another header than the
|
||||
/// 40-byte one, are refused. A package member is read within the member and inflate limits, and its
|
||||
/// CRC-32 is checked.
|
||||
pub fn preview(bytes: &[u8], limits: Limits) -> Result<Option<Preview<'_>>, Error> {
|
||||
if bytes.len() > limits.input {
|
||||
return Err(Error::Limit("input size"));
|
||||
@@ -60,7 +70,8 @@ pub fn preview(bytes: &[u8], limits: Limits) -> Result<Option<Preview<'_>>, Erro
|
||||
return disp(bytes, limits);
|
||||
}
|
||||
if wl::is_wl(bytes) {
|
||||
return Ok(None);
|
||||
// Version 1 (marker `e`) keeps no picture; version 2's 1-bit picture is not read (R40).
|
||||
return if bytes.get(2) == Some(&b'e') { Ok(None) } else { Err(Error::Unsupported(WL_PICTURE)) };
|
||||
}
|
||||
Err(Error::NotCdr)
|
||||
}
|
||||
@@ -83,13 +94,19 @@ fn thumbnail(bytes: &[u8], limits: Limits) -> Result<Option<Preview<'_>>, Error>
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The `DISP` chunk among the RIFF form's own chunks, as a BMP file (R75). A file cut short is
|
||||
/// walked to its end.
|
||||
/// The `DISP` chunk among the RIFF form's own chunks, as a BMP file (R75). A file cut short still
|
||||
/// gives a `DISP` chunk it holds whole. When there is none, the last chunk must end where the form's
|
||||
/// length says the form ends; otherwise the file is damaged.
|
||||
fn disp(bytes: &[u8], limits: Limits) -> Result<Option<Preview<'_>>, Error> {
|
||||
let declared = Rd::at(bytes, 4).u32().ok_or(Error::NotCdr)? as usize;
|
||||
let end = declared.checked_add(8).filter(|e| (12..=bytes.len()).contains(e)).unwrap_or(bytes.len());
|
||||
// A form length past the file is taken to the file's end; one too short for the form type
|
||||
// leaves no chunk to walk.
|
||||
let end = declared.checked_add(8).filter(|e| *e <= bytes.len()).unwrap_or(bytes.len());
|
||||
let mut at: usize = 12;
|
||||
let mut chunks = 0;
|
||||
// Why the last `DISP` chunk passed over was not read: another kind than a bitmap, or a bitmap
|
||||
// this reader does not read.
|
||||
let mut passed: Option<Error> = None;
|
||||
while at.checked_add(8).is_some_and(|h| h <= end) {
|
||||
chunks += 1;
|
||||
if chunks > limits.chunks {
|
||||
@@ -101,12 +118,24 @@ fn disp(bytes: &[u8], limits: Limits) -> Result<Option<Preview<'_>>, Error> {
|
||||
let body = at + 8;
|
||||
if id == DISP {
|
||||
let data = body.checked_add(len).filter(|e| *e <= end).and_then(|e| bytes.get(body..e)).ok_or(Error::Damaged("preview"))?;
|
||||
return Ok(Some(Preview { format: PreviewFormat::Bmp, bytes: Cow::Owned(bmp(data)?) }));
|
||||
match data.get(..DISP_LEAD) {
|
||||
None => return Err(Error::Damaged("preview")),
|
||||
Some(lead) if lead == DISP_BITMAP => match bmp(data) {
|
||||
Ok(b) => return Ok(Some(Preview { format: PreviewFormat::Bmp, bytes: Cow::Owned(b) })),
|
||||
Err(e @ Error::Unsupported(_)) => passed = Some(e),
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
Some(_) => passed = Some(Error::Unsupported(OTHER_DISP)),
|
||||
}
|
||||
}
|
||||
// Chunks are padded to an even length.
|
||||
at = body.saturating_add(len).saturating_add(len & 1);
|
||||
}
|
||||
Ok(None)
|
||||
// A chunk past the end, a partial chunk header or a file cut short may hide a `DISP` chunk.
|
||||
if at > bytes.len() || declared.checked_add(8) != Some(at) {
|
||||
return Err(Error::Damaged("preview"));
|
||||
}
|
||||
passed.map_or(Ok(None), Err)
|
||||
}
|
||||
|
||||
/// The bitmap of a `DISP` body as a BMP file: a file header before its info header, color masks or
|
||||
@@ -116,44 +145,62 @@ fn bmp(disp: &[u8]) -> Result<Vec<u8>, Error> {
|
||||
let dib = disp.get(DISP_LEAD..).ok_or_else(damaged)?;
|
||||
let mut r = Rd::new(dib);
|
||||
let info = r.u32().ok_or_else(damaged)? as usize;
|
||||
// A header too short for its own length field, or longer than the chunk.
|
||||
if info < 4 || info > dib.len() {
|
||||
return Err(damaged());
|
||||
}
|
||||
// Only the 40-byte header is read (R75).
|
||||
if info != INFO_LEN {
|
||||
return Err(Error::Unsupported(OTHER_HEADER));
|
||||
}
|
||||
let (width, height) = (r.i32().ok_or_else(damaged)?, r.i32().ok_or_else(damaged)?);
|
||||
// The planes, then the bit count and compression; the image size and resolution, then the
|
||||
// colors used.
|
||||
r.skip(2).ok_or_else(damaged)?;
|
||||
// The planes, the bit count and compression; the image size and resolution, then the colors
|
||||
// used.
|
||||
let planes = r.u16().ok_or_else(damaged)?;
|
||||
let bits = r.u16().ok_or_else(damaged)?;
|
||||
let compression = r.u32().ok_or_else(damaged)?;
|
||||
r.skip(12).ok_or_else(damaged)?;
|
||||
let size = r.u32().ok_or_else(damaged)?;
|
||||
r.skip(8).ok_or_else(damaged)?;
|
||||
let used = r.u32().ok_or_else(damaged)? as usize;
|
||||
if info < INFO_LEN || info > dib.len() {
|
||||
// Only uncompressed pixels are read: color masks are valid at 16 and 32 bits (R75).
|
||||
match compression {
|
||||
RGB if matches!(bits, 1 | 4 | 8 | 16 | 24 | 32) => {}
|
||||
BITFIELDS if matches!(bits, 16 | 32) => {}
|
||||
RGB | BITFIELDS => return Err(damaged()),
|
||||
_ => return Err(Error::Unsupported(COMPRESSED)),
|
||||
}
|
||||
if planes != 1 {
|
||||
return Err(damaged());
|
||||
}
|
||||
// A table of 2^bits colors when the header names none for 8 bits or fewer.
|
||||
// A table of 2^bits colors when the header names none for 8 bits or fewer, and never more.
|
||||
let colors = if bits <= 8 && used == 0 { 1usize << bits } else { used };
|
||||
let masks = if info == INFO_LEN && compression == BITFIELDS { 12 } else { 0 };
|
||||
if bits < 32 && colors as u64 > 1u64 << bits {
|
||||
return Err(damaged());
|
||||
}
|
||||
// Three masks follow the header.
|
||||
let masks = if compression == BITFIELDS { 12 } else { 0 };
|
||||
let pixels = colors.checked_mul(4).and_then(|t| (FILE_HEADER_LEN + info + masks).checked_add(t)).ok_or_else(damaged)?;
|
||||
let total = FILE_HEADER_LEN + dib.len();
|
||||
if pixels > total {
|
||||
// The pixels are rows of whole 32-bit words, as many as the height says (R75).
|
||||
let width = u64::try_from(width).ok().filter(|w| *w > 0).ok_or_else(damaged)?;
|
||||
if height == 0 {
|
||||
return Err(damaged());
|
||||
}
|
||||
// Uncompressed pixels are rows of whole 32-bit words, as many as the height says (R75).
|
||||
if matches!(compression, RGB | BITFIELDS) {
|
||||
let width = usize::try_from(width).ok().filter(|w| *w > 0).ok_or_else(damaged)?;
|
||||
if !matches!(bits, 1 | 4 | 8 | 16 | 24 | 32) || height == 0 {
|
||||
return Err(damaged());
|
||||
}
|
||||
let stride = width.checked_mul(usize::from(bits)).map(|b| b.div_ceil(32) * 4);
|
||||
let rows = stride.and_then(|s| s.checked_mul(height.unsigned_abs() as usize));
|
||||
if rows.and_then(|n| pixels.checked_add(n)).is_none_or(|e| e > total) {
|
||||
return Err(damaged());
|
||||
}
|
||||
let rows = ((width * u64::from(bits)).div_ceil(32) * 4).checked_mul(u64::from(height.unsigned_abs()));
|
||||
// The image size is 0 or the rows' size.
|
||||
if size != 0 && rows != Some(u64::from(size)) {
|
||||
return Err(damaged());
|
||||
}
|
||||
let (total32, pixels32) = (u32::try_from(total).map_err(|_| damaged())?, u32::try_from(pixels).map_err(|_| damaged())?);
|
||||
let mut out = Vec::with_capacity(total);
|
||||
// The file ends with the last row; bytes after it in the chunk are left out.
|
||||
let end = rows.and_then(|n| n.checked_add(pixels as u64)).filter(|e| *e <= total as u64).ok_or_else(damaged)? as usize;
|
||||
let (end32, pixels32) = (u32::try_from(end).map_err(|_| damaged())?, u32::try_from(pixels).map_err(|_| damaged())?);
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(end).map_err(|_| Error::Limit("preview size"))?;
|
||||
out.extend(BMP_SIGNATURE);
|
||||
out.extend(total32.to_le_bytes());
|
||||
out.extend(end32.to_le_bytes());
|
||||
out.extend([0; 4]);
|
||||
out.extend(pixels32.to_le_bytes());
|
||||
out.extend(dib);
|
||||
out.extend(dib.get(..end - FILE_HEADER_LEN).ok_or_else(damaged)?);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -218,6 +265,13 @@ mod tests {
|
||||
let colors = if used == 0 { 1 << bits } else { used } as usize;
|
||||
assert_eq!(u32::from_le_bytes(b[10..14].try_into().unwrap()) as usize, FILE_HEADER_LEN + 40 + colors * 4, "{bits} bits, {used} colors");
|
||||
}
|
||||
// Bytes after the last row are left out of the file.
|
||||
let body = disp_body(9, 5, 8, 0);
|
||||
let trailing = [body.as_slice(), &[0xAA; 64]].concat();
|
||||
let file = with_disp(1100, trailing);
|
||||
let p = preview(&file, Limits::default()).unwrap().unwrap();
|
||||
assert_eq!(&p.bytes[FILE_HEADER_LEN..], &body[DISP_LEAD..]);
|
||||
assert_eq!(u32::from_le_bytes(p.bytes[2..6].try_into().unwrap()) as usize, p.bytes.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -264,12 +318,30 @@ mod tests {
|
||||
let file = with_disp(1100, body[..cut].to_vec());
|
||||
assert_eq!(preview(&file, Limits::default()), Err(Error::Damaged("preview")), "cut at {cut}");
|
||||
}
|
||||
// An info header longer than the chunk, or shorter than 40 bytes.
|
||||
for info in [u32::MAX, 12] {
|
||||
// An info header longer than the chunk or too short for its length field, and a plane
|
||||
// count other than 1.
|
||||
for info in [u32::MAX, 0, 3] {
|
||||
let mut b = body.clone();
|
||||
b[DISP_LEAD..DISP_LEAD + 4].copy_from_slice(&info.to_le_bytes());
|
||||
assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview")), "info {info}");
|
||||
}
|
||||
for planes in [0u16, 2] {
|
||||
let mut b = body.clone();
|
||||
b[DISP_LEAD + 12..DISP_LEAD + 14].copy_from_slice(&planes.to_le_bytes());
|
||||
assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview")), "{planes} planes");
|
||||
}
|
||||
// Header lengths other than 40 bytes.
|
||||
for info in [12u32, 44, 52, 56, 64, 108, 124] {
|
||||
let mut b = body.clone();
|
||||
b[DISP_LEAD..DISP_LEAD + 4].copy_from_slice(&info.to_le_bytes());
|
||||
assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Unsupported(OTHER_HEADER)), "info {info}");
|
||||
}
|
||||
// A whole 12-byte core header of a 1-by-1 24-bit bitmap, shorter than the 40-byte fields.
|
||||
let mut core = 8u32.to_le_bytes().to_vec();
|
||||
core.extend(12u32.to_le_bytes());
|
||||
core.extend([1, 0, 1, 0, 1, 0, 24, 0]);
|
||||
core.extend([1, 2, 3, 0]);
|
||||
assert_eq!(preview(&with_disp(1100, core), Limits::default()), Err(Error::Unsupported(OTHER_HEADER)));
|
||||
// A color count past the chunk.
|
||||
let mut b = body.clone();
|
||||
b[DISP_LEAD + 32..DISP_LEAD + 36].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
@@ -322,6 +394,112 @@ mod tests {
|
||||
let v16 = package16(&[member("previews/thumbnail.png", [PNG_SIGNATURE, &big].concat(), true)]);
|
||||
assert_eq!(preview(&v16, Limits { member: 4000, ..Limits::default() }), Err(Error::Limit("package member size")));
|
||||
assert_eq!(preview(&v16, Limits { inflated: 4000, ..Limits::default() }), Err(Error::Limit("inflated size")));
|
||||
assert_eq!(preview(&v16, Limits { members: 1, ..Limits::default() }), Err(Error::Limit("package member count")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_walk_that_stops_short_of_the_forms_end_is_damage() {
|
||||
let file = synth::sample(1100, true);
|
||||
assert_eq!(preview(&file, Limits::default()), Ok(None));
|
||||
// A chunk whose length runs past the form, before any `DISP` chunk.
|
||||
let mut past = file.clone();
|
||||
past[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert_eq!(preview(&past, Limits::default()), Err(Error::Damaged("preview")));
|
||||
// A form length too short for the form type, with a `DISP` chunk after it.
|
||||
let mut short = with_disp(1100, disp_body(4, 4, 8, 0));
|
||||
short[4..8].copy_from_slice(&2u32.to_le_bytes());
|
||||
assert_eq!(preview(&short, Limits::default()), Err(Error::Damaged("preview")));
|
||||
// A partial chunk header at the end: the start of a `DISP` chunk whose length is cut off.
|
||||
let mut partial = file.clone();
|
||||
partial.extend(b"DISP");
|
||||
let form_len = (partial.len() - 8) as u32;
|
||||
partial[4..8].copy_from_slice(&form_len.to_le_bytes());
|
||||
assert_eq!(preview(&partial, Limits::default()), Err(Error::Damaged("preview")));
|
||||
// A file without a `DISP` chunk cut inside its last chunk.
|
||||
assert_eq!(preview(&file[..file.len() - 1], Limits::default()), Err(Error::Damaged("preview")));
|
||||
// A file cut where its `DISP` chunk would start, and one cut after it.
|
||||
let whole = with_disp(1100, disp_body(4, 4, 8, 0));
|
||||
let at = whole.windows(4).position(|w| w == b"DISP").unwrap();
|
||||
assert_eq!(preview(&whole[..at], Limits::default()), Err(Error::Damaged("preview")));
|
||||
assert!(preview(&whole[..whole.len() - 1], Limits::default()).unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disp_chunk_that_is_not_a_bitmap_is_passed_over() {
|
||||
let text = [[1u8, 0, 0, 0].as_slice(), b"some text"].concat();
|
||||
let bitmap = disp_body(3, 2, 8, 0);
|
||||
// A bitmap with a 12-byte header, which is not read.
|
||||
let core = [[8u8, 0, 0, 0, 12, 0, 0, 0, 1, 0, 1, 0, 1, 0, 24, 0].as_slice(), &[1, 2, 3, 0]].concat();
|
||||
// A run-length bitmap, whose other fields are not checked: here a plane count of 0.
|
||||
let mut rle = bitmap.clone();
|
||||
rle[DISP_LEAD + 12..DISP_LEAD + 14].copy_from_slice(&0u16.to_le_bytes());
|
||||
rle[DISP_LEAD + 16..DISP_LEAD + 20].copy_from_slice(&1u32.to_le_bytes());
|
||||
let mut content =
|
||||
vec![chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), chunk(b"DISP", text.clone()), chunk(b"DISP", core), chunk(b"DISP", rle)];
|
||||
content.push(chunk(b"DISP", bitmap.clone()));
|
||||
content.extend(synth::sample_content(1100));
|
||||
let file = synth::riff(1100, &content);
|
||||
let p = preview(&file, Limits::default()).unwrap().unwrap();
|
||||
assert_eq!(&p.bytes[FILE_HEADER_LEN..], &bitmap[DISP_LEAD..]);
|
||||
// With no bitmap after it, the file has a picture that is not read.
|
||||
assert_eq!(preview(&with_disp(1100, text), Limits::default()), Err(Error::Unsupported(OTHER_DISP)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_table_larger_than_the_bit_count_allows_is_damage() {
|
||||
assert!(preview(&with_disp(1100, disp_body(4, 4, 1, 2)), Limits::default()).unwrap().is_some());
|
||||
assert_eq!(preview(&with_disp(1100, disp_body(4, 4, 1, 3)), Limits::default()), Err(Error::Damaged("preview")));
|
||||
assert_eq!(preview(&with_disp(1100, disp_body(1, 1, 16, 65_537)), Limits::default()), Err(Error::Damaged("preview")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_image_size_is_0_or_the_rows_size() {
|
||||
// 4 rows of 4 bytes.
|
||||
let body = disp_body(4, 4, 8, 0);
|
||||
for (size, ok) in [(16u32, true), (17, false), (16 + 64, false)] {
|
||||
let mut b = [body.as_slice(), &[0; 64]].concat();
|
||||
b[DISP_LEAD + 20..DISP_LEAD + 24].copy_from_slice(&size.to_le_bytes());
|
||||
let file = with_disp(1100, b);
|
||||
assert_eq!(preview(&file, Limits::default()).is_ok(), ok, "size {size}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_2_files_picture_is_not_read() {
|
||||
for marker in *b"ml" {
|
||||
assert_eq!(preview(&synth::wl_sample(marker), Limits::default()), Err(Error::Unsupported(WL_PICTURE)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_with_both_members_gives_the_png() {
|
||||
let bmp = with_disp(1100, disp_body(3, 2, 8, 0));
|
||||
let bmp = preview(&bmp, Limits::default()).unwrap().unwrap().bytes.into_owned();
|
||||
for extra in [
|
||||
[member("metadata/thumbnails/thumbnail.bmp", bmp.clone(), false), member("previews/thumbnail.png", png(), false)],
|
||||
[member("previews/thumbnail.png", png(), false), member("metadata/thumbnails/thumbnail.bmp", bmp.clone(), false)],
|
||||
] {
|
||||
assert_eq!(preview(&package16(&extra), Limits::default()).unwrap().unwrap().format, PreviewFormat::Png);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compressed_or_masked_bitmap_outside_the_header_rules_is_refused() {
|
||||
let body = disp_body(4, 4, 8, 0);
|
||||
let with = |compression: u32, bits: u16| {
|
||||
let mut b = body.clone();
|
||||
b[DISP_LEAD + 14..DISP_LEAD + 16].copy_from_slice(&bits.to_le_bytes());
|
||||
b[DISP_LEAD + 16..DISP_LEAD + 20].copy_from_slice(&compression.to_le_bytes());
|
||||
preview(&with_disp(1100, b), Limits::default()).map(|p| p.map(|p| p.format))
|
||||
};
|
||||
// Run-length, JPEG, PNG and alpha-mask compression, and a bit count of 0.
|
||||
for (compression, bits) in [(1, 8), (2, 4), (4, 0), (5, 0), (6, 32)] {
|
||||
assert_eq!(with(compression, bits), Err(Error::Unsupported(COMPRESSED)), "compression {compression}");
|
||||
}
|
||||
// Color masks are valid only at 16 and 32 bits, and no bit count of 0 is uncompressed.
|
||||
for (compression, bits) in [(BITFIELDS, 8), (BITFIELDS, 24), (BITFIELDS, 1), (RGB, 0)] {
|
||||
assert_eq!(with(compression, bits), Err(Error::Damaged("preview")), "compression {compression}, {bits} bits");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use craft_cdr::model::{Blend, Cap, Color, Flags, Geometry, Join, LayerKind, Matrix, Object, Segment};
|
||||
use craft_cdr::synth::{self, V, chunk, list};
|
||||
use craft_cdr::{Error, Limits, Warning, read};
|
||||
use craft_cdr::{Error, Limits, Warning, preview, read};
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn shapes(objects: &[Object]) -> Vec<&craft_cdr::model::Shape> {
|
||||
@@ -2167,6 +2167,7 @@ proptest! {
|
||||
let mut b = b"RIFF".to_vec();
|
||||
b.extend(bytes);
|
||||
let _ = read(&b, Limits::default());
|
||||
let _ = preview(&b, Limits::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2177,6 +2178,7 @@ proptest! {
|
||||
b[at % n] = v;
|
||||
}
|
||||
let _ = read(&b, Limits::default());
|
||||
let _ = preview(&b, Limits::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2222,6 +2224,65 @@ proptest! {
|
||||
data[at % n] = v;
|
||||
}
|
||||
}
|
||||
let _ = read(&synth::zip(&members, b""), Limits::default());
|
||||
let zip = synth::zip(&members, b"");
|
||||
let _ = read(&zip, Limits::default());
|
||||
// The package has no picture member, and `preview` does not read the damaged drawing.
|
||||
prop_assert_eq!(preview(&zip, Limits::default()), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_never_panics_on_mutated_pictures(version in prop::sample::select(vec![700u16, 1100, 1300, 1500, 1700]), deflate: bool, zipped: bool, edits in prop::collection::vec((any::<usize>(), any::<u8>()), 1..24)) {
|
||||
let bitmap = disp_body(5, 3, 8);
|
||||
let mut b = if version < 1400 {
|
||||
// A compressed list before the `DISP` chunk, which the walk passes over.
|
||||
let mut content = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())];
|
||||
content.push(synth::cmpr(&synth::sample_content(version)));
|
||||
content.push(chunk(b"DISP", bitmap));
|
||||
synth::riff(version, &content)
|
||||
} else {
|
||||
let (name, picture) = if version < 1700 {
|
||||
("metadata/thumbnails/thumbnail.bmp", [b"BM".as_slice(), &bitmap].concat())
|
||||
} else {
|
||||
("previews/thumbnail.png", [b"\x89PNG\r\n\x1a\n".as_slice(), &bitmap].concat())
|
||||
};
|
||||
let mut picture = synth::Member { name: name.into(), data: picture, deflate };
|
||||
// Edits to the member before it is zipped reach past its CRC-32.
|
||||
if !zipped {
|
||||
let n = picture.data.len();
|
||||
for &(at, v) in &edits {
|
||||
picture.data[at % n] = v;
|
||||
}
|
||||
}
|
||||
if version < 1600 {
|
||||
synth::zip(&[synth::Member { name: "content/riffData.cdr".into(), data: synth::sample(version, false), deflate }, picture], b"")
|
||||
} else {
|
||||
let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())];
|
||||
body.extend(synth::sample_content(version));
|
||||
synth::package16(version, &body, deflate, &[picture])
|
||||
}
|
||||
};
|
||||
if zipped || version < 1400 {
|
||||
let n = b.len();
|
||||
for (at, v) in edits {
|
||||
b[at % n] = v;
|
||||
}
|
||||
}
|
||||
let _ = preview(&b, Limits::default());
|
||||
}
|
||||
}
|
||||
|
||||
/// A `DISP` body: 4 bytes, a 40-byte bitmap info header for `bits` per pixel, a full color table
|
||||
/// and the rows.
|
||||
fn disp_body(width: u32, rows: u32, bits: u16) -> Vec<u8> {
|
||||
let mut b = 8u32.to_le_bytes().to_vec();
|
||||
b.extend(40u32.to_le_bytes());
|
||||
b.extend(width.to_le_bytes());
|
||||
b.extend(rows.to_le_bytes());
|
||||
b.extend(1u16.to_le_bytes());
|
||||
b.extend(bits.to_le_bytes());
|
||||
b.extend([0; 24]);
|
||||
b.extend((0..(1u32 << bits) * 4).map(|i| i as u8));
|
||||
let stride = (width * u32::from(bits)).div_ceil(32) * 4;
|
||||
b.extend((0..stride * rows).map(|i| (i * 3) as u8));
|
||||
b
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user