use cfb::CompoundFile;
use std::io::{Cursor, Read};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeImageKind {
Bmp,
Png,
Jpeg,
Gif,
}
impl NativeImageKind {
pub fn mime(&self) -> &'static str {
match self {
Self::Bmp => "image/bmp",
Self::Png => "image/png",
Self::Jpeg => "image/jpeg",
Self::Gif => "image/gif",
}
}
}
#[derive(Debug, Clone, Default)]
pub struct OleContainer {
pub preview_emf: Option<Vec<u8>>,
pub preview_wmf: Option<Vec<u8>>,
pub ooxml_chart: Option<Vec<u8>>,
pub raw_contents: Option<Vec<u8>>,
pub native_image: Option<(NativeImageKind, Vec<u8>)>,
}
impl OleContainer {
pub fn has_ooxml_chart(&self) -> bool {
self.ooxml_chart.as_ref().is_some_and(|b| !b.is_empty())
}
pub fn has_preview(&self) -> bool {
self.preview_emf.as_ref().is_some_and(|b| !b.is_empty())
|| self.preview_wmf.as_ref().is_some_and(|b| !b.is_empty())
}
}
pub fn parse_ole_container(cfb_bytes: &[u8]) -> Option<OleContainer> {
if cfb_bytes.len() < 8 {
return None;
}
const CFB_MAGIC: [u8; 4] = [0xD0, 0xCF, 0x11, 0xE0];
let cfb_bytes = if cfb_bytes[0..4] != CFB_MAGIC
&& cfb_bytes.len() >= 12
&& cfb_bytes[4..8] == CFB_MAGIC
&& u32::from_le_bytes([cfb_bytes[0], cfb_bytes[1], cfb_bytes[2], cfb_bytes[3]]) as usize
== cfb_bytes.len() - 4
{
&cfb_bytes[4..]
} else {
cfb_bytes
};
let cursor = Cursor::new(cfb_bytes);
let mut comp = CompoundFile::open(cursor).ok()?;
let mut container = OleContainer::default();
let entries: Vec<String> = comp
.walk()
.filter(|e| e.is_stream())
.map(|e| e.path().to_string_lossy().to_string())
.collect();
for path in entries {
let name = path.trim_start_matches('/');
if name == "\u{0002}OlePres000" || name.ends_with("OlePres000") {
if let Ok(mut s) = comp.open_stream(&path) {
let mut buf = Vec::new();
if s.read_to_end(&mut buf).is_ok() {
container.preview_emf = strip_ole_presentation_header(&buf);
container.preview_wmf = strip_ole_presentation_header_wmf(&buf);
}
}
} else if name == "OOXMLChartContents" {
if let Ok(mut s) = comp.open_stream(&path) {
let mut buf = Vec::new();
if s.read_to_end(&mut buf).is_ok() && !buf.is_empty() {
container.ooxml_chart = Some(buf);
}
}
} else if name.eq_ignore_ascii_case("contents") {
if let Ok(mut s) = comp.open_stream(&path) {
let mut buf = Vec::new();
if s.read_to_end(&mut buf).is_ok() && !buf.is_empty() {
container.raw_contents = Some(buf);
}
}
} else if name == "\u{0001}Ole10Native" || name.ends_with("Ole10Native") {
if let Ok(mut s) = comp.open_stream(&path) {
let mut buf = Vec::new();
if s.read_to_end(&mut buf).is_ok() && buf.len() > 4 {
let inner = &buf[4..];
if let Some(img) = detect_native_image(inner) {
container.native_image = Some(img);
}
}
}
}
}
if container.preview_emf.is_none() && container.native_image.is_none() {
if let Ok(entries) = std::panic::catch_unwind(|| {
let cursor = Cursor::new(cfb_bytes);
CompoundFile::open(cursor).ok().map(|comp| {
comp.walk()
.filter(|e| e.is_stream())
.map(|e| e.path().to_string_lossy().to_string())
.collect::<Vec<_>>()
})
}) {
if let Some(Some(paths)) = Some(entries) {
let cursor = Cursor::new(cfb_bytes);
if let Ok(mut comp2) = CompoundFile::open(cursor) {
for path in &paths {
let name = path.trim_start_matches('/');
if name == "\u{0002}OlePres000" || name.ends_with("OlePres000") {
if let Ok(mut s) = comp2.open_stream(path) {
let mut buf = Vec::new();
if s.read_to_end(&mut buf).is_ok() {
if let Some(bmp) = extract_dib_as_bmp(&buf) {
container.native_image = Some((NativeImageKind::Bmp, bmp));
break;
}
}
}
}
}
}
}
}
}
if container.preview_emf.is_some()
|| container.preview_wmf.is_some()
|| container.ooxml_chart.is_some()
|| container.raw_contents.is_some()
|| container.native_image.is_some()
{
Some(container)
} else {
None
}
}
pub fn is_hmapsi_ole_container(cfb_bytes: &[u8]) -> bool {
contains_bytes(cfb_bytes, b"HMapsi") || contains_bytes(cfb_bytes, b"Hmapsi file")
}
pub fn ole_root_clsid(cfb_bytes: &[u8]) -> Option<[u8; 16]> {
crate::parser::cfb_reader::root_clsid(cfb_bytes)
}
pub fn all_ole_streams(cfb_bytes: &[u8]) -> Option<Vec<(String, Vec<u8>)>> {
if cfb_bytes.len() < 8 {
return None;
}
let mut comp = CompoundFile::open(Cursor::new(cfb_bytes)).ok()?;
let paths: Vec<std::path::PathBuf> = comp
.walk()
.filter(|e| e.is_stream())
.map(|e| e.path().to_path_buf())
.collect();
let mut out = Vec::with_capacity(paths.len());
for path in paths {
let mut buf = Vec::new();
let mut stream = comp.open_stream(&path).ok()?;
stream.read_to_end(&mut buf).ok()?;
out.push((path.to_string_lossy().replace('\\', "/"), buf));
}
Some(out)
}
fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle)
}
pub fn parse_equation_contents_script(data: &[u8]) -> Option<String> {
const SIG: &[u8] = b"Hwp 5.0 Equation Editor";
if data.len() < 72 || !data.starts_with(SIG) {
return None;
}
let len = u32::from_le_bytes([data[68], data[69], data[70], data[71]]) as usize;
if len == 0 || !len.is_multiple_of(2) || data.len() < 72 + len {
return None;
}
let units: Vec<u16> = data[72..72 + len]
.chunks_exact(2)
.map(|c| u16::from_le_bytes([c[0], c[1]]))
.collect();
let script = String::from_utf16_lossy(&units)
.trim_end_matches('\0')
.to_string();
if script.trim().is_empty() {
None
} else {
Some(script)
}
}
pub fn raw_contents_is_wmf(data: &[u8]) -> bool {
if data.len() < 18 {
return false;
}
if data.starts_with(&[0xD7, 0xCD, 0xC6, 0x9A]) {
return true;
}
let mt_type = u16::from_le_bytes([data[0], data[1]]);
let header_size = u16::from_le_bytes([data[2], data[3]]);
let version = u16::from_le_bytes([data[4], data[5]]);
(mt_type == 1 || mt_type == 2) && header_size == 9 && (version == 0x0100 || version == 0x0300)
}
pub fn raw_contents_is_emf(data: &[u8]) -> bool {
contents_emf_payload(data).is_some()
}
pub fn contents_emf_payload(data: &[u8]) -> Option<&[u8]> {
fn emf_header_at(data: &[u8], at: usize) -> bool {
data.len() >= at + 44
&& u32::from_le_bytes([data[at], data[at + 1], data[at + 2], data[at + 3]]) == 1
&& &data[at + 40..at + 44] == b" EMF"
}
if emf_header_at(data, 0) {
return Some(data);
}
if data.len() >= 8 {
let declared = u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
if (44..=data.len()).contains(&declared) && emf_header_at(data, 4) {
return Some(&data[4..]);
}
}
None
}
pub fn detect_native_image(data: &[u8]) -> Option<(NativeImageKind, Vec<u8>)> {
if data.len() < 4 {
return None;
}
if data.starts_with(b"BM") {
return Some((NativeImageKind::Bmp, data.to_vec()));
}
if data.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
return Some((NativeImageKind::Png, data.to_vec()));
}
if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
return Some((NativeImageKind::Jpeg, data.to_vec()));
}
if data.starts_with(b"GIF8") {
return Some((NativeImageKind::Gif, data.to_vec()));
}
None
}
fn extract_dib_as_bmp(data: &[u8]) -> Option<Vec<u8>> {
let scan_limit = data.len().min(4096);
for i in 0..scan_limit.saturating_sub(40) {
let bi_size = u32::from_le_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]);
if bi_size != 40 {
continue;
}
let w = i32::from_le_bytes([data[i + 4], data[i + 5], data[i + 6], data[i + 7]]);
let h = i32::from_le_bytes([data[i + 8], data[i + 9], data[i + 10], data[i + 11]]);
if w <= 0 || w > 100_000 || h.abs() == 0 || h.abs() > 100_000 {
continue;
}
let bit_count = u16::from_le_bytes([data[i + 14], data[i + 15]]);
if !matches!(bit_count, 1 | 4 | 8 | 16 | 24 | 32) {
continue;
}
let compression =
u32::from_le_bytes([data[i + 16], data[i + 17], data[i + 18], data[i + 19]]);
let clr_used = u32::from_le_bytes([data[i + 32], data[i + 33], data[i + 34], data[i + 35]]);
let palette_entries = if bit_count <= 8 {
if clr_used > 0 && clr_used <= 256 {
clr_used
} else {
1u32 << bit_count
}
} else {
0
};
let palette_bytes = palette_entries * 4;
let dib_and_data = &data[i..];
let offset_to_pixels = 14 + 40 + palette_bytes as usize;
let file_size = 14 + dib_and_data.len() as u32;
let mut bmp = Vec::with_capacity(file_size as usize);
bmp.extend_from_slice(b"BM");
bmp.extend_from_slice(&file_size.to_le_bytes());
bmp.extend_from_slice(&[0u8; 4]); bmp.extend_from_slice(&(offset_to_pixels as u32).to_le_bytes());
bmp.extend_from_slice(dib_and_data);
let _ = compression;
return Some(bmp);
}
None
}
pub fn strip_ole_presentation_header(data: &[u8]) -> Option<Vec<u8>> {
if data.len() < 64 {
return None;
}
if let Some(emf) = emf_from_wmf_comment_chunks(data) {
return Some(emf);
}
let scan_limit = data.len().min(4096);
for i in 0..(scan_limit.saturating_sub(44)) {
let type_ok = u32::from_le_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]) == 1;
if !type_ok {
continue;
}
let sig = &data[i + 40..i + 44];
if sig == b" EMF" {
return Some(data[i..].to_vec());
}
}
None
}
fn strip_ole_presentation_header_wmf(data: &[u8]) -> Option<Vec<u8>> {
wmf_start_offset(data).map(|at| data[at..].to_vec())
}
fn wmf_start_offset(data: &[u8]) -> Option<usize> {
if data.len() < 26 {
return None;
}
let scan_limit = data.len().min(4096);
for i in 0..(scan_limit.saturating_sub(8)) {
if data[i..i + 4] == [0xD7, 0xCD, 0xC6, 0x9A] {
return Some(i);
}
let mt_type = u16::from_le_bytes([data[i], data[i + 1]]);
let header_size = u16::from_le_bytes([data[i + 2], data[i + 3]]);
let version = u16::from_le_bytes([data[i + 4], data[i + 5]]);
if (mt_type == 1 || mt_type == 2)
&& header_size == 9
&& (version == 0x0100 || version == 0x0300)
{
return Some(i);
}
}
None
}
pub(crate) fn emf_from_wmf_comment_chunks(data: &[u8]) -> Option<Vec<u8>> {
const META_ESCAPE: u16 = 0x0626;
const ENHANCED_METAFILE: u16 = 0x000F;
const EMF_COMMENT_HEADER: usize = 34;
const TOTAL_SIZE_AT: usize = 30;
let start = wmf_start_offset(data)?;
let placeable = data[start..].starts_with(&[0xD7, 0xCD, 0xC6, 0x9A]);
let mut pos = start.checked_add(if placeable { 22 + 18 } else { 18 })?;
let mut emf: Vec<u8> = Vec::new();
let mut declared: Option<usize> = None;
while pos + 6 <= data.len() {
let size_words =
u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize;
let function = u16::from_le_bytes([data[pos + 4], data[pos + 5]]);
if size_words < 3 {
break;
}
let end = pos.checked_add(size_words.checked_mul(2)?)?;
if end > data.len() {
break;
}
if function == META_ESCAPE && size_words >= 5 {
let escape = u16::from_le_bytes([data[pos + 6], data[pos + 7]]);
let count = u16::from_le_bytes([data[pos + 8], data[pos + 9]]) as usize;
let body = pos + 10;
if escape == ENHANCED_METAFILE
&& count >= EMF_COMMENT_HEADER
&& body + count <= end
&& &data[body..body + 4] == b"WMFC"
{
if declared.is_none() {
let at = body + TOTAL_SIZE_AT;
declared = Some(u32::from_le_bytes([
data[at],
data[at + 1],
data[at + 2],
data[at + 3],
]) as usize);
}
emf.extend_from_slice(&data[body + EMF_COMMENT_HEADER..body + count]);
}
}
pos = end;
}
if emf.len() < 44 || declared != Some(emf.len()) {
return None;
}
if u32::from_le_bytes([emf[0], emf[1], emf[2], emf[3]]) != 1 || &emf[40..44] != b" EMF" {
return None;
}
Some(emf)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_strip_no_emf_magic() {
let data = vec![0u8; 100];
assert!(strip_ole_presentation_header(&data).is_none());
}
#[test]
fn test_strip_emf_at_offset() {
let mut data = vec![0u8; 20];
data.extend_from_slice(&1u32.to_le_bytes());
data.extend_from_slice(&100u32.to_le_bytes());
data.extend_from_slice(&[0u8; 32]);
data.extend_from_slice(b" EMF");
data.extend_from_slice(&[0xAA; 20]);
let stripped = strip_ole_presentation_header(&data).expect("EMF should be found");
assert_eq!(&stripped[..4], &1u32.to_le_bytes()); assert_eq!(&stripped[40..44], b" EMF");
}
#[test]
fn test_parse_empty_bytes() {
assert!(parse_ole_container(&[]).is_none());
assert!(parse_ole_container(&[0u8; 4]).is_none());
}
#[test]
fn test_parse_non_cfb() {
let bytes: Vec<u8> = (0..128u8).collect();
assert!(parse_ole_container(&bytes).is_none());
}
}