use std::io::{self, Cursor, Read};
use zip::ZipArchive;
use super::HwpxError;
const CONTENT_MANIFEST_PATH: &str = "Contents/content.hpf";
const DOCUMENT_HEADER_PATH: &str = "Contents/header.xml";
pub(crate) fn has_required_package_entries(data: &[u8]) -> bool {
let cursor = Cursor::new(data);
let Ok(mut archive) = ZipArchive::new(cursor) else {
return false;
};
let has_content_manifest = archive.by_name(CONTENT_MANIFEST_PATH).is_ok();
let has_document_header = archive.by_name(DOCUMENT_HEADER_PATH).is_ok();
has_content_manifest && has_document_header
}
pub const MAX_XML_SIZE: usize = 256 * 1024 * 1024;
pub const MAX_TOTAL_XML_BYTES: usize = 512 * 1024 * 1024;
pub const MAX_BINDATA_SIZE: usize = 512 * 1024 * 1024;
fn read_limited<R: Read>(reader: &mut R, max: usize) -> io::Result<Vec<u8>> {
read_limited_accounted(reader, max, &mut 0)
}
fn read_limited_accounted<R: Read>(
reader: &mut R,
max: usize,
consumed: &mut usize,
) -> io::Result<Vec<u8>> {
let mut buf = Vec::new();
let cap = (max as u64).saturating_add(1);
let result = reader.take(cap).read_to_end(&mut buf);
*consumed = buf.len();
result?;
if buf.len() > max {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"HWPX entry exceeds {} byte limit (possible decompression bomb)",
max
),
));
}
Ok(buf)
}
fn read_limited_reserved<R: Read>(
reader: &mut R,
maximum: usize,
consumed: &mut usize,
reservation: &dyn crate::storage::Reservation,
) -> io::Result<Vec<u8>> {
let mut result = Vec::new();
let mut chunk = [0u8; 8192];
loop {
reservation.hash_payload(0, 0).map_err(io::Error::other)?;
let remaining = maximum.saturating_sub(result.len()).saturating_add(1);
let count = reader.read(&mut chunk[..remaining.min(8192)])?;
if count == 0 {
break;
}
*consumed = consumed.saturating_add(count);
let required = result
.len()
.checked_add(count)
.filter(|v| *v <= maximum)
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
reservation.reject("HWPX decoded entry limit"),
)
})?;
if required > result.capacity() {
let capacity = required
.max(result.capacity().saturating_mul(2))
.min(maximum);
reservation
.hash_payload(1, capacity)
.map_err(io::Error::other)?;
result
.try_reserve_exact(capacity - result.len())
.map_err(|_| {
io::Error::other(
reservation.reject("decoded archive backing allocation failed"),
)
})?;
}
result.extend_from_slice(&chunk[..count]);
}
Ok(result)
}
pub struct HwpxReader {
archive: ZipArchive<Cursor<Vec<u8>>>,
file_names: Vec<String>,
xml_read_remaining: usize,
reservation: Option<std::sync::Arc<dyn crate::storage::Reservation>>,
}
impl HwpxReader {
pub fn open(data: &[u8]) -> Result<Self, HwpxError> {
Self::open_with_reservation(data, None)
}
pub(crate) fn open_with_reservation(
data: &[u8],
reservation: Option<std::sync::Arc<dyn crate::storage::Reservation>>,
) -> Result<Self, HwpxError> {
let copy = if let Some(reservation) = &reservation {
reservation
.hash_payload(1, data.len())
.map_err(HwpxError::ZipError)?;
let mut copy = Vec::new();
copy.try_reserve_exact(data.len())
.map_err(|_| HwpxError::ZipError("PDF_WORKER_MEMORY: archive copy".into()))?;
copy.extend_from_slice(data);
copy
} else {
data.to_vec()
};
let cursor = Cursor::new(copy);
let archive = ZipArchive::new(cursor)?;
let mut file_names = Vec::new();
if let Some(reservation) = &reservation {
reservation
.hash_payload(std::mem::size_of::<String>(), archive.len())
.map_err(HwpxError::ZipError)?;
file_names
.try_reserve_exact(archive.len())
.map_err(|_| HwpxError::ZipError("PDF_WORKER_MEMORY: archive index".into()))?;
}
for name in archive.file_names() {
let name = name?;
if let Some(reservation) = &reservation {
reservation
.hash_payload(1, name.len())
.map_err(HwpxError::ZipError)?;
}
file_names.push(name.into_owned());
}
Ok(HwpxReader {
archive,
file_names,
xml_read_remaining: MAX_TOTAL_XML_BYTES,
reservation,
})
}
pub fn read_file(&mut self, path: &str) -> Result<String, HwpxError> {
let bytes = self.read_xml_bytes_limited(path, MAX_XML_SIZE)?;
match String::from_utf8(bytes) {
Ok(s) => Ok(s),
Err(e) => {
eprintln!(
"경고: {} UTF-8 손상({}) — 관용(lossy) 디코딩 적용 (U+FFFD 치환)",
path,
e.utf8_error()
);
Ok(String::from_utf8_lossy(e.as_bytes()).into_owned())
}
}
}
pub fn read_file_bytes(&mut self, path: &str) -> Result<Vec<u8>, HwpxError> {
self.read_file_bytes_limited(path, MAX_BINDATA_SIZE)
}
pub fn read_file_bytes_limited(
&mut self,
path: &str,
max_bytes: usize,
) -> Result<Vec<u8>, HwpxError> {
self.read_bytes_with_policy(path, max_bytes, false)
}
pub(super) fn read_xml_bytes_limited(
&mut self,
path: &str,
max_bytes: usize,
) -> Result<Vec<u8>, HwpxError> {
self.read_bytes_with_policy(path, max_bytes, true)
}
fn read_bytes_with_policy(
&mut self,
path: &str,
max_bytes: usize,
charge_xml: bool,
) -> Result<Vec<u8>, HwpxError> {
let index = self.file_index(path)?;
let mut file = self
.archive
.by_index(index)
.map_err(|e| HwpxError::MissingFile(format!("{}: {}", path, e)))?;
let entry_limit = max_bytes.min(if charge_xml {
MAX_XML_SIZE
} else {
MAX_BINDATA_SIZE
});
if file.size() > entry_limit as u64 {
return Err(HwpxError::ZipError(format!(
"{} 읽기 실패: HWPX entry exceeds {} byte limit (possible decompression bomb)",
path, entry_limit,
)));
}
let allowance = if charge_xml {
entry_limit.min(self.xml_read_remaining)
} else {
entry_limit
};
if charge_xml && file.size() > self.xml_read_remaining as u64 {
return Err(HwpxError::XmlReadBudgetExceeded {
path: path.into(),
max_bytes: MAX_TOTAL_XML_BYTES,
});
}
let mut consumed = 0;
let result = if let Some(reservation) = &self.reservation {
read_limited_reserved(&mut file, allowance, &mut consumed, reservation.as_ref())
} else {
read_limited_accounted(&mut file, allowance, &mut consumed)
};
if charge_xml {
self.xml_read_remaining = self.xml_read_remaining.saturating_sub(consumed);
if consumed > allowance && allowance < entry_limit {
return Err(HwpxError::XmlReadBudgetExceeded {
path: path.into(),
max_bytes: MAX_TOTAL_XML_BYTES,
});
}
}
result.map_err(|e| HwpxError::ZipError(format!("{} 읽기 실패: {}", path, e)))
}
pub fn file_size_limited(&mut self, path: &str, max_bytes: usize) -> Result<usize, HwpxError> {
let index = self.file_index(path)?;
let file = self
.archive
.by_index(index)
.map_err(|e| HwpxError::MissingFile(format!("{}: {}", path, e)))?;
let max_bytes = max_bytes.min(MAX_BINDATA_SIZE);
let size = usize::try_from(file.size()).map_err(|_| {
HwpxError::ZipError(format!(
"{} 읽기 실패: HWPX entry size does not fit usize",
path
))
})?;
if size > max_bytes {
return Err(HwpxError::ZipError(format!(
"{} 읽기 실패: HWPX entry exceeds {} byte limit (possible decompression bomb)",
path, max_bytes
)));
}
Ok(size)
}
fn file_index(&self, path: &str) -> Result<usize, HwpxError> {
self.archive
.index_for_name(path)
.or_else(|| self.file_names.iter().position(|name| name == path))
.ok_or_else(|| HwpxError::MissingFile(path.into()))
}
pub fn raw_deflated_entry(
&mut self,
path: &str,
) -> Option<crate::model::bin_data::DeflatedZipEntry> {
let index = self.file_index(path).ok()?;
let mut file = self.archive.by_index_raw(index).ok()?;
if file.compression() != zip::CompressionMethod::Deflated {
return None;
}
let compressed = usize::try_from(file.compressed_size())
.ok()
.filter(|size| *size <= MAX_BINDATA_SIZE)?;
let mut compressed_bytes = Vec::with_capacity(compressed);
file.read_to_end(&mut compressed_bytes).ok()?;
Some(crate::model::bin_data::DeflatedZipEntry {
crc32: file.crc32(),
uncompressed_size: file.size(),
compressed_bytes,
})
}
pub fn file_names(&self) -> Vec<String> {
let Some(reservation) = &self.reservation else {
return self.file_names.clone();
};
let copy = (|| -> Result<Vec<String>, String> {
reservation.hash_payload(std::mem::size_of::<String>(), self.file_names.len())?;
let mut names = Vec::new();
names
.try_reserve_exact(self.file_names.len())
.map_err(|_| reservation.reject("HWPX file-name index allocation failed"))?;
for name in &self.file_names {
reservation.hash_payload(1, name.len())?;
let mut copy = String::new();
copy.try_reserve_exact(name.len())
.map_err(|_| reservation.reject("HWPX file-name allocation failed"))?;
copy.push_str(name);
names.push(copy);
}
Ok(names)
})();
copy.unwrap_or_default() }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_open_invalid_zip() {
let result = HwpxReader::open(&[0u8; 100]);
assert!(result.is_err());
use std::io::Write;
for original_name in ["한.xml", "cafe.xml"] {
let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
writer
.start_file(original_name, zip::write::SimpleFileOptions::default())
.unwrap();
writer.write_all(b"<root/>").unwrap();
let mut bytes = writer.finish().unwrap().into_inner();
let expected_name = if original_name == "cafe.xml" {
let central = bytes
.windows(4)
.position(|signature| signature == b"PK\x01\x02")
.expect("ZIP 중앙 디렉터리");
bytes[30 + 3] = 0x82;
bytes[central + 46 + 3] = 0x82;
"café.xml"
} else {
original_name
};
let mut reader = HwpxReader::open(&bytes).expect("정상 ZIP 이름");
assert_eq!(reader.file_names(), vec![expected_name]);
assert_eq!(reader.file_size_limited(expected_name, 7).unwrap(), 7);
assert_eq!(reader.read_file(expected_name).unwrap(), "<root/>");
}
}
#[test]
fn test_detect_odf_encryption() {
use crate::parser::hwpx::{detect_odf_encryption, parse_hwpx, HwpxError};
use std::io::Write;
use zip::write::SimpleFileOptions;
use zip::ZipWriter;
let enc = br#"<odf:manifest><odf:file-entry full-path="Contents/header.xml"><odf:encryption-data><odf:algorithm algorithm-name="http://www.w3.org/2001/04/xmlenc#aes256-cbc"/><odf:key-derivation key-derivation-name="...#pbkdf2"/></odf:encryption-data></odf:file-entry></odf:manifest>"#;
let detail = detect_odf_encryption(enc).expect("암호화 감지");
assert!(detail.contains("AES-256-CBC"), "{detail}");
assert!(detail.contains("PBKDF2"), "{detail}");
let plain =
br#"<odf:manifest><odf:file-entry full-path="Contents/header.xml"/></odf:manifest>"#;
assert!(detect_odf_encryption(plain).is_none());
let mut out = Cursor::new(Vec::<u8>::new());
{
let mut zip = ZipWriter::new(&mut out);
let opts =
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
zip.start_file("mimetype", opts).unwrap();
zip.write_all(b"application/hwp+zip").unwrap();
zip.start_file("META-INF/manifest.xml", opts).unwrap();
zip.write_all(enc).unwrap();
zip.start_file("Contents/header.xml", opts).unwrap();
zip.write_all(&[0x93u8, 0xFF, 0x00, 0x11]).unwrap(); zip.finish().unwrap();
}
let bytes = out.into_inner();
match parse_hwpx(&bytes) {
Err(e @ HwpxError::Encrypted(_)) => {
assert!(e.is_encrypted());
assert!(e.to_string().contains("암호화된 문서"), "{e}");
}
other => panic!("expected Encrypted, got {other:?}"),
}
}
#[test]
fn test_read_limited_under_cap() {
let data = vec![0u8; 1000];
let mut cursor = Cursor::new(data.clone());
let result = read_limited(&mut cursor, 2000).unwrap();
assert_eq!(result.len(), 1000);
}
#[test]
fn test_read_limited_at_cap() {
let data = vec![0u8; 1000];
let mut cursor = Cursor::new(data.clone());
let result = read_limited(&mut cursor, 1000).unwrap();
assert_eq!(result.len(), 1000);
}
#[test]
fn test_read_limited_over_cap() {
let data = vec![0u8; 1001];
let mut cursor = Cursor::new(data);
let result = read_limited(&mut cursor, 1000);
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
#[test]
fn test_compressed_entry_limited_read_rejects_before_materialization() {
use std::io::Write;
use zip::write::SimpleFileOptions;
use zip::ZipWriter;
let mut out = Cursor::new(Vec::<u8>::new());
{
let mut zip = ZipWriter::new(&mut out);
let options =
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
zip.start_file("BinData/font.ttf", options).unwrap();
zip.write_all(&vec![b'A'; 4096]).unwrap();
zip.finish().unwrap();
}
let mut reader = HwpxReader::open(&out.into_inner()).unwrap();
let error = reader
.read_file_bytes_limited("BinData/font.ttf", 1024)
.expect_err("oversized deflated entry must be rejected");
assert!(error.to_string().contains("1024 byte limit"));
}
#[test]
fn test_large_legit_xml_entry_accepted() {
use std::io::Write;
use zip::write::SimpleFileOptions;
use zip::ZipWriter;
let mut out = Cursor::new(Vec::<u8>::new());
{
let mut zip = ZipWriter::new(&mut out);
let opts =
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
zip.start_file("Contents/section1.xml", opts).unwrap();
let payload = vec![b'A'; 40 * 1024 * 1024]; zip.write_all(&payload).unwrap();
zip.finish().unwrap();
}
let bytes = out.into_inner();
let mut reader = HwpxReader::open(&bytes).unwrap();
let result = reader.read_file("Contents/section1.xml");
assert!(
result.is_ok(),
"40MB XML entry should be accepted: {:?}",
result.err()
);
assert_eq!(result.unwrap().len(), 40 * 1024 * 1024);
}
#[test]
fn test_invalid_utf8_entry_lossy_accepted() {
use std::io::Write;
use zip::write::SimpleFileOptions;
use zip::ZipWriter;
let mut out = Cursor::new(Vec::<u8>::new());
{
let mut zip = ZipWriter::new(&mut out);
let opts =
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
zip.start_file("Contents/header.xml", opts).unwrap();
zip.write_all(b"<hwpml>\x93</hwpml>").unwrap();
zip.finish().unwrap();
}
let bytes = out.into_inner();
let mut reader = HwpxReader::open(&bytes).unwrap();
let s = reader
.read_file("Contents/header.xml")
.expect("#1932: 손상 UTF-8 은 lossy 폴백으로 수용되어야 함");
assert!(s.starts_with("<hwpml>"));
assert!(
s.contains('\u{FFFD}'),
"손상 바이트는 U+FFFD 로 치환: {s:?}"
);
assert!(s.ends_with("</hwpml>"));
}
#[test]
fn test_zip_bomb_xml_entry_rejected() {
use std::io::Write;
use zip::write::SimpleFileOptions;
use zip::ZipWriter;
let mut out = Cursor::new(Vec::<u8>::new());
{
let mut zip = ZipWriter::new(&mut out);
let opts =
SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
zip.start_file("Contents/bomb.xml", opts).unwrap();
let payload = vec![b'A'; MAX_XML_SIZE + 1];
zip.write_all(&payload).unwrap();
zip.finish().unwrap();
}
let bytes = out.into_inner();
assert!(
bytes.len() < 1024 * 1024,
"bomb compressed too large: {}",
bytes.len()
);
let mut reader = HwpxReader::open(&bytes).unwrap();
let result = reader.read_file("Contents/bomb.xml");
assert!(result.is_err(), "bomb entry should be rejected");
match result.unwrap_err() {
HwpxError::ZipError(msg) => {
assert!(
msg.contains("decompression bomb") || msg.contains("limit"),
"unexpected error message: {}",
msg
);
}
other => panic!("expected ZipError, got {:?}", other),
}
}
}