use byteorder::{LittleEndian, ReadBytesExt};
use snafu::Snafu;
use std::io::{self, Cursor, Read};
#[derive(Debug, Snafu)]
pub enum Hwp3OleError {
#[snafu(display("입출력 오류가 발생했습니다: {source}"))]
IoError { source: io::Error },
#[snafu(display("알 수 없는 OLE 서명입니다: {signature:#X}"))]
UnknownSignature { signature: u32 },
}
impl From<io::Error> for Hwp3OleError {
fn from(error: io::Error) -> Self {
Hwp3OleError::IoError { source: error }
}
}
#[derive(Debug)]
pub struct Hwp3OleInfo {
pub signature: u32,
pub storage_data: Vec<u8>,
}
impl Hwp3OleInfo {
pub fn read<R: Read>(mut reader: R, total_length: u32) -> Result<Self, Hwp3OleError> {
if total_length < 4 {
return Err(Hwp3OleError::IoError {
source: io::Error::new(
io::ErrorKind::UnexpectedEof,
"OLE Info length is too short",
),
});
}
let signature = reader.read_u32::<LittleEndian>()?;
let mut storage_data = super::alloc_record_buf((total_length - 4) as usize)?;
reader.read_exact(&mut storage_data)?;
if signature != 0xF8995567 && signature != 0xF8995568 {
return Err(Hwp3OleError::UnknownSignature { signature });
}
Ok(Hwp3OleInfo {
signature,
storage_data,
})
}
}
#[derive(Debug)]
pub struct Hwp3OleStreamInfo {
pub width: u32, pub height: u32, pub aspect: u32, pub reserved: [u8; 116],
}
impl Default for Hwp3OleStreamInfo {
fn default() -> Self {
Self {
width: 0,
height: 0,
aspect: 0,
reserved: [0; 116],
}
}
}
impl Hwp3OleStreamInfo {
pub fn read<R: Read>(mut reader: R) -> Result<Self, io::Error> {
let width = reader.read_u32::<LittleEndian>()?;
let height = reader.read_u32::<LittleEndian>()?;
let aspect = reader.read_u32::<LittleEndian>()?;
let mut reserved = [0u8; 116];
reader.read_exact(&mut reserved)?;
Ok(Hwp3OleStreamInfo {
width,
height,
aspect,
reserved,
})
}
}
#[derive(Debug)]
pub struct Hwp3ChartConnectionInfo {
pub linked: u16, pub tblid: u16, pub entire: u32, pub startcol: u32,
pub startrow: u32,
pub endcol: u32,
pub endrow: u32,
pub chsize: u32, pub reserved: [u8; 100],
}
impl Default for Hwp3ChartConnectionInfo {
fn default() -> Self {
Self {
linked: 0,
tblid: 0,
entire: 0,
startcol: 0,
startrow: 0,
endcol: 0,
endrow: 0,
chsize: 0,
reserved: [0; 100],
}
}
}
impl Hwp3ChartConnectionInfo {
pub fn read<R: Read>(mut reader: R) -> Result<Self, io::Error> {
let linked = reader.read_u16::<LittleEndian>()?;
let tblid = reader.read_u16::<LittleEndian>()?;
let entire = reader.read_u32::<LittleEndian>()?;
let startcol = reader.read_u32::<LittleEndian>()?;
let startrow = reader.read_u32::<LittleEndian>()?;
let endcol = reader.read_u32::<LittleEndian>()?;
let endrow = reader.read_u32::<LittleEndian>()?;
let chsize = reader.read_u32::<LittleEndian>()?;
let mut reserved = [0u8; 100];
reader.read_exact(&mut reserved)?;
Ok(Hwp3ChartConnectionInfo {
linked,
tblid,
entire,
startcol,
startrow,
endcol,
endrow,
chsize,
reserved,
})
}
}
pub fn extract_ole_payloads(cfb_bytes: &[u8]) -> Vec<(String, Vec<u8>)> {
let mut out = Vec::new();
let Ok(mut comp) = cfb::CompoundFile::open(Cursor::new(cfb_bytes.to_vec())) else {
return out;
};
let root = std::path::Path::new("/");
let storages: Vec<(std::path::PathBuf, [u8; 16])> = comp
.walk()
.filter(|e| e.is_storage() && !e.is_root())
.filter(|e| e.path().parent() == Some(root))
.map(|e| (e.path().to_path_buf(), e.clsid().to_bytes_le()))
.collect();
for (storage, storage_clsid) in storages {
let Some(name) = storage
.file_name()
.map(|n| n.to_string_lossy().to_string())
.filter(|n| !n.is_empty())
else {
continue;
};
let stream_paths: Vec<(String, std::path::PathBuf)> = comp
.walk()
.filter(|e| e.is_stream())
.filter(|e| e.path().parent() == Some(storage.as_path()))
.filter_map(|e| {
e.path()
.file_name()
.map(|n| (n.to_string_lossy().to_string(), e.path().to_path_buf()))
})
.collect();
let mut named: Vec<(String, Vec<u8>)> = Vec::new();
for (stream_name, path) in stream_paths {
let Ok(mut stream) = comp.open_stream(&path) else {
continue;
};
let mut buf = Vec::new();
if stream.read_to_end(&mut buf).is_ok() {
named.push((stream_name, buf));
}
}
if named.is_empty() {
continue;
}
let refs: Vec<(&str, &[u8])> = named
.iter()
.map(|(n, d)| (n.as_str(), d.as_slice()))
.collect();
if let Ok(bytes) =
crate::serializer::mini_cfb::build_cfb_with_root_clsid(&refs, storage_clsid)
{
out.push((name, bytes));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn stamp_named_entry_clsid(cfb: &mut [u8], target: &str, clsid: [u8; 16]) {
let mut at = 512;
while at + 128 <= cfb.len() {
let name_len = u16::from_le_bytes([cfb[at + 64], cfb[at + 65]]) as usize;
if name_len >= 2 && name_len <= 64 {
let units: Vec<u16> = cfb[at..at + name_len - 2]
.chunks_exact(2)
.map(|c| u16::from_le_bytes([c[0], c[1]]))
.collect();
if String::from_utf16_lossy(&units) == target {
cfb[at + 80..at + 96].copy_from_slice(&clsid);
return;
}
}
at += 128;
}
panic!("디렉터리 엔트리 '{target}' 를 찾지 못했다");
}
#[test]
fn task4097_promoted_sub_storage_clsid_becomes_the_new_root_clsid() {
const CLSID: [u8; 16] = [
0x14, 0x42, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x46,
];
let mut src = crate::serializer::mini_cfb::build_cfb(&[
("/00000000.OOO/Contents", &[1u8; 64][..]),
("/00000000.OOO/\u{2}OlePres000", &[2u8; 64][..]),
])
.expect("합성 CFB");
stamp_named_entry_clsid(&mut src, "00000000.OOO", CLSID);
let out = extract_ole_payloads(&src);
assert_eq!(out.len(), 1, "root 직속 서브 스토리지 1건이 승격되어야 함");
assert_eq!(out[0].0, "00000000.OOO");
assert_eq!(
crate::parser::cfb_reader::root_clsid(&out[0].1),
Some(CLSID),
"승격된 서브 스토리지의 CLSID 가 새 루트로 옮겨져야 한다 (#4097)"
);
let container = crate::parser::ole_container::parse_ole_container(&out[0].1)
.expect("재포장본을 parse_ole_container 가 열 수 있어야 함");
assert!(container.raw_contents.is_some(), "Contents 유지");
}
#[test]
fn task4097_zero_sub_storage_clsid_stays_zero() {
let src = crate::serializer::mini_cfb::build_cfb(&[("/OBJ/Contents", &[3u8; 32][..])])
.expect("합성 CFB");
let out = extract_ole_payloads(&src);
assert_eq!(out.len(), 1);
assert_eq!(
crate::parser::cfb_reader::root_clsid(&out[0].1),
Some([0u8; 16])
);
}
}