Skip to main content

unityrs_testkit/
web.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/files/BundleFile.py, UnityPy/files/WebFile.py. See THIRD_PARTY_LICENSES.
2//! Synthetic legacy bundles and WebFile containers, including stored compression streams.
3#![allow(
4    clippy::cast_possible_truncation,
5    clippy::cast_possible_wrap,
6    reason = "synthetic builders deliberately encode fixed-width fields"
7)]
8use crate::bundle::{BundleSpec, EntrySpec, TestCodec, build_with_signature, compress};
9use crate::writer::ByteWriter;
10
11/// UnityWeb/UnityRaw, formats 1–6 (`files/BundleFile.py:55-94`).
12#[must_use]
13pub fn legacy(signature: &[u8], format: u32, entries: &[(&str, &[u8])]) -> Vec<u8> {
14    legacy_levels(signature, format, entries, 1)
15}
16
17/// The same legacy payload with multiple levels; only the last is used.
18#[must_use]
19pub fn legacy_levels(
20    signature: &[u8],
21    format: u32,
22    entries: &[(&str, &[u8])],
23    levels: usize,
24) -> Vec<u8> {
25    let levels = levels.clamp(1, 1024);
26    if format == 6 {
27        return build_with_signature(
28            &BundleSpec {
29                format,
30                entries: entries
31                    .iter()
32                    .map(|(n, b)| EntrySpec {
33                        name: n.as_bytes().to_vec(),
34                        data: b.to_vec(),
35                        flags: 0,
36                    })
37                    .collect(),
38                ..BundleSpec::default()
39            },
40            signature,
41        );
42    }
43    let table = 4 + entries.iter().map(|(n, _)| n.len() + 9).sum::<usize>();
44    let mut body = ByteWriter::be();
45    body.i32(entries.len() as i32);
46    let mut offset = table;
47    for (name, data) in entries {
48        body.cstr(name.as_bytes())
49            .u32(offset as u32)
50            .u32(data.len() as u32);
51        offset += data.len();
52    }
53    for (_, data) in entries {
54        body.bytes(data);
55    }
56    let body = body.into_inner();
57    let packed = if signature == b"UnityWeb" {
58        let raw = compress(TestCodec::Lzma, &body);
59        let mut packed = raw[..5].to_vec();
60        packed.extend_from_slice(&(body.len() as u64).to_le_bytes());
61        packed.extend_from_slice(&raw[5..]);
62        packed
63    } else {
64        body.clone()
65    };
66    let mut w = ByteWriter::be();
67    w.cstr(signature)
68        .u32(format)
69        .cstr(b"5.x.x")
70        .cstr(b"2022.3.0f1");
71    if format >= 4 {
72        w.bytes(&[42; 16]).u32(1234);
73    }
74    let header = w.len()
75        + 24
76        + 8 * (levels - 1)
77        + usize::from(format >= 2) * 4
78        + usize::from(format >= 3) * 4;
79    w.u32(0).u32(header as u32).u32(1).i32(levels as i32);
80    for _ in 1..levels {
81        w.u32(u32::MAX).u32(u32::MAX);
82    }
83    w.u32(packed.len() as u32).u32(body.len() as u32);
84    if format >= 2 {
85        w.u32((header + packed.len()) as u32);
86    }
87    if format >= 3 {
88        w.u32(table as u32);
89    }
90    w.bytes(&packed);
91    w.into_inner()
92}
93
94/// Plain WebFile (`files/WebFile.py:73-105`).
95#[must_use]
96pub fn plain(signature: &str, entries: &[(&str, &[u8])]) -> Vec<u8> {
97    let mut w = ByteWriter::le();
98    let mut offset = signature.len() + 5 + entries.iter().map(|(n, _)| 12 + n.len()).sum::<usize>();
99    w.cstr(signature.as_bytes()).i32(offset as i32);
100    for (name, data) in entries {
101        w.i32(offset as i32)
102            .i32(data.len() as i32)
103            .i32(name.len() as i32)
104            .bytes(name.as_bytes());
105        offset += data.len();
106    }
107    for (_, data) in entries {
108        w.bytes(data);
109    }
110    w.into_inner()
111}
112
113/// A plain WebFile whose first member's name length is -2 (Tier U).
114/// Nonempty `entries` retain their payloads, but opening the directory is unsupported.
115#[must_use]
116pub fn unsupported_name_length(entries: &[(&str, Vec<u8>)]) -> Vec<u8> {
117    let mut data = crate::env::web_file(entries);
118    let name_length = b"UnityWebData1.0\0".len() + 12;
119    if let Some(length) = data.get_mut(name_length..name_length + 4) {
120        length.copy_from_slice(&(-2_i32).to_le_bytes());
121    }
122    data
123}
124
125/// Gzip with a stored DEFLATE stream, deterministic header and CRC.
126#[must_use]
127pub fn gzip(data: &[u8]) -> Vec<u8> {
128    let mut out = vec![31, 139, 8, 0, 0, 0, 0, 0, 0, 3];
129    for (i, chunk) in data.chunks(65535).enumerate() {
130        out.push(u8::from((i + 1) * 65535 >= data.len()));
131        let n = chunk.len() as u16;
132        out.extend_from_slice(&n.to_le_bytes());
133        out.extend_from_slice(&(!n).to_le_bytes());
134        out.extend_from_slice(chunk);
135    }
136    if data.is_empty() {
137        out.extend_from_slice(&[1, 0, 0, 255, 255]);
138    }
139    let mut crc = !0u32;
140    for b in data {
141        crc ^= u32::from(*b);
142        for _ in 0..8 {
143            crc = (crc >> 1) ^ (0xedb8_8320 & 0u32.wrapping_sub(crc & 1));
144        }
145    }
146    out.extend_from_slice(&(!crc).to_le_bytes());
147    out.extend_from_slice(&(data.len() as u32).to_le_bytes());
148    out
149}
150
151/// Brotli with a metadata block placing Unity's detection marker at 0x20,
152/// then uncompressed meta-blocks (RFC 7932 sections 9.1 and 9.2).
153#[must_use]
154pub fn brotli(data: &[u8]) -> Vec<u8> {
155    // WBITS=16 (0); ISLAST=0; MNIBBLES=3; reserved=0; MSKIPBYTES=1;
156    // MSKIPLEN=35 (36 bytes). Header occupies two bytes.
157    let mut out = vec![0xac, 0x11];
158    out.resize(38, 0);
159    out[32..38].copy_from_slice(b"brotli");
160    for chunk in data.chunks(65536) {
161        let bits = (((chunk.len() - 1) as u32) << 3) | (1 << 19);
162        out.extend_from_slice(&bits.to_le_bytes()[..3]);
163        out.extend_from_slice(chunk);
164    }
165    out.push(3);
166    out
167}
168
169/// A Huffman-coded WebFile containing `raw` = `ab12` repeated 3000 times.
170/// Synthetic stream encoded by brotli 1.2.0, quality 11, lgwin 16, with a
171/// metadata block for detection. Exercises tables and the static dictionary.
172#[must_use]
173pub fn huffman() -> Vec<u8> {
174    let mut out = vec![0xac, 0x27];
175    out.resize(82, 0);
176    out[32..38].copy_from_slice(b"brotli");
177    out.extend_from_slice(&[
178        33, 240, 130, 223, 226, 192, 110, 242, 60, 50, 201, 102, 109, 84, 95, 156, 158, 53, 192,
179        128, 28, 248, 116, 25, 145, 41, 152, 178, 20, 139, 185, 235, 152, 171, 176, 60, 176, 1, 7,
180        26, 121, 0, 22, 225, 38, 114, 1, 224, 80, 45, 109, 107, 199, 33, 56, 242, 150, 38, 0, 235,
181        48,
182    ]);
183    out
184}