use crate::error::HwpError;
use crate::model::document::Document;
const MAX_SCRIPT_BYTES: usize = 1_048_576;
fn invalid() -> HwpError {
HwpError::InvalidField("FORM_ACTION_INVALID: invalid or excessive form action".into())
}
fn utf16(bytes: &[u8]) -> Result<String, HwpError> {
if bytes.len() > MAX_SCRIPT_BYTES || !bytes.len().is_multiple_of(2) {
return Err(invalid());
}
String::from_utf16(
&bytes
.chunks_exact(2)
.map(|b| u16::from_le_bytes([b[0], b[1]]))
.collect::<Vec<_>>(),
)
.map(|s| s.trim_start_matches('\u{feff}').to_owned())
.map_err(|_| invalid())
}
pub(crate) fn script_stream_compressed(document: &Document) -> bool {
document.header.compressed
|| document.provenance.format != crate::model::provenance::SourceFormat::Hwp5
}
fn is_distribution_envelope(bytes: &[u8]) -> bool {
bytes.starts_with(
&(u32::from(crate::parser::tags::HWPTAG_DISTRIBUTE_DOC_DATA) | (256 << 20)).to_le_bytes(),
)
}
fn inflate_script_stream(bytes: &[u8]) -> Result<Vec<u8>, HwpError> {
use std::io::Read;
let mut raw = Vec::new();
flate2::read::DeflateDecoder::new(bytes)
.take((MAX_SCRIPT_BYTES + 1) as u64)
.read_to_end(&mut raw)
.map_err(|_| invalid())?;
if raw.len() > MAX_SCRIPT_BYTES {
return Err(invalid());
}
Ok(raw)
}
pub(crate) fn script_stream_for_hwp(
document: &Document,
bytes: &[u8],
target_compressed: bool,
) -> Result<Option<Vec<u8>>, HwpError> {
if bytes.is_empty()
|| script_stream_compressed(document) == target_compressed
|| is_distribution_envelope(bytes)
{
return Ok(None);
}
if target_compressed {
use std::io::Write;
let mut encoder =
flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(bytes).map_err(|_| invalid())?;
Ok(Some(encoder.finish().map_err(|_| invalid())?))
} else {
Ok(Some(inflate_script_stream(bytes)?))
}
}
pub(crate) fn script_sources_from_streams(
document: &Document,
) -> Result<(String, String), HwpError> {
let compressed = script_stream_compressed(document);
let Some((_, bytes)) = document
.extra_streams
.iter()
.find(|(path, _)| path.trim_start_matches('/') == "Scripts/DefaultJScript")
else {
return Ok((String::new(), String::new()));
};
if bytes.len() > MAX_SCRIPT_BYTES {
return Err(invalid());
}
let raw = if is_distribution_envelope(bytes) {
crate::parser::crypto::decrypt_viewtext_section_limited(bytes, compressed, MAX_SCRIPT_BYTES)
.map_err(|_| invalid())?
} else if !compressed {
bytes.clone()
} else {
inflate_script_stream(bytes)?
};
if raw.len() > MAX_SCRIPT_BYTES {
return Err(invalid());
}
let mut offset = 0usize;
let mut part = || -> Result<String, HwpError> {
let count_end = offset.checked_add(4).ok_or_else(invalid)?;
let count = u32::from_le_bytes(
raw.get(offset..count_end)
.ok_or_else(invalid)?
.try_into()
.map_err(|_| invalid())?,
) as usize;
offset = count_end;
let end = offset
.checked_add(count.checked_mul(2).ok_or_else(invalid)?)
.ok_or_else(invalid)?;
let decoded = utf16(raw.get(offset..end).ok_or_else(invalid)?)?;
offset = end;
Ok(decoded)
};
Ok((part()?, part()?))
}
pub(crate) fn scripts(document: &Document) -> Result<(String, String), HwpError> {
match (
document.hwpx_aux_entry("Scripts/headerScripts"),
document.hwpx_aux_entry("Scripts/sourceScripts"),
) {
(Some(header), Some(source)) => Ok((utf16(header)?, utf16(source)?)),
_ => script_sources_from_streams(document),
}
}