Skip to main content

unityrs_export/extractor/
paths.rs

1// Ported from UnityPy 1.25.2 (MIT): tools/extractor.py. See THIRD_PARTY_LICENSES.
2//! Naming from tools/extractor.py:25-78 and tools/extractor.py:81-157.
3//! Safety policy: validate before dropping directories; reject parent, NUL,
4//! absolute and backslash-bearing paths. Empty slash components are ignored.
5use super::Error;
6use std::sync::Arc;
7use unityrs_core::{
8    RawStr,
9    limits::{Meter, MeteredVec},
10};
11
12/// Validate an untrusted relative output path, including its original prefix.
13pub fn validate(path: &[u8]) -> Result<(), Error> {
14    if path.starts_with(b"/")
15        || path.contains(&0)
16        || path.contains(&b'\\')
17        || path
18            .split(|b| *b == b'/')
19            .any(|s| s == b".." || s.contains(&b':'))
20    {
21        return Err(Error::UnsafePath);
22    }
23    Ok(())
24}
25/// Slash split, Python slicing (negative counts included), empty parts omitted.
26pub fn container(path: &[u8], ignore: i64, meter: &Arc<Meter>) -> Result<RawStr, Error> {
27    validate(path)?;
28    meter.count_decode(path.len() as u64)?;
29    let count = path.split(|b| *b == b'/').count();
30    let start = if ignore < 0 {
31        count.saturating_sub(usize::try_from(ignore.unsigned_abs()).unwrap_or(usize::MAX))
32    } else {
33        usize::try_from(ignore).unwrap_or(usize::MAX)
34    };
35    let mut out = MeteredVec::new(meter);
36    for part in path
37        .split(|b| *b == b'/')
38        .skip(start)
39        .filter(|s| !s.is_empty())
40    {
41        if !out.is_empty() {
42            out.push(b'/')?;
43        }
44        out.extend_from_slice(part)?;
45    }
46    if out.is_empty() {
47        return Err(Error::UnsafePath);
48    }
49    Ok(RawStr::charged(out.as_slice(), meter)?)
50}
51/// POSIX splitext: a leading run of dots alone is part of the stem.
52#[must_use]
53pub fn split(path: &[u8]) -> (&[u8], &[u8]) {
54    let base = path.iter().rposition(|b| *b == b'/').map_or(0, |i| i + 1);
55    if let Some(dot) = path.iter().rposition(|b| *b == b'.').filter(|i| *i >= base)
56        && path
57            .get(base..dot)
58            .unwrap_or_default()
59            .iter()
60            .any(|b| *b != b'.')
61    {
62        return (
63            path.get(..dot).unwrap_or_default(),
64            path.get(dot..).unwrap_or_default(),
65        );
66    }
67    (path, b"")
68}
69pub(super) fn join(a: &[u8], b: &[u8], meter: &Arc<Meter>) -> Result<RawStr, Error> {
70    validate(b)?;
71    Ok(RawStr::charged_concat(
72        &[a, if a.is_empty() { b"" } else { b"/" }, b],
73        meter,
74    )?)
75}
76pub(super) fn suffix(stem: &[u8], ext: &[u8], meter: &Arc<Meter>) -> Result<RawStr, Error> {
77    let result = RawStr::charged_concat(&[stem, ext], meter)?;
78    validate(result.as_bytes())?;
79    Ok(result)
80}