verticopolis_engine/load/
container.rs1use super::*;
4
5pub(crate) const EXPANDS_TOO_FAR: &str =
7 "this .vctower expands to more data than we will hold; it looks crafted rather than saved";
8
9pub fn decode_vctower(text: &str) -> Result<Value, String> {
13 parse_save_json(&inflate_vctower(text)?).map_err(|e| format!("json: {e}"))
14}
15
16pub fn decode_vctower_bytes(bytes: &[u8]) -> Result<Value, String> {
20 parse_save_json(&inflate_vctower_bytes(bytes)?).map_err(|e| format!("json: {e}"))
21}
22
23pub(crate) fn inflate_vctower_bytes(bytes: &[u8]) -> Result<Vec<u8>, String> {
26 match binary_stamp(bytes) {
27 Some(after) => {
28 let packed = after
29 .strip_prefix(b"\n")
30 .ok_or("not a VCTOWER2 file: no newline after the stamp")?;
31 inflate_packed(packed).map_err(|e| match e {
32 InflateError::NotAContainer => "not a VCTOWER2 file".to_string(),
33 InflateError::ExpandsTooFar => EXPANDS_TOO_FAR.to_string(),
34 InflateError::Damaged(why) => why,
35 })
36 }
37 None => match std::str::from_utf8(bytes) {
38 Ok(text) => inflate_vctower(text),
39 Err(_) => Err("not a VCTOWER1 or VCTOWER2 file".to_string()),
40 },
41 }
42}
43
44pub(crate) fn binary_stamp(bytes: &[u8]) -> Option<&[u8]> {
48 let after = bytes.strip_prefix(TOWER_FILE_MAGIC_BINARY.as_bytes())?;
49 (!after.first().is_some_and(u8::is_ascii_digit)).then_some(after)
50}
51
52pub(crate) enum InflateError {
54 NotAContainer,
56 ExpandsTooFar,
58 Damaged(String),
60}
61
62pub(crate) fn inflate_vctower(text: &str) -> Result<Vec<u8>, String> {
64 inflate_container(text).map_err(|e| match e {
65 InflateError::NotAContainer => "not a VCTOWER1 file".to_string(),
66 InflateError::ExpandsTooFar => EXPANDS_TOO_FAR.to_string(),
67 InflateError::Damaged(why) => why,
68 })
69}
70
71pub(crate) fn inflate_container(text: &str) -> Result<Vec<u8>, InflateError> {
74 let trimmed = js_trim(text);
75 if !trimmed.starts_with(TOWER_FILE_MAGIC) {
76 return Err(InflateError::NotAContainer);
77 }
78 inflate_packed(&lenient_base64(&trimmed[TOWER_FILE_MAGIC.len()..]))
79}
80
81pub(crate) fn inflate_packed(packed: &[u8]) -> Result<Vec<u8>, InflateError> {
85 use std::io::Read;
86 let mut out = Vec::new();
87 flate2::read::DeflateDecoder::new(packed)
88 .take(MAX_SAVE_INFLATED_BYTES + 1)
89 .read_to_end(&mut out)
90 .map_err(|e| InflateError::Damaged(format!("inflate: {e}")))?;
91 if out.len() as u64 > MAX_SAVE_INFLATED_BYTES {
92 return Err(InflateError::ExpandsTooFar);
93 }
94 if out.starts_with(b"\xEF\xBB\xBF") {
96 out.drain(..3);
97 }
98 Ok(out)
99}
100
101#[doc(hidden)]
102pub fn parse_save_json(text: &[u8]) -> Result<Value, serde_json::Error> {
112 match repair_lone_surrogates(text) {
113 Some(fixed) => serde_json::from_slice(&fixed),
114 None => serde_json::from_slice(text),
115 }
116}
117
118pub(super) fn hex4(text: &[u8], at: usize) -> Option<u16> {
120 let digits = text.get(at..at + 4)?;
121 let s = std::str::from_utf8(digits).ok()?;
122 if !s.bytes().all(|b| b.is_ascii_hexdigit()) {
123 return None;
124 }
125 u16::from_str_radix(s, 16).ok()
126}
127
128pub(crate) fn repair_lone_surrogates(text: &[u8]) -> Option<Vec<u8>> {
132 let mut out: Option<Vec<u8>> = None;
133 let mut copied = 0;
134 let mut in_string = false;
135 let mut i = 0;
136 while i < text.len() {
137 let b = text[i];
138 if !in_string {
139 in_string = b == b'"';
140 i += 1;
141 continue;
142 }
143 match b {
144 b'"' => {
145 in_string = false;
146 i += 1;
147 }
148 b'\\' if text.get(i + 1) == Some(&b'u') => {
149 let Some(unit) = hex4(text, i + 2) else {
150 i += 2;
152 continue;
153 };
154 let paired_low = || {
155 text.get(i + 6) == Some(&b'\\')
156 && text.get(i + 7) == Some(&b'u')
157 && hex4(text, i + 8).is_some_and(|u| (0xDC00..=0xDFFF).contains(&u))
158 };
159 if (0xD800..=0xDBFF).contains(&unit) && paired_low() {
160 i += 12;
161 } else if (0xD800..=0xDFFF).contains(&unit) {
162 let buf = out.get_or_insert_with(|| Vec::with_capacity(text.len()));
163 buf.extend_from_slice(&text[copied..i]);
164 buf.extend_from_slice(b"\\ufffd");
165 i += 6;
166 copied = i;
167 } else {
168 i += 6;
169 }
170 }
171 b'\\' => i += 2,
174 _ => i += 1,
175 }
176 }
177 out.map(|mut buf| {
178 buf.extend_from_slice(&text[copied..]);
179 buf
180 })
181}
182
183pub const TOWER_FILE_MAGIC: &str = "VCTOWER1";
186
187pub const TOWER_FILE_MAGIC_BINARY: &str = "VCTOWER2";
191
192#[derive(Clone, Copy, Debug, PartialEq, Eq)]
194pub(crate) enum Frame {
195 Text,
197 Binary,
199}
200
201pub fn encode_vctower(save: &Value) -> Result<Vec<u8>, String> {
206 pack_json(&crate::canonical::js_json(save))
207}
208
209pub(crate) fn pack_json(json: &str) -> Result<Vec<u8>, String> {
213 pack_json_as(json, Frame::Text)
214}
215
216pub(crate) fn pack_json_as(json: &str, frame: Frame) -> Result<Vec<u8>, String> {
218 if json.len() as u64 > MAX_SAVE_INFLATED_BYTES {
219 return Err(format!(
220 "This tower's save data is larger than {} MB, the most a save can hold.",
221 MAX_SAVE_INFLATED_BYTES / (1024 * 1024)
222 ));
223 }
224 let packed = crate::fflate::deflate_level1(json.as_bytes());
225 if frame == Frame::Binary {
226 let mut out = Vec::with_capacity(TOWER_FILE_MAGIC_BINARY.len() + 1 + packed.len());
227 out.extend_from_slice(TOWER_FILE_MAGIC_BINARY.as_bytes());
228 out.push(b'\n');
229 out.extend_from_slice(&packed);
230 return Ok(out);
231 }
232 let b64 = base64::engine::general_purpose::STANDARD.encode(packed);
233 let mut out = Vec::with_capacity(TOWER_FILE_MAGIC.len() + b64.len() + 2);
234 out.extend_from_slice(TOWER_FILE_MAGIC.as_bytes());
235 out.push(b'\n');
236 out.extend_from_slice(b64.as_bytes());
237 out.push(b'\n');
238 Ok(out)
239}
240
241pub fn stamp_save(save: &mut Value, app_version: &str, saved_at_ms: f64) -> Result<(), String> {
247 let carries_founder = detect_founder(save);
248 let Value::Object(m) = save else {
249 return Err("not a tower save (the save is not an object)".into());
250 };
251 if !m.get("minutes").is_some_and(Value::is_number)
252 || !m.get("units").is_some_and(Value::is_array)
253 {
254 return Err("not a tower save (no numeric minutes or no units list)".into());
255 }
256 check_stamp(app_version, saved_at_ms)?;
257 if carries_founder {
258 m.insert("founder".into(), json!(true));
259 }
260 m.insert("savedAt".into(), json!(saved_at_ms));
261 m.insert("appVersion".into(), json!(app_version));
262 Ok(())
263}
264
265pub(crate) fn check_stamp(app_version: &str, saved_at_ms: f64) -> Result<(), String> {
268 if !(saved_at_ms.is_finite() && saved_at_ms.abs() <= 8.64e15) {
269 return Err(format!("savedAt {saved_at_ms} is not a time"));
270 }
271 if parse_int(app_version).is_some_and(|v| v < 2.0) {
272 return Err(format!(
273 "appVersion {app_version:?} reads as a build before 2.0, which marks the tower as a founder's"
274 ));
275 }
276 Ok(())
277}
278
279pub fn encode_simulation_vctower(
285 sim: &Simulation,
286 app_version: &str,
287 saved_at_ms: f64,
288) -> Result<Vec<u8>, String> {
289 crate::export_stream::encode_vctower_string(sim.save_text(), app_version, saved_at_ms)
290}
291
292pub fn encode_simulation_vctower_binary(
297 sim: &Simulation,
298 app_version: &str,
299 saved_at_ms: f64,
300) -> Result<Vec<u8>, String> {
301 crate::export_stream::encode_vctower_string_as(
302 sim.save_text(),
303 app_version,
304 saved_at_ms,
305 Frame::Binary,
306 )
307}
308
309pub(super) fn lenient_base64(text: &str) -> Vec<u8> {
315 let body = text.split('=').next().unwrap_or("");
316 let mut symbols: String = body
317 .chars()
318 .filter_map(|c| match c {
319 'A'..='Z' | 'a'..='z' | '0'..='9' | '+' | '/' => Some(c),
320 '-' => Some('+'),
321 '_' => Some('/'),
322 _ => None,
323 })
324 .collect();
325 if symbols.len() % 4 == 1 {
326 symbols.pop();
327 }
328 base64::engine::GeneralPurpose::new(
332 &base64::alphabet::STANDARD,
333 base64::engine::GeneralPurposeConfig::new()
334 .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
335 .with_decode_allow_trailing_bits(true),
336 )
337 .decode(symbols.as_bytes())
338 .unwrap_or_default()
339}
340
341#[doc(hidden)]
342pub fn js_trim(s: &str) -> &str {
346 s.trim_matches(is_js_whitespace)
347}
348
349pub(crate) fn is_js_whitespace(c: char) -> bool {
351 (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}'
352}