mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-02 10:38:15 -06:00
* #239: open PowerPoint 97-2003 .ppt/.pot/.pps files
New crate deckcraft-ppt (L3), written from the public [MS-CFB], [MS-PPT]
and [MS-ODRAW] Open Specifications: a compound-file reader (ported from
FilmCraft's clean-room reader), the edit chain and persist directory, and
the OfficeArt drawings. Main masters become masters (colours, fonts, text
styles, background, decorations), title masters become layouts; slides
keep their shapes (presets, freeforms, groups, rotation, flips), fills,
lines, shadows, pictures (PNG, JPEG, DIB, TIFF, EMF, WMF), text with the
master styles resolved into it, fields, notes and hidden flags.
Import only: an opened .ppt has no save path, so Save asks for a new
name. A .pps from the system starts the slide show. File dialogs, drag
and drop, the web shell and the macOS, Windows and Linux file
associations offer the three extensions. Tests build .ppt files from
records and sweep hostile input.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* #239: address review: budget picture decoding, read each persist directory once, macOS .pot/.pps types
- Pictures decode lazily, when a shape first uses them, each at most once and all
within a shared 4 GiB budget: many store entries pointing at one deflated blob
can no longer ask for unbounded memory.
- A persist directory named by many edits is read once.
- Info.plist declares com.microsoft.powerpoint.pot and .pps alongside .ppt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* #239: address review: check the picture budget before copying bitmap data
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* #239: build against current main
- convert.rs: set `flip: None` on imported gradients. `Gradient` gained the field in
ad97533a; None is what an unflipped gradient was before.
- tests.rs: split `imports_a_presentation` into one check per section (title, picture,
group, text box, master) for the workspace `cognitive_complexity` lint (6ddd2fb8).
The assertions are unchanged.
- Cargo.lock: deckcraft-ppt takes the workspace version, 0.15.0.
* #239: keep the picture budget on 32-bit targets
`MAX_TOTAL` was `4 << 30` as a `usize`. On wasm32 that is 2^32, which wraps to 0
without any error, so the web build's picture budget was zero and every .ppt
picture was dropped. Use the address space as the limit there. A compile-time
assertion that the budget holds at least one picture keeps it from happening
again on any target: the CI wasm step (`cargo check`) now fails if it does.
* #239: read past the character fields PowerPoint 2002 and later add
A TextCFException can end with pp10runid (mask bit 20), newEAFontRef (24),
csFontRef (25) and pp11ext (26), after `position`. read_cf stopped at
`position`, so in a StyleTextPropAtom the next run's count and mask were read
from the leftover bytes, and every later run got garbage formatting or the
walk ended. Master text styles go through the same reader. The fields are
read past and not used. The test has a run carrying all four followed by a
bold 18 pt run, which now reads as written.
* #239: convert each listed object once and index notes pages
Nothing stopped a slide list from naming one persist object many times, and
each listing converted its whole drawing again: a 100k-shape slide listed
180k times fits in about 10 MB and makes 1.8e10 shapes. An object is now
listed once across the slide, master and notes lists (PowerPoint never lists
one twice), and a repeat is logged and skipped. Notes pages are looked up
through a map built once, instead of a scan per slide (slides x notes). The
first matching page still wins.
* #239: find formatting runs by binary search
paragraphs() found the run at a position (rposition) and the next run start
(find) by scanning the run starts for every run, break and field, so text
cost grew with chars x runs. The starts are a running sum and never
decrease, so both lookups are now partition_point. Measured in a debug
build, 640k one-character runs (about 6 MB of file): 75 s before, about 2 s
after. The test uses a 20 s bound, like render's pathgrad budget test.
* #239: cap decoded pictures at the .pptx package total
The picture budget was 4 GiB, so a few MB of small deflated metafiles, each
inflating to 64 MiB, could make the import hold 4 GiB. A .pptx package may
inflate to 2 GiB in total (deckcraft-pptx opc MAX_TOTAL), and pictures are
the only part of a .ppt this crate inflates, so use the same 2 GiB. That also
fits a 32-bit usize, which replaces the wasm32 special case. This is a limit
change, so there is no new test: the budget test
(the_store_decodes_lazily_within_a_budget) and the compile-time check that
the budget holds a picture still cover it.
* #239: fall back to the first main master the same way every time
A slide naming a master that doesn't exist fell back to the lowest index in
the masters HashMap. A title master is stored with its main master's index,
so the two tied and the HashMap's random order picked one: the same file got
the "Title Master" layout on some opens and the main master's on others. The
fallback now considers main masters only. The test opens such a deck 30
times; before the fix it took the title master's layout within those opens.
* #239: try the edit scan before calling a file too old
Any Current User token other than the plain or encrypted one, including none
at all from a truncated record, returned TooOld at once. A PowerPoint 97 file
with a damaged Current User stream was reported as "made by PowerPoint 95 or
earlier", and the UserEditAtom scan meant for a missing stream never ran.
[MS-PPT] allows only those two tokens, so an unknown one can't tell a damaged
file from an older format. The scan now runs, and TooOld is returned only when
it finds no edit record behind an unknown token.
* #239: read persist directories within one stream's worth of words
dirs_seen only skips a directory named at the same offset again. Directories
nested inside one another, each named by its own UserEditAtom, were each read
to the end of the stream: MAX_EDITS x the stream. In a debug build, 4095 such
edits over a 64 MiB stream took about 48 s. All directories now share a budget
of stream.len() / 4 words. Real directories are separate records inside the
stream, so they always fit. The hostile case stops in milliseconds and is
reported as damaged.
* #239: check two additions on input-derived sizes
- cfb.rs: the mini sector end `at + MINI_SECTOR_SIZE` was unchecked. On a
32-bit target (wasm32), a sector number near 0x03FF_FFFF puts `at` at the
top of usize, so the add panics in a debug build and wraps in release.
- text.rs: the style-run total `chars.len() as u32 + 1` truncated and could
overflow past u32::MAX characters. It now saturates.
Neither case can be reached in a native test (one needs a 32-bit target, the
other more than 4 GiB of text), so there is no new test. The `+ 1`s in
convert.rs paragraphs() that the review also named are bounded by the text
length and can't overflow, so they are unchanged.
* #239: gaps: name every loss in the .ppt Impact line
The Impact line said old decks "open and read correctly" and named only
motion and links, while the Evidence above it also lists sounds and video,
degraded tables, OLE objects, charts and WordArt, and missing PICT pictures.
(CodeRabbit's open note on docs/gaps.md.)
* #239: ppt: a sector chain that revisits a sector is an error
read_chain stopped at the stream's size, so a FAT loop shorter than the stream returned the
looped sectors again as the stream's bytes. It now tracks visited sectors and fails on a revisit,
and reserves the stream's size (capped at the file length) up front.
a_looping_chain_stops expected the repeated bytes; it now expects the error (eliets2's review).
* #239: ppt: slide shapes inherit from their own master's shapes
Master shape properties were remembered by shape id alone, so a later master (a title master,
or a second main master) that reused a shape id replaced the first master's entry, and slides
inherited fill and line from the wrong master. They are now keyed by master slide id and shape id,
and a shape's hspMaster is looked up in its slide's master, then a title master's main master.
Notes pages have no imported master, so they inherit nothing.
PowerPoint gives shapes file-unique ids, so this takes a damaged or generated file (eliets2's
review).
* #239: ppt: drop the unused fBackground field
RawShape.background was set from the FSP flag but never read: the background shape is the
drawing container's own shape (OfficeArtDgContainer.shape, [MS-ODRAW] 2.2.13), which drawing()
already takes. The comment there now says so (eliets2's review).
* #239: ppt: shadowed text keeps its shadow
TextCFException's shadow bit was read and merged but never reached the run. A shadowed run now
gets a shadow in the colour scheme's shadow colour, at the distance and direction of the app's own
Text Shadow command, with no blur (the record has none). Emboss has no counterpart in the model,
so its field is gone and the loss is listed in the docs (eliets2's review).
* #239: the .pps show-on-open test opens a real 97-2003 file
a_ppsx_from_the_system_starts_the_show saved a .pptx under the name "Old talk.pps", so it went
through the PPTX path and never reached the legacy importer. crates/ppt/tests/fixtures/old-talk.pps
is a one-slide .pps built from records by the ppt tests (rebuilt with DECKCRAFT_WRITE_PPT_FIXTURE=1,
checked on every run), attributed CC0 like the other generated fixtures, and the UI test opens it
(eliets2's review).
* #239: docs: one date, the full list of losses, .pot in the README
From eliets2's review:
- README names .ppt/.pot/.pps and says the import has no writer (Save asks for a new name).
- The parity-checklist row lists the same losses as docs/gaps.md, now with text emboss, and the
checklist gets a status line for the change.
- The ROADMAP progress row, the architecture and file-format change rows and every header carry
one date (2026-11-09), so the progress row sits at the top in order; the ROADMAP gets its
status line.
- docs/gaps.md says why there is no real-deck corpus in the repo (no PowerPoint-made files) and
where one would live.
* #239: ppt: test mini streams, 4096-byte sectors and the DIFAT chain
The compound-file test builder only made version-3 files with 512-byte sectors, no mini stream
and every FAT sector in the header, so read_mini_chain, 4096-byte sectors and the DIFAT chain never
ran. build_with takes the sector shift and the mini stream cutoff, and lists FAT sectors past the
header's 109 in DIFAT sectors; build is build_with(streams, 9, 0), so existing tests see the same
layout. Three tests read streams back through each path (eliets2's review).
* #239: ppt: test every picture kind, two-UID blips and blips inside the FBSE
The blip tests covered PNG, deflated WMF and DIB only. New tests decode JPEG (RGB and CMYK), TIFF
and PNG with one and two UIDs, an uncompressed EMF with each UID count, a metafile over the budget
(compressed or not), and a blip held inside its FBSE rather than in the Pictures stream. All
passed as written (eliets2's review).
* #239: ppt: placeholder text held only in the slide list is imported
A shape's client text box may hold just an OutlineTextRefAtom, with no TextHeaderAtom ([MS-PPT]
OfficeArtClientTextbox): the text lives in the slide list, and that is the usual form for slide
placeholders. read_block returned None without a header, so text_block never reached its
outline fallback and the placeholder came in empty. A block with a reference and no header is
now returned for the caller to follow.
placeholder_text_can_come_from_the_slide_list covers the reference alone (it failed before this
change) and a header with a reference; the test document builder can put outline blocks in the
slide list (streams_with_outline). Found writing the test eliets2's review asked for.
* #239: ppt: test newer edits and the two other encryption signs
doc::read had tests for one edit and the Current User token only. a_later_edit_replaces_a_slide
adds an edit whose persist directory gives the slide a new object; the newer slide is imported and
the master from the older directory is kept. encryption_is_found_in_the_edit_and_the_persist_directory
covers an edit record long enough for encryptSessionPersistIdRef and a CryptSession object named
by a later edit. Both passed as written (eliets2's review).
* #239: ppt: test title masters and slides that follow nothing
No test made a slide of a title master or a slide with the follow-master flags off. The new test
checks that a title master becomes a "Title Master" layout with its own background and shapes
and without the master's shapes, that its slide uses that layout and follows its background, and
that a slide with all three flags off keeps its own background and colour scheme and hides the
master's shapes. It passed as written (eliets2's review).
* #239: ppt: merge boolean properties flag by flag
A boolean property word holds sixteen flags, each with its own fUse bit.
Props::inherit and add_table kept the whole word from the most specific
set, so a placeholder or text box that set only fNoFillHitTest lost the
inherited "not filled" and "no line" and was drawn with a fill and an
outline. Merge those words per flag instead (#1137 review, issue 1).
* #239: ppt: recover a broken edit chain and report lost slides
An edit whose previous-edit offset points back at itself (or anywhere
that isn't an edit) cut the older edits off, and with them the persist
directories holding the slides: such a file opened as an empty deck
with no warning. When the chain doesn't end at offset 0, read every
edit's persist directory in the stream, newest first, filling only what
the chain left unset.
Slides the slide list names but whose objects are still missing are now
returned by deckcraft_ppt::import_checked and reported like a damaged
.pptx: lostSlides, a "(Repaired)" copy and the CLI warning
(#1137 review, issue 3).
* #239: ppt: picture frames, inline picture fills, gradients, footers, numbering
The remaining differences from LibreOffice in the #1137 stress test:
- Picture frames (and OLE frames) that say nothing about fill or line
start with neither, as placeholders and text boxes do, instead of the
drawing defaults' fill.
- A pib or fillBlip held in the property's own complex bytes (fBid) is
decoded within the picture budget: table cells with a picture fill
showed a plain colour.
- Shaded fills put the back colour at fillFocus ([MS-ODRAW]), and the
linear angle follows how LibreOffice writes and reads it (0 degrees
from the top): the linear gradient was reversed, the radial inside out.
- HeadersFooters (the slide's, else the document's) add the date,
footer and slide number placeholders; the master's footer placement,
alignment, size and colour reach every layout.
- Numbering from the document's ___PPT9 tag (OutlineTextProps9, pp9rt
in the runs' fontStyle) turns bulleted paragraphs into numbered ones.
- Wingdings diamonds draw as a diamond, not a dot.
* #239: ppt: read CString records up to their first NUL
Header/footer text and the ___PPT9 tag name were decoded from the whole
CString body. A writer that ends the string with a NUL would put the NUL
into the footer text and make the tag name fail to match, losing the
numbering. Stop at the first NUL, as the font names already do.
---------
Co-authored-by: kiwi4boy <kiwi4boy@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: keithcsqueensu <92232107+keithcsqueensu@users.noreply.github.com>
Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
553 lines
23 KiB
Rust
553 lines
23 KiB
Rust
//! Reading Compound File Binary containers ([MS-CFB] §2.2–2.6), the file system a `.ppt` lives in:
|
||
//! fixed-size sectors chained by a FAT, a directory of 128-byte entries arranged as one sibling
|
||
//! tree per storage, and a mini stream (with its own mini FAT) for streams under 4096 bytes.
|
||
//!
|
||
//! Ported from FilmCraft's clean-room `filmcraft-cfb` reader (same owner and licence), with every
|
||
//! read bounds-checked through `get` and every chain bounded by the file's sector count, so a
|
||
//! damaged file gives an error, never a panic or an endless loop.
|
||
|
||
use std::cmp::Ordering;
|
||
|
||
const SIGNATURE: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
|
||
const MAXREGSECT: u32 = 0xFFFF_FFFA;
|
||
const ENDOFCHAIN: u32 = 0xFFFF_FFFE;
|
||
const FREESECT: u32 = 0xFFFF_FFFF;
|
||
const NOSTREAM: u32 = 0xFFFF_FFFF;
|
||
const MINI_SECTOR_SIZE: usize = 64;
|
||
|
||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||
pub enum CfbError {
|
||
#[error("not a compound file")]
|
||
NotCfb,
|
||
#[error("damaged compound file: {0}")]
|
||
Invalid(String),
|
||
#[error("no stream {0:?}")]
|
||
NotFound(String),
|
||
}
|
||
|
||
type Result<T> = std::result::Result<T, CfbError>;
|
||
|
||
fn invalid(s: impl Into<String>) -> CfbError {
|
||
CfbError::Invalid(s.into())
|
||
}
|
||
|
||
/// Whether `bytes` starts with the compound file signature.
|
||
pub fn sniff(bytes: &[u8]) -> bool {
|
||
bytes.starts_with(&SIGNATURE)
|
||
}
|
||
|
||
pub(crate) fn u16_at(b: &[u8], at: usize) -> Option<u16> {
|
||
let s = b.get(at..at.checked_add(2)?)?;
|
||
Some(u16::from_le_bytes([*s.first()?, *s.get(1)?]))
|
||
}
|
||
|
||
pub(crate) fn u32_at(b: &[u8], at: usize) -> Option<u32> {
|
||
let s = b.get(at..at.checked_add(4)?)?;
|
||
Some(u32::from_le_bytes([*s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?]))
|
||
}
|
||
|
||
fn u64_at(b: &[u8], at: usize) -> Option<u64> {
|
||
Some(u64::from(u32_at(b, at)?) | (u64::from(u32_at(b, at + 4)?) << 32))
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||
enum Kind {
|
||
Root,
|
||
Storage,
|
||
Stream,
|
||
Unknown,
|
||
}
|
||
|
||
#[derive(Clone, Debug)]
|
||
struct Entry {
|
||
name: String,
|
||
kind: Kind,
|
||
start: u32,
|
||
size: u64,
|
||
children: Vec<usize>,
|
||
left: u32,
|
||
right: u32,
|
||
child: u32,
|
||
}
|
||
|
||
/// A parsed compound file over borrowed bytes.
|
||
pub struct CompoundFile<'a> {
|
||
data: &'a [u8],
|
||
sector_size: usize,
|
||
mini_cutoff: u64,
|
||
fat: Vec<u32>,
|
||
minifat: Vec<u32>,
|
||
mini_stream: Vec<u8>,
|
||
entries: Vec<Entry>,
|
||
}
|
||
|
||
impl<'a> CompoundFile<'a> {
|
||
/// Parse the header, FAT, mini FAT, directory and mini stream of `data`.
|
||
pub fn open(data: &'a [u8]) -> Result<CompoundFile<'a>> {
|
||
if data.len() < 512 || !sniff(data) || u16_at(data, 28) != Some(0xFFFE) {
|
||
return Err(CfbError::NotCfb);
|
||
}
|
||
let h = |at| u32_at(data, at).ok_or(CfbError::NotCfb);
|
||
let version = u16_at(data, 26).ok_or(CfbError::NotCfb)?;
|
||
let shift = u16_at(data, 30).ok_or(CfbError::NotCfb)?;
|
||
if shift != 9 && shift != 12 {
|
||
return Err(invalid(format!("sector shift {shift}")));
|
||
}
|
||
let sector_size = 1usize << shift;
|
||
let n_fat = h(44)? as usize;
|
||
let first_dir = h(48)?;
|
||
let mini_cutoff = u64::from(h(56)?);
|
||
let first_minifat = h(60)?;
|
||
let first_difat = h(68)?;
|
||
let max_sectors = data.len() / sector_size + 1;
|
||
if n_fat > max_sectors {
|
||
return Err(invalid(format!("{n_fat} FAT sectors in a {}-byte file", data.len())));
|
||
}
|
||
let mut cf =
|
||
CompoundFile { data, sector_size, mini_cutoff, fat: Vec::new(), minifat: Vec::new(), mini_stream: Vec::new(), entries: Vec::new() };
|
||
// FAT sector numbers: 109 in the header, then the DIFAT chain.
|
||
let mut fat_sectors: Vec<u32> = (0..109).filter_map(|i| u32_at(data, 76 + i * 4)).filter(|&s| s <= MAXREGSECT).collect();
|
||
let mut d = first_difat;
|
||
let mut seen = 0usize;
|
||
let per = sector_size / 4 - 1;
|
||
while d <= MAXREGSECT && fat_sectors.len() < n_fat {
|
||
seen += 1;
|
||
if seen > max_sectors {
|
||
return Err(invalid("DIFAT chain loops"));
|
||
}
|
||
let s = cf.sector(d)?;
|
||
fat_sectors.extend((0..per).filter_map(|i| u32_at(s, i * 4)).filter(|&v| v <= MAXREGSECT));
|
||
d = u32_at(s, per * 4).ok_or_else(|| invalid("short DIFAT sector"))?;
|
||
}
|
||
fat_sectors.truncate(n_fat);
|
||
let mut fat = Vec::with_capacity(fat_sectors.len().saturating_mul(sector_size / 4));
|
||
for s in fat_sectors {
|
||
let b = cf.sector(s)?;
|
||
fat.extend((0..sector_size / 4).filter_map(|i| u32_at(b, i * 4)));
|
||
}
|
||
cf.fat = fat;
|
||
let dir = cf.read_chain(first_dir, None)?;
|
||
for e in dir.as_chunks::<128>().0 {
|
||
cf.entries.push(parse_entry(e, version).ok_or_else(|| invalid("short directory entry"))?);
|
||
}
|
||
match cf.entries.first() {
|
||
Some(r) if r.kind == Kind::Root => {}
|
||
_ => return Err(invalid("the first directory entry is not the root")),
|
||
}
|
||
if first_minifat <= MAXREGSECT {
|
||
let mf = cf.read_chain(first_minifat, None)?;
|
||
cf.minifat = mf.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c)).collect();
|
||
}
|
||
let (root_start, root_size) = cf.entries.first().map(|r| (r.start, r.size)).unwrap_or((ENDOFCHAIN, 0));
|
||
if root_start <= MAXREGSECT && root_size > 0 {
|
||
let size = usize::try_from(root_size.min(data.len() as u64)).unwrap_or(0);
|
||
cf.mini_stream = cf.read_chain(root_start, Some(size))?;
|
||
}
|
||
cf.build_tree()?;
|
||
Ok(cf)
|
||
}
|
||
|
||
fn sector(&self, n: u32) -> Result<&'a [u8]> {
|
||
if n > MAXREGSECT {
|
||
return Err(invalid(format!("bad sector {n:#x}")));
|
||
}
|
||
let start = (n as usize).checked_add(1).and_then(|k| k.checked_mul(self.sector_size)).ok_or_else(|| invalid("sector number overflow"))?;
|
||
let end = start.checked_add(self.sector_size).ok_or_else(|| invalid("sector number overflow"))?;
|
||
self.data.get(start..end).ok_or_else(|| invalid(format!("sector {n} is outside the file")))
|
||
}
|
||
|
||
/// Concatenate a regular sector chain; `limit` stops once that many bytes are read.
|
||
fn read_chain(&self, start: u32, limit: Option<usize>) -> Result<Vec<u8>> {
|
||
// Reserve up to the stream's size; `limit` is checked against the file length by callers,
|
||
// and `min` keeps a bad size from reserving more than the file.
|
||
let mut out = Vec::with_capacity(limit.unwrap_or(0).min(self.data.len()));
|
||
let mut s = start;
|
||
// A chain cannot visit more sectors than the file holds, and must not visit one twice: a
|
||
// loop cut off by `limit` would otherwise return repeated sectors as the stream.
|
||
let mut visited = vec![false; self.data.len() / self.sector_size + 1];
|
||
while s != ENDOFCHAIN {
|
||
match visited.get_mut(s as usize) {
|
||
Some(v) if !*v => *v = true,
|
||
Some(_) => return Err(invalid("sector chain loops")),
|
||
None => return Err(invalid(format!("sector {s} is outside the file"))),
|
||
}
|
||
out.extend_from_slice(self.sector(s)?);
|
||
if limit.is_some_and(|l| out.len() >= l) {
|
||
break;
|
||
}
|
||
s = *self.fat.get(s as usize).ok_or_else(|| invalid(format!("sector {s} has no FAT entry")))?;
|
||
if s == FREESECT {
|
||
return Err(invalid("chain runs into a free sector"));
|
||
}
|
||
}
|
||
if let Some(l) = limit {
|
||
if out.len() < l {
|
||
return Err(invalid("stream is truncated"));
|
||
}
|
||
out.truncate(l);
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
fn read_mini_chain(&self, start: u32, size: usize) -> Result<Vec<u8>> {
|
||
let mut out = Vec::with_capacity(size.min(self.mini_stream.len()));
|
||
let mut s = start;
|
||
let mut steps = 0usize;
|
||
while out.len() < size {
|
||
if s > MAXREGSECT {
|
||
return Err(invalid("mini stream chain ends early"));
|
||
}
|
||
steps += 1;
|
||
if steps > self.minifat.len().max(1) {
|
||
return Err(invalid("mini sector chain loops"));
|
||
}
|
||
let at = (s as usize).checked_mul(MINI_SECTOR_SIZE).ok_or_else(|| invalid("mini sector overflow"))?;
|
||
// Checked: on a 32-bit target a sector number near 0x03FF_FFFF puts `at` at the top of usize.
|
||
let end = at.checked_add(MINI_SECTOR_SIZE).ok_or_else(|| invalid("mini sector overflow"))?;
|
||
let b = self.mini_stream.get(at..end).ok_or_else(|| invalid("mini sector outside the mini stream"))?;
|
||
out.extend_from_slice(b);
|
||
s = *self.minifat.get(s as usize).ok_or_else(|| invalid("mini sector has no mini FAT entry"))?;
|
||
}
|
||
out.truncate(size);
|
||
Ok(out)
|
||
}
|
||
|
||
fn build_tree(&mut self) -> Result<()> {
|
||
let n = self.entries.len();
|
||
let mut owned = vec![false; n];
|
||
if let Some(o) = owned.first_mut() {
|
||
*o = true;
|
||
}
|
||
for parent in 0..n {
|
||
let Some(p) = self.entries.get(parent) else { continue };
|
||
if !matches!(p.kind, Kind::Root | Kind::Storage) {
|
||
continue;
|
||
}
|
||
let mut kids = Vec::new();
|
||
// In-order walk of the sibling tree, iterative and cycle-safe.
|
||
let mut stack: Vec<u32> = Vec::new();
|
||
let mut cur = p.child;
|
||
let mut steps = 0;
|
||
while cur != NOSTREAM || !stack.is_empty() {
|
||
while cur != NOSTREAM {
|
||
let i = cur as usize;
|
||
match owned.get_mut(i) {
|
||
Some(o) if !*o => *o = true,
|
||
_ => return Err(invalid(format!("directory entry {cur} is referenced twice or does not exist"))),
|
||
}
|
||
stack.push(cur);
|
||
cur = self.entries.get(i).map_or(NOSTREAM, |e| e.left);
|
||
steps += 1;
|
||
if steps > n {
|
||
return Err(invalid("directory tree loops"));
|
||
}
|
||
}
|
||
if let Some(top) = stack.pop() {
|
||
kids.push(top as usize);
|
||
cur = self.entries.get(top as usize).map_or(NOSTREAM, |e| e.right);
|
||
}
|
||
}
|
||
if let Some(p) = self.entries.get_mut(parent) {
|
||
p.children = kids;
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// Names of the root storage's streams and storages.
|
||
pub fn root_names(&self) -> Vec<&str> {
|
||
self.entries.first().map(|r| r.children.iter().filter_map(|&c| self.entries.get(c)).map(|e| e.name.as_str()).collect()).unwrap_or_default()
|
||
}
|
||
|
||
/// Contents of the stream `name` directly under the root (names compare case-insensitively,
|
||
/// [MS-CFB] §2.6.4).
|
||
pub fn read_root_stream(&self, name: &str) -> Result<Vec<u8>> {
|
||
let root = self.entries.first().ok_or_else(|| CfbError::NotFound(name.into()))?;
|
||
let e = root
|
||
.children
|
||
.iter()
|
||
.filter_map(|&c| self.entries.get(c))
|
||
.find(|e| e.kind == Kind::Stream && compare_names(&e.name, name).is_eq())
|
||
.ok_or_else(|| CfbError::NotFound(name.into()))?;
|
||
let size = usize::try_from(e.size).map_err(|_| invalid("stream too large"))?;
|
||
if size == 0 {
|
||
return Ok(Vec::new());
|
||
}
|
||
if e.size > self.data.len() as u64 {
|
||
return Err(invalid(format!("stream {:?} is larger than the file", e.name)));
|
||
}
|
||
if e.size < self.mini_cutoff { self.read_mini_chain(e.start, size) } else { self.read_chain(e.start, Some(size)) }
|
||
}
|
||
}
|
||
|
||
fn upper(u: u16) -> u16 {
|
||
if (u16::from(b'a')..=u16::from(b'z')).contains(&u) {
|
||
return u - 32;
|
||
}
|
||
if u < 0x80 {
|
||
return u;
|
||
}
|
||
match char::from_u32(u32::from(u)) {
|
||
Some(c) => {
|
||
let mut up = c.to_uppercase();
|
||
match (up.next(), up.next()) {
|
||
(Some(x), None) => u16::try_from(u32::from(x)).unwrap_or(u),
|
||
_ => u,
|
||
}
|
||
}
|
||
None => u,
|
||
}
|
||
}
|
||
|
||
/// Sibling order of directory entries ([MS-CFB] §2.6.4): shorter names first, then a code-unit
|
||
/// comparison of the upper-cased names.
|
||
fn compare_names(a: &str, b: &str) -> Ordering {
|
||
let ua: Vec<u16> = a.encode_utf16().collect();
|
||
let ub: Vec<u16> = b.encode_utf16().collect();
|
||
ua.len().cmp(&ub.len()).then_with(|| ua.iter().map(|&u| upper(u)).cmp(ub.iter().map(|&u| upper(u))))
|
||
}
|
||
|
||
fn parse_entry(b: &[u8], version: u16) -> Option<Entry> {
|
||
let name_len = usize::from(u16_at(b, 64)?).min(64);
|
||
let units: Vec<u16> = (0..name_len / 2).filter_map(|i| u16_at(b, i * 2)).take_while(|&u| u != 0).collect();
|
||
let kind = match b.get(66)? {
|
||
5 => Kind::Root,
|
||
1 => Kind::Storage,
|
||
2 => Kind::Stream,
|
||
_ => Kind::Unknown,
|
||
};
|
||
let size = u64_at(b, 120)?;
|
||
Some(Entry {
|
||
name: String::from_utf16_lossy(&units),
|
||
kind,
|
||
start: u32_at(b, 116)?,
|
||
// Version 3 files may leave garbage in the high 32 bits (§2.6.3).
|
||
size: if version == 3 { size & 0xFFFF_FFFF } else { size },
|
||
children: Vec::new(),
|
||
left: u32_at(b, 68)?,
|
||
right: u32_at(b, 72)?,
|
||
child: u32_at(b, 76)?,
|
||
})
|
||
}
|
||
|
||
/// Builds small version-3 compound files for tests: every stream goes in regular sectors (the
|
||
/// mini stream cutoff is set to 0), one flat directory under the root.
|
||
#[cfg(test)]
|
||
pub(crate) fn build(streams: &[(&str, &[u8])]) -> Vec<u8> {
|
||
build_with(streams, 9, 0)
|
||
}
|
||
|
||
/// A chain of whole `ss`-byte sectors holding `data`, appended to `sectors` and `fat`; returns its
|
||
/// first sector.
|
||
#[cfg(test)]
|
||
fn push_chain(sectors: &mut Vec<Vec<u8>>, fat: &mut Vec<u32>, ss: usize, data: &[u8]) -> u32 {
|
||
let n = data.len().div_ceil(ss).max(1);
|
||
let first = sectors.len() as u32;
|
||
for k in 0..n {
|
||
let mut s = data.get(k * ss..((k + 1) * ss).min(data.len())).unwrap_or(&[]).to_vec();
|
||
s.resize(ss, 0);
|
||
sectors.push(s);
|
||
fat.push(if k + 1 == n { ENDOFCHAIN } else { first + k as u32 + 1 });
|
||
}
|
||
first
|
||
}
|
||
|
||
/// Builds a compound file with `1 << shift` byte sectors (9: version 3, 12: version 4). Streams
|
||
/// shorter than `mini_cutoff` go in the mini stream. When the FAT outgrows the header's 109
|
||
/// slots, the rest are listed in DIFAT sectors. Layout: streams, mini stream, mini FAT,
|
||
/// directory, DIFAT, then the FAT last.
|
||
#[cfg(test)]
|
||
pub(crate) fn build_with(streams: &[(&str, &[u8])], shift: u16, mini_cutoff: u32) -> Vec<u8> {
|
||
let ss = 1usize << shift;
|
||
let per = ss / 4;
|
||
let mut sectors: Vec<Vec<u8>> = Vec::new();
|
||
let mut fat: Vec<u32> = Vec::new();
|
||
let mut mini = Vec::new();
|
||
let mut minifat: Vec<u32> = Vec::new();
|
||
let mut starts = Vec::new();
|
||
for (_, data) in streams {
|
||
if data.is_empty() {
|
||
starts.push(ENDOFCHAIN);
|
||
} else if (data.len() as u64) < u64::from(mini_cutoff) {
|
||
let n = data.len().div_ceil(MINI_SECTOR_SIZE);
|
||
let first = minifat.len() as u32;
|
||
for k in 0..n {
|
||
minifat.push(if k + 1 == n { ENDOFCHAIN } else { first + k as u32 + 1 });
|
||
}
|
||
mini.extend_from_slice(data);
|
||
mini.resize(minifat.len() * MINI_SECTOR_SIZE, 0);
|
||
starts.push(first);
|
||
} else {
|
||
starts.push(push_chain(&mut sectors, &mut fat, ss, data));
|
||
}
|
||
}
|
||
let (root_start, root_size) = if mini.is_empty() { (ENDOFCHAIN, 0) } else { (push_chain(&mut sectors, &mut fat, ss, &mini), mini.len() as u32) };
|
||
let minifat_first = if minifat.is_empty() {
|
||
ENDOFCHAIN
|
||
} else {
|
||
minifat.resize(minifat.len().div_ceil(per) * per, FREESECT);
|
||
let bytes: Vec<u8> = minifat.iter().flat_map(|v| v.to_le_bytes()).collect();
|
||
push_chain(&mut sectors, &mut fat, ss, &bytes)
|
||
};
|
||
let minifat_sectors = (minifat.len() / per) as u32;
|
||
// Directory: root + streams. Root's child is entry 1; siblings are chained as right children in
|
||
// name order (a valid, if unbalanced, tree).
|
||
let mut order: Vec<usize> = (0..streams.len()).collect();
|
||
order.sort_by(|&a, &b| compare_names(streams[a].0, streams[b].0));
|
||
let n_entries = streams.len() + 1;
|
||
let mut dir = vec![0u8; n_entries.div_ceil(ss / 128) * ss];
|
||
let mut put = |idx: usize, name: &str, kind: u8, left: u32, right: u32, child: u32, start: u32, size: u32| {
|
||
let e = idx * 128;
|
||
let units: Vec<u16> = name.encode_utf16().collect();
|
||
for (i, u) in units.iter().enumerate() {
|
||
dir[e + i * 2..e + i * 2 + 2].copy_from_slice(&u.to_le_bytes());
|
||
}
|
||
dir[e + 64..e + 66].copy_from_slice(&((units.len() as u16 + 1) * 2).to_le_bytes());
|
||
dir[e + 66] = kind;
|
||
dir[e + 68..e + 72].copy_from_slice(&left.to_le_bytes());
|
||
dir[e + 72..e + 76].copy_from_slice(&right.to_le_bytes());
|
||
dir[e + 76..e + 80].copy_from_slice(&child.to_le_bytes());
|
||
dir[e + 116..e + 120].copy_from_slice(&start.to_le_bytes());
|
||
dir[e + 120..e + 124].copy_from_slice(&size.to_le_bytes());
|
||
};
|
||
let first_child = order.first().map_or(NOSTREAM, |&i| i as u32 + 1);
|
||
put(0, "Root Entry", 5, NOSTREAM, NOSTREAM, first_child, root_start, root_size);
|
||
for (k, &i) in order.iter().enumerate() {
|
||
let right = order.get(k + 1).map_or(NOSTREAM, |&j| j as u32 + 1);
|
||
put(i + 1, streams[i].0, 2, NOSTREAM, right, NOSTREAM, starts[i], streams[i].1.len() as u32);
|
||
}
|
||
let dir_first = push_chain(&mut sectors, &mut fat, ss, &dir);
|
||
// FAT and DIFAT sectors: enough FAT entries for every sector, including their own.
|
||
let difat_for = |n_fat: usize| n_fat.saturating_sub(109).div_ceil(per - 1);
|
||
let mut n_fat = 1;
|
||
while sectors.len() + difat_for(n_fat) + n_fat > n_fat * per {
|
||
n_fat += 1;
|
||
}
|
||
let n_difat = difat_for(n_fat);
|
||
let difat_first = sectors.len() as u32;
|
||
let fat_first = difat_first + n_difat as u32;
|
||
fat.extend(std::iter::repeat_n(0xFFFF_FFFC, n_difat));
|
||
fat.extend(std::iter::repeat_n(0xFFFF_FFFD, n_fat));
|
||
fat.resize(n_fat * per, FREESECT);
|
||
let fat_ids: Vec<u32> = (0..n_fat as u32).map(|k| fat_first + k).collect();
|
||
for d in 0..n_difat {
|
||
let mut v: Vec<u32> = fat_ids.iter().skip(109 + d * (per - 1)).take(per - 1).copied().collect();
|
||
v.resize(per - 1, FREESECT);
|
||
v.push(if d + 1 == n_difat { ENDOFCHAIN } else { difat_first + d as u32 + 1 });
|
||
sectors.push(v.iter().flat_map(|x| x.to_le_bytes()).collect());
|
||
}
|
||
for k in 0..n_fat {
|
||
sectors.push(fat[k * per..(k + 1) * per].iter().flat_map(|v| v.to_le_bytes()).collect());
|
||
}
|
||
let mut out = vec![0u8; ss];
|
||
out[..8].copy_from_slice(&SIGNATURE);
|
||
out[24..26].copy_from_slice(&0x3Eu16.to_le_bytes());
|
||
out[26..28].copy_from_slice(&(if shift == 12 { 4u16 } else { 3 }).to_le_bytes());
|
||
out[28..30].copy_from_slice(&0xFFFEu16.to_le_bytes());
|
||
out[30..32].copy_from_slice(&shift.to_le_bytes());
|
||
out[32..34].copy_from_slice(&6u16.to_le_bytes());
|
||
out[44..48].copy_from_slice(&(n_fat as u32).to_le_bytes());
|
||
out[48..52].copy_from_slice(&dir_first.to_le_bytes());
|
||
out[56..60].copy_from_slice(&mini_cutoff.to_le_bytes());
|
||
out[60..64].copy_from_slice(&minifat_first.to_le_bytes());
|
||
out[64..68].copy_from_slice(&minifat_sectors.to_le_bytes());
|
||
out[68..72].copy_from_slice(&(if n_difat == 0 { ENDOFCHAIN } else { difat_first }).to_le_bytes());
|
||
out[72..76].copy_from_slice(&(n_difat as u32).to_le_bytes());
|
||
for i in 0..109 {
|
||
let v = fat_ids.get(i).copied().unwrap_or(FREESECT);
|
||
out[76 + i * 4..80 + i * 4].copy_from_slice(&v.to_le_bytes());
|
||
}
|
||
for s in sectors {
|
||
out.extend_from_slice(&s);
|
||
}
|
||
out
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
#![allow(clippy::unwrap_used)]
|
||
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn reads_streams_back() {
|
||
let big: Vec<u8> = (0..3000u32).map(|i| (i % 251) as u8).collect();
|
||
let f = build(&[("PowerPoint Document", &big), ("Current User", b"hello"), ("Pictures", &[])]);
|
||
let cf = CompoundFile::open(&f).unwrap();
|
||
assert_eq!(cf.read_root_stream("PowerPoint Document").unwrap(), big);
|
||
assert_eq!(cf.read_root_stream("current user").unwrap(), b"hello");
|
||
assert_eq!(cf.read_root_stream("Pictures").unwrap(), b"");
|
||
assert!(matches!(cf.read_root_stream("Nope"), Err(CfbError::NotFound(_))));
|
||
assert_eq!(cf.root_names().len(), 3);
|
||
}
|
||
|
||
#[test]
|
||
fn hostile_files_never_panic() {
|
||
let f = build(&[("PowerPoint Document", &[7u8; 1500]), ("Current User", b"x")]);
|
||
assert!(CompoundFile::open(b"PK\x03\x04").is_err());
|
||
for at in (0..f.len()).step_by(4) {
|
||
for v in [0u32, 1, 3, 0xFFFF_FFFA, 0xFFFF_FFFE, 0xFFFF_FFFF, 0x7FFF_FFFF] {
|
||
let mut c = f.clone();
|
||
c[at..at + 4].copy_from_slice(&v.to_le_bytes());
|
||
if let Ok(cf) = CompoundFile::open(&c) {
|
||
let _ = cf.read_root_stream("PowerPoint Document");
|
||
}
|
||
}
|
||
}
|
||
for cut in [0usize, 100, 511, 512, 1000, 2000] {
|
||
let _ = CompoundFile::open(&f[..cut.min(f.len())]);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_looping_chain_stops() {
|
||
let mut f = build(&[("PowerPoint Document", &[1u8; 1500])]);
|
||
// The FAT is the last sector; point sector 1's entry back at sector 0. The stream's size
|
||
// would be reached by going round the loop, but repeated sectors are not the stream.
|
||
let fat_at = f.len() - 512;
|
||
f[fat_at + 4..fat_at + 8].copy_from_slice(&0u32.to_le_bytes());
|
||
let cf = CompoundFile::open(&f).unwrap();
|
||
assert!(cf.read_root_stream("PowerPoint Document").is_err());
|
||
// The directory's chain looping back on itself is an error.
|
||
let mut g = build(&[("PowerPoint Document", &[1u8; 10])]);
|
||
let fat_at = g.len() - 512;
|
||
g[fat_at + 4..fat_at + 8].copy_from_slice(&1u32.to_le_bytes());
|
||
assert!(CompoundFile::open(&g).is_err());
|
||
}
|
||
|
||
/// Streams under the cutoff are read from the mini stream, through the mini FAT.
|
||
#[test]
|
||
fn reads_mini_streams() {
|
||
let big: Vec<u8> = (0..5000u32).map(|i| (i % 251) as u8).collect();
|
||
let small: Vec<u8> = (0..200u8).collect();
|
||
let f = build_with(&[("PowerPoint Document", &big), ("Current User", &small), ("Tiny", b"x")], 9, 4096);
|
||
let cf = CompoundFile::open(&f).unwrap();
|
||
assert!(!cf.minifat.is_empty() && !cf.mini_stream.is_empty(), "the small streams went in the mini stream");
|
||
assert_eq!(cf.read_root_stream("PowerPoint Document").unwrap(), big);
|
||
assert_eq!(cf.read_root_stream("Current User").unwrap(), small);
|
||
assert_eq!(cf.read_root_stream("Tiny").unwrap(), b"x");
|
||
}
|
||
|
||
/// Version 4 files use 4096-byte sectors, the header filling the first.
|
||
#[test]
|
||
fn reads_4096_byte_sectors() {
|
||
let big: Vec<u8> = (0..10_000u32).map(|i| (i % 253) as u8).collect();
|
||
let f = build_with(&[("PowerPoint Document", &big), ("Current User", b"hello")], 12, 4096);
|
||
let cf = CompoundFile::open(&f).unwrap();
|
||
assert_eq!(cf.sector_size, 4096);
|
||
assert_eq!(cf.read_root_stream("PowerPoint Document").unwrap(), big);
|
||
assert_eq!(cf.read_root_stream("Current User").unwrap(), b"hello");
|
||
}
|
||
|
||
/// Past 109 FAT sectors (about 7 MB at 512-byte sectors), the rest are found through the
|
||
/// DIFAT chain.
|
||
#[test]
|
||
fn reads_fat_sectors_listed_in_the_difat() {
|
||
let big: Vec<u8> = (0..7_500_000u32).map(|i| (i % 249) as u8).collect();
|
||
let f = build_with(&[("PowerPoint Document", &big)], 9, 0);
|
||
assert_ne!(u32_at(&f, 68), Some(ENDOFCHAIN), "the file has a DIFAT chain");
|
||
let cf = CompoundFile::open(&f).unwrap();
|
||
assert_eq!(cf.read_root_stream("PowerPoint Document").unwrap(), big);
|
||
}
|
||
}
|