1use std::io::{Cursor, Read};
9
10use super::error::OrkError;
11use super::warning::{ANOTHER_CURVE, Imported, Warning, WarningKind};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
15#[serde(rename_all = "snake_case")]
16#[non_exhaustive]
17pub enum Container {
18 Zip,
20 Gzip,
22 Xml,
24}
25
26impl Container {
27 pub fn as_str(self) -> &'static str {
29 match self {
30 Self::Zip => "zip",
31 Self::Gzip => "gzip",
32 Self::Xml => "xml",
33 }
34 }
35
36 pub fn sniff(bytes: &[u8]) -> Option<Self> {
48 match bytes {
49 [b'P', b'K', 3, 4, ..] | [b'P', b'K', 5, 6, ..] | [b'P', b'K', 7, 8, ..] => {
50 Some(Self::Zip)
51 }
52 [0x1f, 0x8b, ..] => Some(Self::Gzip),
53 _ if xml_body(bytes).starts_with(b"<") => Some(Self::Xml),
54 _ => None,
55 }
56 }
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
65pub struct Attachment {
66 pub name: String,
68 pub bytes: Vec<u8>,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Unpacked {
75 pub container: Container,
77 pub design_entry: Option<String>,
79 pub design: String,
81 pub attachments: Vec<Attachment>,
83}
84
85pub fn unpack(bytes: &[u8]) -> Result<Imported<Unpacked>, OrkError> {
91 unpack_within(bytes, MAX_UNPACKED_BYTES)
92}
93
94pub fn unpack_within(bytes: &[u8], budget: u64) -> Result<Imported<Unpacked>, OrkError> {
100 match Container::sniff(bytes) {
101 Some(Container::Zip) => unpack_zip(bytes, budget),
102 Some(Container::Gzip) => {
103 let mut text = Vec::new();
104 flate2::read::GzDecoder::new(bytes)
105 .take(budget.saturating_add(1))
106 .read_to_end(&mut text)
107 .map_err(|error| OrkError::Gzip {
108 reason: error.to_string(),
109 })?;
110 if text.len() as u64 > budget {
111 return Err(OrkError::TooBig { limit: budget });
112 }
113 Ok(Imported::clean(Unpacked {
114 container: Container::Gzip,
115 design_entry: None,
116 design: utf8(text)?,
117 attachments: Vec::new(),
118 }))
119 }
120 Some(Container::Xml) => Ok(Imported::clean(Unpacked {
121 container: Container::Xml,
122 design_entry: None,
123 design: utf8(bytes.to_vec())?,
124 attachments: Vec::new(),
125 })),
126 None => Err(OrkError::UnknownContainer { head: head(bytes) }),
127 }
128}
129
130const DESIGN_ENTRY: &str = "rocket.ork";
132
133pub const MAX_UNPACKED_BYTES: u64 = 256 * 1024 * 1024;
143
144fn unpack_zip(bytes: &[u8], budget: u64) -> Result<Imported<Unpacked>, OrkError> {
145 let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|error| OrkError::Zip {
146 reason: error.to_string(),
147 })?;
148 let mut warnings = Vec::new();
149 let mut entries: Vec<Attachment> = Vec::new();
150 let mut used = 0u64;
151 for index in 0..archive.len() {
152 let mut entry = match archive.by_index(index) {
153 Ok(entry) => entry,
154 Err(error) => {
155 warnings.push(Warning::new(
156 format!("entry {index}"),
157 WarningKind::Skipped,
158 format!(
159 "this entry could not be opened and was left out: {error}. If it held a \
160 thrust curve, {ANOTHER_CURVE}"
161 ),
162 ));
163 continue;
164 }
165 };
166 if entry.is_dir() {
167 continue;
168 }
169 let name = match entry.name() {
170 Ok(name) => name.into_owned(),
171 Err(error) => {
172 warnings.push(Warning::new(
173 format!("entry {index}"),
174 WarningKind::Skipped,
175 format!(
176 "this entry's name could not be read, so it was left out: {error}. If it \
177 held a thrust curve, {ANOTHER_CURVE}"
178 ),
179 ));
180 continue;
181 }
182 };
183 let left = budget.saturating_sub(used);
184 let mut content = Vec::new();
185 if let Err(error) = entry.by_ref().take(left + 1).read_to_end(&mut content) {
188 warnings.push(Warning::new(
189 name,
190 WarningKind::Skipped,
191 format!(
192 "this entry could not be decompressed and was left out: {error}. If it held \
193 a thrust curve, {ANOTHER_CURVE}"
194 ),
195 ));
196 continue;
197 }
198 if content.len() as u64 > left {
199 warnings.push(Warning::new(
200 name,
201 WarningKind::Skipped,
202 format!(
203 "this entry was left out: unpacking it would pass the {budget}-byte limit on \
204 what one archive may decompress to. If it held a thrust curve, \
205 {ANOTHER_CURVE}"
206 ),
207 ));
208 continue;
209 }
210 used += content.len() as u64;
211 entries.push(Attachment {
212 name,
213 bytes: content,
214 });
215 }
216
217 let chosen = choose_design(&entries, &mut warnings).ok_or(OrkError::NoDesign)?;
218 let design_bytes = entries.remove(chosen);
219 let design = utf8(design_bytes.bytes)?;
220 Ok(Imported {
221 value: Unpacked {
222 container: Container::Zip,
223 design_entry: Some(design_bytes.name),
224 design,
225 attachments: entries,
226 },
227 warnings,
228 })
229}
230
231fn choose_design(entries: &[Attachment], warnings: &mut Vec<Warning>) -> Option<usize> {
233 if let Some(index) = entries.iter().position(|e| e.name == DESIGN_ENTRY) {
234 return Some(index);
235 }
236 let candidates: Vec<usize> = entries
237 .iter()
238 .enumerate()
239 .filter(|(_, e)| {
240 let lower = e.name.to_ascii_lowercase();
241 lower.ends_with(".ork") || lower.ends_with(".xml")
242 })
243 .map(|(index, _)| index)
244 .collect();
245 let first = *candidates.first()?;
246 warnings.push(Warning::new(
247 entries[first].name.clone(),
248 WarningKind::Unusual,
249 if candidates.len() > 1 {
250 format!(
251 "the archive has no `{DESIGN_ENTRY}`; this is the first of {} entries that could \
252 be the design, and the others are kept as attachments",
253 candidates.len()
254 )
255 } else {
256 format!("the archive has no `{DESIGN_ENTRY}`; this entry was read as the design")
257 },
258 ));
259 Some(first)
260}
261
262fn xml_body(bytes: &[u8]) -> &[u8] {
264 let rest = bytes.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(bytes);
265 let start = rest
266 .iter()
267 .position(|byte| !byte.is_ascii_whitespace())
268 .unwrap_or(rest.len());
269 &rest[start..]
270}
271
272fn utf8(bytes: Vec<u8>) -> Result<String, OrkError> {
275 let mut text = String::from_utf8(bytes).map_err(|_| OrkError::NotUtf8)?;
276 if text.starts_with('\u{feff}') {
277 text.remove(0);
278 }
279 Ok(text)
280}
281
282fn head(bytes: &[u8]) -> String {
284 if bytes.is_empty() {
285 return "nothing (the file is empty)".to_owned();
286 }
287 bytes
288 .iter()
289 .take(4)
290 .map(|byte| format!("{byte:02x}"))
291 .collect::<Vec<_>>()
292 .join(" ")
293}