Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -169,14 +169,9 @@ jobs:
with:
path: dist
merge-multiple: true
- name: Cache release signer
id: signer
uses: actions/cache@v6
with:
path: ~/.cargo/bin/rsign
key: rsign2-0.6.7-${{ runner.os }}-${{ runner.arch }}-v1
- name: Install release signer
if: steps.signer.outputs.cache-hit != 'true'
# Built fresh on every release: a cached binary could be replaced by any
# workflow that can write this repository's Actions cache.
run: cargo install rsign2 --locked --version 0.6.7
- name: Record package sizes
run: |
Expand Down
6 changes: 5 additions & 1 deletion src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -822,7 +822,11 @@ fn office(spec: &JobSpec, toolbox: &Toolbox, cancel: &AtomicBool) -> Result<(),
run_plain(soffice, &args, cancel)?;
let ext = "pdf";
let stem = input.file_stem().ok_or(JobError::NoOutput)?;
let produced = staging.path().join(stem).with_extension(ext);
// LibreOffice replaces only the last extension: "a.v2.doc" becomes "a.v2.pdf".
let mut name = stem.to_os_string();
name.push(".");
name.push(ext);
let produced = staging.path().join(name);
if !produced.is_file() {
return Err(JobError::NoOutput);
}
Expand Down
8 changes: 7 additions & 1 deletion src/externals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,13 @@ fn bundled_dirs() -> Vec<PathBuf> {
/// so a release always runs the exact tools it shipped with.
fn find_program(names: &[&str]) -> Option<PathBuf> {
let path_dirs = std::env::var_os("PATH")
.map(|path| std::env::split_paths(&path).collect::<Vec<_>>())
// Empty or relative entries mean "the current folder", which may hold
// downloaded files; only absolute folders are searched.
.map(|path| {
std::env::split_paths(&path)
.filter(|d| d.is_absolute())
.collect::<Vec<_>>()
})
.unwrap_or_default();
let dirs: Vec<PathBuf> = bundled_dirs().into_iter().chain(path_dirs).collect();
names.iter().find_map(|name| {
Expand Down
3 changes: 2 additions & 1 deletion src/ffmpeg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ fn add_input(args: &mut Vec<OsString>, path: &Path, demuxer: Option<&str>) {
args.extend(["-f".into(), format.into()]);
}
if demuxer.is_none() {
args.extend(["-protocol_whitelist".into(), "file,pipe".into()]);
// Same set as conversion inputs: local files and AES-128 HLS segments.
args.extend(["-protocol_whitelist".into(), "file,pipe,crypto".into()]);
}
args.extend(["-i".into(), input_url(path, demuxer)]);
}
Expand Down
197 changes: 169 additions & 28 deletions src/office.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const MAX_PART_BYTES: u64 = 64 << 20;
const MAX_PPTX_CONTENT_BYTES: usize = 128 << 20;
/// Largest plain-text input read whole.
const MAX_TEXT_BYTES: u64 = 32 << 20;
/// Bound nested DOCX table state and total bytes copied while flattening tables.
/// Bound nested DOCX and ODF table state and total bytes copied while flattening tables.
const MAX_DOCX_TABLE_DEPTH: usize = 32;
const MAX_DOCX_TABLE_COPY_BYTES: usize = 64 << 20;
/// Spreadsheet rows rendered per sheet.
Expand Down Expand Up @@ -185,35 +185,50 @@ struct DocxState {
tables: Vec<Vec<Vec<String>>>,
row: Vec<String>,
cell: String,
/// The enclosing row and cell, saved while a nested table is read.
outer: Vec<(Vec<String>, String)>,
table_copy_bytes: usize,
}

/// Appends `text` to a table cell, charging `copied` before any byte is copied.
fn append_budgeted(cell: &mut String, copied: &mut usize, text: &str) -> Result<(), OfficeError> {
*copied = copied
.checked_add(text.len())
.filter(|&bytes| bytes <= MAX_DOCX_TABLE_COPY_BYTES)
.ok_or_else(|| corrupt("nested table copy limit exceeded"))?;
cell.push_str(text);
Ok(())
}

/// Appends a nested table to its parent cell as text: cells joined with ` | `,
/// rows with line breaks. Every copied byte, including separators, is charged
/// before allocation; the budget is shared across the entire document.
fn append_nested_rows(
cell: &mut String,
copied: &mut usize,
rows: &[Vec<String>],
) -> Result<(), OfficeError> {
for (row_index, row) in rows.iter().enumerate() {
if row_index > 0 {
append_budgeted(cell, copied, "\n")?;
}
for (cell_index, text) in row.iter().enumerate() {
if cell_index > 0 {
append_budgeted(cell, copied, " | ")?;
}
append_budgeted(cell, copied, text)?;
}
}
Ok(())
}

impl DocxState {
fn append_nested_text(&mut self, text: &str) -> Result<(), OfficeError> {
self.table_copy_bytes = self
.table_copy_bytes
.checked_add(text.len())
.filter(|&bytes| bytes <= MAX_DOCX_TABLE_COPY_BYTES)
.ok_or_else(|| corrupt("DOCX nested table copy limit exceeded"))?;
self.cell.push_str(text);
Ok(())
append_budgeted(&mut self.cell, &mut self.table_copy_bytes, text)
}

fn append_nested_table(&mut self, rows: &[Vec<String>]) -> Result<(), OfficeError> {
// Append directly so every copied byte, including separators, is charged
// before allocation. The budget is shared across the entire document.
for (row_index, row) in rows.iter().enumerate() {
if row_index > 0 {
self.append_nested_text("\n")?;
}
for (cell_index, cell) in row.iter().enumerate() {
if cell_index > 0 {
self.append_nested_text(" | ")?;
}
self.append_nested_text(cell)?;
}
}
Ok(())
append_nested_rows(&mut self.cell, &mut self.table_copy_bytes, rows)
}

fn push_text(&mut self, text: &str) {
Expand Down Expand Up @@ -282,6 +297,10 @@ fn docx_blocks(xml: &str) -> Result<Vec<Block>, OfficeError> {
if st.tables.len() >= MAX_DOCX_TABLE_DEPTH {
return Err(corrupt("DOCX table nesting limit exceeded"));
}
if !st.tables.is_empty() {
let saved = (std::mem::take(&mut st.row), std::mem::take(&mut st.cell));
st.outer.push(saved);
}
st.tables.push(Vec::new());
}
"tr" => st.row.clear(),
Expand Down Expand Up @@ -312,6 +331,13 @@ fn docx_blocks(xml: &str) -> Result<Vec<Block>, OfficeError> {
if st.tables.is_empty() {
st.blocks.push(Block::Table(rows));
} else {
if let Some((row, cell)) = st.outer.pop() {
st.row = row;
st.cell = cell;
}
if !st.cell.is_empty() {
st.append_nested_text("\n")?;
}
// A nested table becomes text inside its parent cell.
st.append_nested_table(&rows)?;
}
Expand All @@ -337,6 +363,9 @@ fn odf_blocks(xml: &str) -> Result<Vec<Block>, OfficeError> {
let mut tables: Vec<Vec<Vec<String>>> = Vec::new();
let mut row: Vec<String> = Vec::new();
let mut cell = String::new();
// The enclosing row and cell, saved while a nested table is read.
let mut outer: Vec<(Vec<String>, String)> = Vec::new();
let mut copied = 0usize;
loop {
match reader.read_event().map_err(corrupt)? {
Event::Start(e) => match e.local_name().as_ref() {
Expand All @@ -348,7 +377,15 @@ fn odf_blocks(xml: &str) -> Result<Vec<Block>, OfficeError> {
}
"p" => depth_text += 1,
"list" => list_depth += 1,
"table" => tables.push(Vec::new()),
"table" => {
if tables.len() >= MAX_DOCX_TABLE_DEPTH {
return Err(corrupt("ODF table nesting limit exceeded"));
}
if !tables.is_empty() {
outer.push((std::mem::take(&mut row), std::mem::take(&mut cell)));
}
tables.push(Vec::new());
}
"table-row" => row.clear(),
"table-cell" => cell.clear(),
"page" if !blocks.is_empty() => blocks.push(Block::PageBreak),
Expand Down Expand Up @@ -399,7 +436,16 @@ fn odf_blocks(xml: &str) -> Result<Vec<Block>, OfficeError> {
}
"table" => {
if let Some(rows) = tables.pop() {
blocks.push(Block::Table(rows));
if tables.is_empty() {
blocks.push(Block::Table(rows));
} else if let Some((outer_row, outer_cell)) = outer.pop() {
// A nested table becomes text inside its parent cell.
(row, cell) = (outer_row, outer_cell);
if !cell.is_empty() {
append_budgeted(&mut cell, &mut copied, "\n")?;
}
append_nested_rows(&mut cell, &mut copied, &rows)?;
}
}
}
_ => {}
Expand Down Expand Up @@ -721,14 +767,21 @@ fn rtf_text(rtf: &str) -> String {
// Brace depth at which an ignored group started, if any.
let mut skip_from: Option<usize> = None;
let mut depth = 0usize;
// Fallback units after each `\uN` (`\ucN`, scoped to its group; default 1).
let mut uc = 1usize;
let mut outer_uc: Vec<usize> = Vec::new();
while let Some(c) = chars.next() {
match c {
'{' => depth += 1,
'{' => {
depth += 1;
outer_uc.push(uc);
}
'}' => {
if skip_from == Some(depth) {
skip_from = None;
}
depth = depth.saturating_sub(1);
uc = outer_uc.pop().unwrap_or(1);
}
'\\' => {
let mut word = String::new();
Expand Down Expand Up @@ -771,6 +824,9 @@ fn rtf_text(rtf: &str) -> String {
if chars.peek() == Some(&' ') {
chars.next();
}
if word == "uc" {
uc = param.parse().unwrap_or(1);
}
if SKIP_GROUPS.contains(&word.as_str()) && skip_from.is_none() {
skip_from = Some(depth);
}
Expand All @@ -786,9 +842,28 @@ fn rtf_text(rtf: &str) -> String {
{
out.push(ch);
}
// Skip the plain-text fallback that follows a Unicode escape.
if chars.peek().is_some_and(|c| !matches!(c, '\\' | '{' | '}')) {
chars.next();
// Skip the `\ucN` fallback units that follow a Unicode
// escape: each is one character, one `\'hh` escape (what
// Word writes) or one escaped symbol such as `\{`.
// `\uc0` means there is none.
for _ in 0..uc {
match chars.peek() {
Some('\\') => {
let mut ahead = chars.clone();
ahead.next();
let len = match ahead.peek() {
Some('\'') => 4,
Some(c) if !c.is_ascii_alphabetic() => 2,
// A control word ends the fallback.
_ => break,
};
chars.by_ref().take(len).for_each(drop);
}
Some('{' | '}') | None => break,
Some(_) => {
chars.next();
}
}
}
}
_ => {}
Expand Down Expand Up @@ -1126,6 +1201,54 @@ mod tests {
assert_eq!(st.cell, "a | b\ncd", "reject before copying");
}

#[test]
fn docx_nested_table_keeps_outer_cells() {
let xml = r#"<w:document xmlns:w="w"><w:body><w:tbl><w:tr>
<w:tc><w:p><w:r><w:t>A</w:t></w:r></w:p></w:tc>
<w:tc><w:p><w:r><w:t>before</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:p><w:r><w:t>x</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>y</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:tc>
<w:tc><w:p><w:r><w:t>C</w:t></w:r></w:p></w:tc>
</w:tr></w:tbl></w:body></w:document>"#;
assert_eq!(
docx_blocks(xml).expect("parse"),
vec![Block::Table(vec![vec![
"A".into(),
"before\nx | y".into(),
"C".into()
]])]
);
}

#[test]
fn odf_nested_table_keeps_outer_cells() {
let xml = r#"<office:document-content xmlns:office="o" xmlns:text="t" xmlns:table="b"><office:body><office:text>
<table:table><table:table-row>
<table:table-cell><text:p>A</text:p></table:table-cell>
<table:table-cell><text:p>before</text:p><table:table><table:table-row><table:table-cell><text:p>x</text:p></table:table-cell><table:table-cell><text:p>y</text:p></table:table-cell></table:table-row></table:table></table:table-cell>
<table:table-cell><text:p>C</text:p></table:table-cell>
</table:table-row></table:table>
</office:text></office:body></office:document-content>"#;
assert_eq!(
odf_blocks(xml).expect("parse"),
vec![Block::Table(vec![vec![
"A".into(),
"before\nx | y".into(),
"C".into()
]])]
);
}

#[test]
fn odf_nested_payload_hits_copy_budget_before_copying() {
let xml = format!(
"{}<text:p>{}</text:p>{}",
"<table:table><table:table-row><table:table-cell>".repeat(18),
"x".repeat(4 << 20),
"</table:table-cell></table:table-row></table:table>".repeat(18)
);
assert!(matches!(odf_blocks(&xml),
Err(OfficeError::Corrupt(message)) if message.contains("copy limit")));
}

#[test]
fn odf_reads_headings_spaces_and_tables() {
let xml = r#"<office:document-content xmlns:office="o" xmlns:text="t" xmlns:table="b"><office:body><office:text>
Expand Down Expand Up @@ -1216,6 +1339,24 @@ mod tests {
assert!(!text.contains("Arial"));
}

#[test]
fn rtf_word_unicode_fallbacks_are_skipped() {
// Word writes each non-ASCII letter as \uN followed by a \'hh fallback.
let rtf = r"{\rtf1\ansi\ansicpg1251\uc1 \u1055\'cf\u1088\'f0\u1080\'e8 \u1513\'f9!}";
assert_eq!(rtf_text(rtf), "При ש!");
}

#[test]
fn rtf_fallback_count_follows_uc_and_its_group() {
// `\uc0` means no fallback, so the hex escape is real text.
assert_eq!(rtf_text(r"{\rtf1\ansi\uc0\u945\'42}"), "αB");
// `\ucN` is scoped to its group and restored when the group ends.
let rtf = r"{\uc2\u945ab{\uc0\u946\'43}\u947xyZ}";
assert_eq!(rtf_text(rtf), "αβCγZ");
// An escaped symbol such as `\{` is one whole fallback unit.
assert_eq!(rtf_text(r"{\rtf1\ansi\uc2\u945\'61\{Z}"), "αZ");
}

#[test]
fn docx_round_trip_through_writer_and_reader() {
let dir = tempfile::tempdir().expect("tempdir");
Expand Down
12 changes: 9 additions & 3 deletions src/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,11 @@ impl Args {
}

fn input(self, path: &Path) -> Self {
self.flag("-i", input_url(path, None))
// A crafted playlist or container must not make ffmpeg open URLs or
// other protocols: user files may only read local files. `crypto`
// decrypts local AES-128 HLS segments and can only wrap those.
self.flag("-protocol_whitelist", "file,pipe,crypto")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.flag("-i", input_url(path, None))
}

fn output(mut self, path: &Path) -> PendingPlan {
Expand Down Expand Up @@ -2132,7 +2136,9 @@ mod tests {
)
.unwrap();
let cmd = joined(&p);
assert!(cmd.contains("-loop 1 -framerate 30 -i file:/in/photo.png"));
assert!(cmd.contains(
"-loop 1 -framerate 30 -protocol_whitelist file,pipe,crypto -i file:/in/photo.png"
));
assert!(cmd.contains("xfade=transition=slideright:duration=1.000000:offset=1.000000"));
assert!(cmd.contains("anullsrc") && cmd.contains("acrossfade"));
assert_eq!(p.expected_secs, Some(4.0));
Expand Down Expand Up @@ -2278,7 +2284,7 @@ mod tests {
)
.expect("plan");
let cmd = joined(&p);
assert!(cmd.contains("-ss 5.000 -to 15.000 -i"));
assert!(cmd.contains("-ss 5.000 -to 15.000 -protocol_whitelist file,pipe,crypto -i"));
assert!(
cmd.contains(
"-vf crop=640:360:10:20,transpose=1,subtitles=filename=/s/it\\\\\\'s\\\\: a\\,b.srt"
Expand Down
Loading