use crate::parser::ole_container::{all_ole_streams, ole_root_clsid};
use crate::serializer::mini_cfb::build_cfb_with_root_clsid;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OleRepackError {
NotACompoundFile,
RootClsidUnreadable,
StreamNotFound(String),
Rebuild(String),
}
impl std::fmt::Display for OleRepackError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotACompoundFile => write!(f, "중첩 OLE 가 CFB 로 열리지 않는다"),
Self::RootClsidUnreadable => write!(f, "중첩 CFB 의 루트 CLSID 를 읽지 못했다"),
Self::StreamNotFound(name) => write!(f, "중첩 CFB 에 스트림 `{name}` 이 없다"),
Self::Rebuild(msg) => write!(f, "중첩 CFB 재포장 실패: {msg}"),
}
}
}
fn normalized(path: &str) -> &str {
path.trim_start_matches('/')
}
pub fn replace_ole_stream(
original: &[u8],
stream_name: &str,
new_bytes: &[u8],
) -> Result<Vec<u8>, OleRepackError> {
let mut streams = all_ole_streams(original).ok_or(OleRepackError::NotACompoundFile)?;
let target = normalized(stream_name);
let slot = streams
.iter_mut()
.find(|(path, _)| normalized(path) == target)
.ok_or_else(|| OleRepackError::StreamNotFound(stream_name.to_string()))?;
if slot.1 == new_bytes {
return Ok(original.to_vec());
}
slot.1 = new_bytes.to_vec();
let clsid = ole_root_clsid(original).ok_or(OleRepackError::RootClsidUnreadable)?;
let refs: Vec<(&str, &[u8])> = streams
.iter()
.map(|(name, data)| (name.as_str(), data.as_slice()))
.collect();
build_cfb_with_root_clsid(&refs, clsid).map_err(OleRepackError::Rebuild)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::serializer::mini_cfb::build_cfb;
const CLSID: [u8; 16] = [
0x37, 0xa1, 0x3d, 0x4c, 0x90, 0xdc, 0xb9, 0x47, 0x9b, 0xed, 0x59, 0xda, 0xe3, 0x52, 0xa2,
0x80,
];
fn sample() -> Vec<u8> {
build_cfb_with_root_clsid(
&[
("OOXMLChartContents", b"<c:chartSpace/>".as_slice()),
("Contents", b"legacy-grid".as_slice()),
("\u{2}OlePres000", b"emf-preview".as_slice()),
],
CLSID,
)
.expect("샘플 CFB")
}
fn stream(cfb: &[u8], name: &str) -> Option<Vec<u8>> {
all_ole_streams(cfb)?
.into_iter()
.find(|(p, _)| normalized(p) == name)
.map(|(_, d)| d)
}
#[test]
fn replaces_only_the_named_stream() {
let original = sample();
let out = replace_ole_stream(&original, "OOXMLChartContents", b"<c:new/>").expect("재포장");
assert_eq!(
stream(&out, "OOXMLChartContents").as_deref(),
Some(&b"<c:new/>"[..])
);
assert_eq!(
stream(&out, "Contents").as_deref(),
Some(&b"legacy-grid"[..])
);
assert_eq!(
stream(&out, "\u{2}OlePres000").as_deref(),
Some(&b"emf-preview"[..])
);
}
#[test]
fn preserves_the_root_clsid() {
let original = sample();
let out = replace_ole_stream(&original, "OOXMLChartContents", b"<c:new/>").expect("재포장");
assert_eq!(ole_root_clsid(&out), Some(CLSID));
}
#[test]
fn identical_content_is_not_repacked() {
let original = sample();
let out = replace_ole_stream(&original, "OOXMLChartContents", b"<c:chartSpace/>")
.expect("재포장");
assert_eq!(out, original, "바뀐 게 없으면 원본 바이트 그대로여야 한다");
}
#[test]
fn repacking_is_not_byte_preserving() {
let original = sample();
let streams = all_ole_streams(&original).expect("열거");
let refs: Vec<(&str, &[u8])> = streams
.iter()
.map(|(n, d)| (n.as_str(), d.as_slice()))
.collect();
let repacked = build_cfb_with_root_clsid(&refs, CLSID).expect("재포장");
assert_eq!(
stream(&repacked, "Contents").as_deref(),
Some(&b"legacy-grid"[..])
);
}
#[test]
fn leading_slash_is_ignored_in_the_name() {
let original = sample();
let a =
replace_ole_stream(&original, "OOXMLChartContents", b"<c:x/>").expect("슬래시 없이");
let b =
replace_ole_stream(&original, "/OOXMLChartContents", b"<c:x/>").expect("슬래시 붙여");
assert_eq!(a, b);
}
#[test]
fn missing_stream_is_refused_not_created() {
let original = sample();
assert_eq!(
replace_ole_stream(&original, "OOXMLChartContent", b"x"),
Err(OleRepackError::StreamNotFound(
"OOXMLChartContent".to_string()
))
);
}
#[test]
fn non_cfb_input_is_refused() {
assert_eq!(
replace_ole_stream(b"not a cfb at all", "Contents", b"x"),
Err(OleRepackError::NotACompoundFile)
);
}
#[test]
fn zero_root_clsid_stays_zero() {
let original = build_cfb(&[("Contents", b"x".as_slice())]).expect("CFB");
let out = replace_ole_stream(&original, "Contents", b"y").expect("재포장");
assert_eq!(ole_root_clsid(&out), Some([0u8; 16]));
}
}