team-ljyzipelo

공개
878줄29 KB
1use crate::protocol::*;
2use std::collections::{BTreeMap, BTreeSet};
3use zlib_rs::{Deflate, DeflateFlush, Inflate, InflateFlush, Status, crc32::crc32};
4
5type Result<T> = std::result::Result<T, ErrorCode>;
6pub const MAX_PATH_DEPTH: usize = 64;
7pub const MAX_METADATA_BYTES: usize = 8 * 1024 * 1024;
8pub const MAX_OUTPUT_NODES: usize = 32_768;
9
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub struct MetadataLimits {
12 pub(crate) bytes: usize,
13 pub(crate) nodes: usize,
14 pub(crate) enlarged: bool,
15}
16impl Default for MetadataLimits {
17 fn default() -> Self {
18 Self {
19 bytes: MAX_METADATA_BYTES,
20 nodes: MAX_OUTPUT_NODES,
21 enlarged: false,
22 }
23 }
24}
25impl MetadataLimits {
26 pub(crate) fn approved() -> Self {
27 Self {
28 bytes: 64 * 1024 * 1024,
29 nodes: 262_144,
30 enlarged: true,
31 }
32 }
33}
34
35#[derive(Default)]
36pub(crate) struct MetadataBudget {
37 bytes: usize,
38 nodes: usize,
39}
40impl MetadataBudget {
41 fn charge_cost(&mut self, bytes: usize, nodes: usize, limits: MetadataLimits) -> Result<()> {
42 let bytes = self
43 .bytes
44 .checked_add(bytes)
45 .filter(|n| *n <= limits.bytes)
46 .ok_or(ErrorCode::Limit)?;
47 let nodes = self
48 .nodes
49 .checked_add(nodes)
50 .filter(|n| *n <= limits.nodes)
51 .ok_or(ErrorCode::Limit)?;
52 self.bytes = bytes;
53 self.nodes = nodes;
54 Ok(())
55 }
56 pub(crate) fn charge(&mut self, name: &str) -> Result<()> {
57 self.charge_with(name, MetadataLimits::default())
58 }
59 pub(crate) fn charge_with(&mut self, name: &str, limits: MetadataLimits) -> Result<()> {
60 // 이름 복제와 인덱스 노드 비용을 할당 전에 계산함.
61 let cost = name
62 .len()
63 .checked_mul(4)
64 .and_then(|n| n.checked_add(256))
65 .ok_or(ErrorCode::Limit)?;
66 self.charge_cost(cost, 1, limits)
67 }
68 pub(crate) fn charge_copy(&mut self, name: &str, limits: MetadataLimits) -> Result<()> {
69 if !limits.enlarged {
70 return self.charge_with(name, limits);
71 }
72 // 확대 계획의 경로와 대기 이름은 기존 항목 노드에 속한 복사 비용임.
73 self.charge_cost(
74 name.len().checked_mul(4).ok_or(ErrorCode::Limit)?,
75 0,
76 limits,
77 )
78 }
79}
80
81#[derive(Debug)]
82pub struct Member {
83 pub entry: Entry,
84 pub data: Vec<u8>,
85}
86pub struct Catalog {
87 pub format: Format,
88 pub members: Vec<Member>,
89}
90fn part(b: &[u8], at: usize, n: usize) -> Result<&[u8]> {
91 b.get(at..at.checked_add(n).ok_or(ErrorCode::Integrity)?)
92 .ok_or(ErrorCode::Integrity)
93}
94fn u16at(b: &[u8], at: usize) -> Result<u16> {
95 Ok(u16::from_le_bytes(part(b, at, 2)?.try_into().unwrap()))
96}
97fn u32at(b: &[u8], at: usize) -> Result<u32> {
98 Ok(u32::from_le_bytes(part(b, at, 4)?.try_into().unwrap()))
99}
100
101pub fn valid_name(name: &str, directory: bool) -> Result<String> {
102 let name = if directory {
103 name.strip_suffix('/').unwrap_or(name)
104 } else {
105 name
106 };
107 if name.is_empty()
108 || name.len() > 4096
109 || name.starts_with('/')
110 || name.contains('\\')
111 || name
112 .chars()
113 .any(|c| c.is_control() || matches!(c, ':' | '*' | '?' | '"' | '<' | '>' | '|'))
114 {
115 return Err(ErrorCode::UnsafePath);
116 }
117 if name.split('/').count() > MAX_PATH_DEPTH {
118 return Err(ErrorCode::Limit);
119 }
120 for component in name.split('/') {
121 if component.is_empty()
122 || matches!(component, "." | "..")
123 || component.ends_with(['.', ' '])
124 || component.len() > 255
125 {
126 return Err(ErrorCode::UnsafePath);
127 }
128 let stem = component.split('.').next().unwrap().to_ascii_uppercase();
129 if matches!(
130 stem.as_str(),
131 "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
132 ) || ["COM", "LPT"].iter().any(|p| {
133 stem.strip_prefix(p).is_some_and(|n| {
134 matches!(
135 n,
136 "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
137 )
138 })
139 }) {
140 return Err(ErrorCode::UnsafePath);
141 }
142 }
143 Ok(name.to_owned())
144}
145pub fn validate_members(members: &[Member]) -> Result<()> {
146 validate_members_with(members, &mut || Ok(()))
147}
148pub(crate) fn validate_members_with(
149 members: &[Member],
150 check: &mut impl crate::resources::Monitor,
151) -> Result<()> {
152 let mut names = BTreeMap::<String, bool>::new();
153 let mut budget = MetadataBudget::default();
154 for member in members {
155 check.activity()?;
156 budget.charge_with(&member.entry.name, check.metadata_limits())?;
157 let directory = member.entry.kind == EntryKind::Directory;
158 let name = valid_name(&member.entry.name, directory)?.to_lowercase();
159 if names.insert(name, directory).is_some() {
160 return Err(ErrorCode::Conflict);
161 }
162 }
163 for name in names.keys() {
164 check.activity()?;
165 let mut parent = name.as_str();
166 while let Some((p, _)) = parent.rsplit_once('/') {
167 if names.get(p) == Some(&false) {
168 return Err(ErrorCode::Conflict);
169 }
170 parent = p;
171 }
172 }
173 Ok(())
174}
175pub(crate) fn output_directories(
176 members: &[Member],
177 check: &mut impl crate::resources::Monitor,
178) -> Result<BTreeSet<String>> {
179 validate_members_with(members, check)?;
180 let mut budget = MetadataBudget::default();
181 let mut dirs = BTreeSet::new();
182 for member in members {
183 check.activity()?;
184 budget.charge_with(&member.entry.name, check.metadata_limits())?;
185 if member.entry.kind == EntryKind::Directory && !dirs.contains(member.entry.name.as_str()) {
186 dirs.insert(member.entry.name.clone());
187 }
188 let mut name = member.entry.name.as_str();
189 while let Some((parent, _)) = name.rsplit_once('/') {
190 if !dirs.contains(parent) {
191 budget.charge_with(parent, check.metadata_limits())?;
192 dirs.insert(parent.to_owned());
193 }
194 name = parent;
195 }
196 }
197 Ok(dirs)
198}
199
200fn bounded_append(output: &mut Vec<u8>, data: &[u8], limit: u64) -> Result<()> {
201 if (output.len() as u64)
202 .checked_add(data.len() as u64)
203 .is_none_or(|n| n > limit)
204 {
205 return Err(ErrorCode::Limit);
206 }
207 output
208 .try_reserve(data.len())
209 .map_err(|_| ErrorCode::Limit)?;
210 output.extend_from_slice(data);
211 Ok(())
212}
213fn inflate(
214 input: &[u8],
215 gzip: bool,
216 limit: u64,
217 check: &mut impl crate::resources::Monitor,
218) -> Result<(Vec<u8>, usize)> {
219 let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 });
220 let mut out = Vec::new();
221 let mut buffer = [0; 65536];
222 loop {
223 check.check()?;
224 let before_in = stream.total_in();
225 let before_out = stream.total_out();
226 let status = stream
227 .decompress(
228 &input[before_in as usize..],
229 &mut buffer,
230 InflateFlush::NoFlush,
231 )
232 .map_err(|_| ErrorCode::Integrity)?;
233 let written = (stream.total_out() - before_out) as usize;
234 bounded_append(&mut out, &buffer[..written], limit)?;
235 if status == Status::StreamEnd {
236 return Ok((out, stream.total_in() as usize));
237 }
238 if stream.total_in() == before_in && stream.total_out() == before_out {
239 return Err(ErrorCode::Integrity);
240 }
241 }
242}
243fn gzip(
244 input: &[u8],
245 limits: Limits,
246 check: &mut impl crate::resources::Monitor,
247) -> Result<Vec<u8>> {
248 let mut at = 0;
249 let mut result = Vec::new();
250 while at < input.len() {
251 if !input[at..].starts_with(&[31, 139, 8]) {
252 return Err(ErrorCode::Integrity);
253 }
254 let (out, used) = inflate(
255 &input[at..],
256 true,
257 limits.output - result.len() as u64,
258 check,
259 )?;
260 if used == 0 {
261 return Err(ErrorCode::Integrity);
262 }
263 bounded_append(&mut result, &out, limits.output)?;
264 at += used;
265 }
266 Ok(result)
267}
268pub(crate) fn tar_string(b: &[u8]) -> Result<String> {
269 let n = b.iter().position(|v| *v == 0).unwrap_or(b.len());
270 if b[n..].iter().any(|v| *v != 0) {
271 return Err(ErrorCode::Integrity);
272 }
273 std::str::from_utf8(&b[..n])
274 .map(str::to_owned)
275 .map_err(|_| ErrorCode::UnsupportedFeature)
276}
277pub(crate) fn octal(b: &[u8]) -> Result<u64> {
278 if b.first().is_some_and(|x| x & 128 != 0) {
279 return Err(ErrorCode::UnsupportedFeature);
280 }
281 let text = std::str::from_utf8(b)
282 .map_err(|_| ErrorCode::Integrity)?
283 .trim_matches(['\0', ' ']);
284 if text.is_empty() {
285 return Ok(0);
286 }
287 u64::from_str_radix(text, 8).map_err(|_| ErrorCode::Integrity)
288}
289fn tar(
290 input: &[u8],
291 limits: Limits,
292 decode: bool,
293 check: &mut impl crate::resources::Monitor,
294) -> Result<Vec<Member>> {
295 let mut at = 0;
296 let mut members = Vec::new();
297 let mut total = 0u64;
298 let mut metadata = MetadataBudget::default();
299 loop {
300 check.check()?;
301 let header = part(input, at, 512)?;
302 if header.iter().all(|b| *b == 0) {
303 if part(input, at + 512, 512)?.iter().any(|b| *b != 0)
304 || input[at..].iter().any(|b| *b != 0)
305 || input.len() % 512 != 0
306 {
307 return Err(ErrorCode::Integrity);
308 }
309 break;
310 }
311 if members.len() >= limits.entries as usize {
312 return Err(ErrorCode::Limit);
313 }
314 let expected = octal(&header[148..156])?;
315 let checksum = header
316 .iter()
317 .enumerate()
318 .map(|(i, b)| {
319 if (148..156).contains(&i) {
320 32u64
321 } else {
322 *b as u64
323 }
324 })
325 .sum::<u64>();
326 if checksum != expected {
327 return Err(ErrorCode::Integrity);
328 }
329 let mut name = tar_string(&header[..100])?;
330 if &header[257..263] == b"ustar\0" || &header[257..263] == b"ustar " {
331 let prefix = tar_string(&header[345..500])?;
332 if !prefix.is_empty() {
333 name = format!("{prefix}/{name}");
334 }
335 } else if header[257..263].iter().any(|b| *b != 0) {
336 return Err(ErrorCode::UnsupportedFeature);
337 }
338 let kind = match header[156] {
339 0 | b'0' => EntryKind::File,
340 b'5' => EntryKind::Directory,
341 b'1' | b'2' => EntryKind::Link,
342 b'x' | b'g' | b'L' | b'K' => return Err(ErrorCode::UnsupportedFeature),
343 _ => EntryKind::Other,
344 };
345 let size = octal(&header[124..136])?;
346 if kind != EntryKind::File && size != 0 {
347 return Err(ErrorCode::Integrity);
348 }
349 total = total
350 .checked_add(size)
351 .filter(|n| *n <= limits.output)
352 .ok_or(ErrorCode::Limit)?;
353 let size = usize::try_from(size).map_err(|_| ErrorCode::Limit)?;
354 let bytes = part(input, at + 512, size)?;
355 metadata.charge(&name)?;
356 let name = valid_name(&name, kind == EntryKind::Directory)?;
357 let data = if decode { bytes.to_vec() } else { Vec::new() };
358 members.push(Member {
359 entry: Entry {
360 entry_id: members.len() as u32,
361 name,
362 kind,
363 size: size as u64,
364 compressed_size: size as u64,
365 encrypted: false,
366 },
367 data,
368 });
369 at = at
370 .checked_add(512)
371 .and_then(|n| n.checked_add(size.div_ceil(512) * 512))
372 .ok_or(ErrorCode::Integrity)?;
373 }
374 validate_members(&members)?;
375 Ok(members)
376}
377#[derive(Clone, Copy, PartialEq, Eq)]
378pub(crate) struct AesExtra {
379 pub version: u16,
380 pub method: u16,
381}
382pub(crate) fn aes_extra(extra: &[u8]) -> Result<Option<AesExtra>> {
383 let mut at = 0;
384 let mut found = None;
385 while at < extra.len() {
386 let tag = u16at(extra, at)?;
387 let len = u16at(extra, at + 2)? as usize;
388 let value = part(extra, at + 4, len)?;
389 if tag == 1 {
390 return Err(ErrorCode::UnsupportedFeature);
391 }
392 if tag == 0x9901 {
393 if found.is_some() || len < 7 {
394 return Err(ErrorCode::Integrity);
395 }
396 let version = u16at(value, 0)?;
397 let method = u16at(value, 5)?;
398 if !matches!(version, 1 | 2)
399 || &value[2..4] != b"AE"
400 || value[4] != 3
401 || !matches!(method, 0 | 8)
402 {
403 return Err(ErrorCode::UnsupportedFeature);
404 }
405 found = Some(AesExtra { version, method });
406 }
407 at += 4 + len;
408 }
409 Ok(found)
410}
411/// ZIP 항목 이름을 해석함.
412///
413/// - UTF-8 플래그(비트 11)가 있으면 이름은 UTF-8이어야 하며 아니면 손상으로 봄.
414/// - 플래그가 없으면 CRC가 원래 이름과 맞는 Info-ZIP Unicode Path 확장 필드(0x7075)를 먼저 씀.
415/// CRC가 다르거나 버전이 1이 아니면 APPNOTE 4.6.9에 따라 무시함.
416/// - 그다음 이름 바이트가 UTF-8로 유효하면 그대로 씀. Linux와 macOS 도구가 이렇게 기록함.
417/// - 그 밖의 바이트(CP437, CP949 등)는 코드 페이지를 추측하지 않고 지원하지 않음으로 거부함.
418///
419/// 어느 경우든 결과는 호출자가 `valid_name`으로 다시 검사함.
420pub(crate) fn zip_name(raw: &[u8], flags: u16, extra: &[u8]) -> Result<String> {
421 if flags & 0x0800 != 0 {
422 return std::str::from_utf8(raw)
423 .map(str::to_owned)
424 .map_err(|_| ErrorCode::Integrity);
425 }
426 let mut at = 0;
427 let mut unicode = None;
428 while at < extra.len() {
429 let tag = u16at(extra, at)?;
430 let len = u16at(extra, at + 2)? as usize;
431 let value = part(extra, at + 4, len)?;
432 if tag == 0x7075 {
433 if unicode.is_some() || len < 5 {
434 return Err(ErrorCode::Integrity);
435 }
436 unicode = Some(value);
437 }
438 at += 4 + len;
439 }
440 if let Some(value) = unicode
441 && value[0] == 1
442 && u32::from_le_bytes(value[1..5].try_into().unwrap()) == crc32(0, raw)
443 {
444 return std::str::from_utf8(&value[5..])
445 .map(str::to_owned)
446 .map_err(|_| ErrorCode::Integrity);
447 }
448 std::str::from_utf8(raw)
449 .map(str::to_owned)
450 .map_err(|_| ErrorCode::UnsupportedFeature)
451}
452fn zip(
453 input: &[u8],
454 limits: Limits,
455 decode: bool,
456 password: Option<&[u8]>,
457 check: &mut impl crate::resources::Monitor,
458) -> Result<Vec<Member>> {
459 if input.len() < 22 {
460 return Err(ErrorCode::Integrity);
461 }
462 let end = (input.len().saturating_sub(65557)..=input.len() - 22)
463 .rev()
464 .find(|&i| {
465 input.get(i..i + 4) == Some(b"PK\x05\x06")
466 && u16at(input, i + 20)
467 .ok()
468 .is_some_and(|n| i + 22 + n as usize == input.len())
469 })
470 .ok_or(ErrorCode::Integrity)?;
471 let count = u16at(input, end + 10)? as usize;
472 if u16at(input, end + 4)? != 0
473 || u16at(input, end + 6)? != 0
474 || count != u16at(input, end + 8)? as usize
475 {
476 return Err(ErrorCode::UnsupportedFeature);
477 }
478 if count == 65535 || u32at(input, end + 12)? == u32::MAX || u32at(input, end + 16)? == u32::MAX
479 {
480 return Err(ErrorCode::UnsupportedFeature);
481 }
482 if count > limits.entries as usize {
483 return Err(ErrorCode::Limit);
484 }
485 let central = u32at(input, end + 16)? as usize;
486 if central.checked_add(u32at(input, end + 12)? as usize) != Some(end) {
487 return Err(ErrorCode::Integrity);
488 }
489 let mut at = central;
490 let mut members = Vec::new();
491 let mut spans = Vec::new();
492 let mut total = 0u64;
493 let mut metadata = MetadataBudget::default();
494 for id in 0..count {
495 check.check()?;
496 let h = part(input, at, 46)?;
497 if &h[..4] != b"PK\x01\x02" {
498 return Err(ErrorCode::Integrity);
499 }
500 let flags = u16at(h, 8)?;
501 let method = u16at(h, 10)?;
502 if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) || u16at(h, 34)? != 0 {
503 return Err(ErrorCode::UnsupportedFeature);
504 }
505 let crc = u32at(h, 16)?;
506 let compressed = u32at(h, 20)? as usize;
507 let size = u32at(h, 24)? as usize;
508 if compressed == u32::MAX as usize || size == u32::MAX as usize {
509 return Err(ErrorCode::UnsupportedFeature);
510 }
511 total = total
512 .checked_add(size as u64)
513 .filter(|n| *n <= limits.output)
514 .ok_or(ErrorCode::Limit)?;
515 let name_len = u16at(h, 28)? as usize;
516 let extra_len = u16at(h, 30)? as usize;
517 let comment_len = u16at(h, 32)? as usize;
518 let extra = aes_extra(part(input, at + 46 + name_len, extra_len)?)?;
519 let encrypted = flags & 1 != 0;
520 if (method == 99) != extra.is_some() || (method == 99 && !encrypted) {
521 return Err(ErrorCode::Integrity);
522 }
523 if extra.is_some_and(|e| e.version == 2) && crc != 0 {
524 return Err(ErrorCode::Integrity);
525 }
526 let raw = part(input, at + 46, name_len)?;
527 let name = zip_name(raw, flags, part(input, at + 46 + name_len, extra_len)?)?;
528 let name = name.as_str();
529 let mode = u32at(h, 38)? >> 16;
530 let kind = match mode & 0xf000 {
531 0xa000 => EntryKind::Link,
532 0x4000 => EntryKind::Directory,
533 0 | 0x8000 => {
534 if name.ends_with('/') {
535 EntryKind::Directory
536 } else {
537 EntryKind::File
538 }
539 }
540 _ => EntryKind::Other,
541 };
542 metadata.charge(name)?;
543 let name = valid_name(name, kind == EntryKind::Directory)?;
544 let local = u32at(h, 42)? as usize;
545 let lh = part(input, local, 30)?;
546 if &lh[..4] != b"PK\x03\x04" || u16at(lh, 6)? != flags || u16at(lh, 8)? != method {
547 return Err(ErrorCode::Integrity);
548 }
549 let ln = u16at(lh, 26)? as usize;
550 let le = u16at(lh, 28)? as usize;
551 if aes_extra(part(input, local + 30 + ln, le)?)? != extra
552 || u16at(lh, 10)? != u16at(h, 12)?
553 || part(input, local + 30, ln)? != raw
554 {
555 return Err(ErrorCode::Integrity);
556 }
557 if flags & 8 == 0
558 && (u32at(lh, 14)? != crc
559 || u32at(lh, 18)? as usize != compressed
560 || u32at(lh, 22)? as usize != size)
561 {
562 return Err(ErrorCode::Integrity);
563 }
564 let start = local
565 .checked_add(30 + ln + le)
566 .ok_or(ErrorCode::Integrity)?;
567 let packed = part(input, start, compressed)?;
568 let mut stop = start + compressed;
569 if flags & 8 != 0 {
570 if input.get(stop..stop + 4) == Some(b"PK\x07\x08") {
571 stop += 4;
572 }
573 if u32at(input, stop)? != crc
574 || u32at(input, stop + 4)? as usize != compressed
575 || u32at(input, stop + 8)? as usize != size
576 {
577 return Err(ErrorCode::Integrity);
578 }
579 stop += 12;
580 }
581 if stop > central {
582 return Err(ErrorCode::Integrity);
583 }
584 spans.push((local, stop));
585 if encrypted && compressed < if extra.is_some() { 28 } else { 12 } {
586 return Err(ErrorCode::Integrity);
587 }
588 let data = if decode {
589 let decrypted;
590 let packed = if encrypted {
591 let password = password.ok_or(ErrorCode::WrongPassword)?;
592 decrypted = if extra.is_some() {
593 crate::crypto::aes_decrypt(packed, password, check)?
594 } else {
595 let verifier = if flags & 8 != 0 {
596 (u16at(h, 12)? >> 8) as u8
597 } else {
598 (crc >> 24) as u8
599 };
600 crate::crypto::zipcrypto_decrypt(packed, password, verifier, check)?
601 };
602 decrypted.as_slice()
603 } else {
604 packed
605 };
606 let actual_method = extra.map_or(method, |e| e.method);
607 let bytes = if actual_method == 0 {
608 if packed.len() != size {
609 return Err(ErrorCode::Integrity);
610 }
611 packed.to_vec()
612 } else {
613 let (out, used) = inflate(packed, false, size as u64, check)?;
614 if used != packed.len() {
615 return Err(ErrorCode::Integrity);
616 }
617 out
618 };
619 if bytes.len() != size
620 || (extra.is_none_or(|e| e.version == 1) && crc32(0, &bytes) != crc)
621 {
622 return Err(ErrorCode::Integrity);
623 }
624 bytes
625 } else {
626 Vec::new()
627 };
628 if kind == EntryKind::Directory && size != 0 {
629 return Err(ErrorCode::Integrity);
630 }
631 members.push(Member {
632 entry: Entry {
633 entry_id: id as u32,
634 name,
635 kind,
636 size: size as u64,
637 compressed_size: compressed as u64,
638 encrypted,
639 },
640 data,
641 });
642 at = at
643 .checked_add(46 + name_len + extra_len + comment_len)
644 .ok_or(ErrorCode::Integrity)?;
645 }
646 if at != end {
647 return Err(ErrorCode::Integrity);
648 }
649 spans.sort_unstable();
650 let mut next = 0;
651 for (start, stop) in spans {
652 if start != next {
653 return Err(ErrorCode::Integrity);
654 }
655 next = stop;
656 }
657 if next != central {
658 return Err(ErrorCode::Integrity);
659 }
660 validate_members(&members)?;
661 Ok(members)
662}
663pub fn parse(
664 input: &[u8],
665 limits: Limits,
666 decode: bool,
667 check: &mut impl crate::resources::Monitor,
668) -> Result<Catalog> {
669 parse_with_password(input, limits, decode, None, check)
670}
671pub fn parse_with_password(
672 input: &[u8],
673 limits: Limits,
674 decode: bool,
675 password: Option<&[u8]>,
676 check: &mut impl crate::resources::Monitor,
677) -> Result<Catalog> {
678 if !limits.valid() {
679 return Err(ErrorCode::Limit);
680 }
681 let limits = limits.legacy();
682 if input.len() as u64 > limits.input {
683 return Err(ErrorCode::Limit);
684 }
685 if input.starts_with(b"7z\xbc\xaf\x27\x1c") {
686 return Ok(Catalog {
687 format: Format::SevenZip,
688 members: crate::seven_zip::parse(input, limits, decode, check)?,
689 });
690 }
691 if input.starts_with(b"PK\x03\x04") || input.starts_with(b"PK\x05\x06") {
692 return Ok(Catalog {
693 format: Format::Zip,
694 members: zip(input, limits, decode, password, check)?,
695 });
696 }
697 if input.starts_with(&[31, 139]) {
698 let bytes = gzip(input, limits, check)?;
699 if bytes.len() >= 512 && matches!(&bytes[257..263], b"ustar\0" | b"ustar ") {
700 return Ok(Catalog {
701 format: Format::TarGzip,
702 members: tar(&bytes, limits, decode, check)?,
703 });
704 }
705 let len = bytes.len() as u64;
706 return Ok(Catalog {
707 format: Format::Gzip,
708 members: vec![Member {
709 entry: Entry {
710 entry_id: 0,
711 name: "GZip stream".to_owned(),
712 kind: EntryKind::File,
713 size: len,
714 compressed_size: input.len() as u64,
715 encrypted: false,
716 },
717 data: if decode { bytes } else { Vec::new() },
718 }],
719 });
720 }
721 if input.len() >= 512 {
722 return Ok(Catalog {
723 format: Format::Tar,
724 members: tar(input, limits, decode, check)?,
725 });
726 }
727 Err(ErrorCode::UnsupportedFormat)
728}
729fn deflate(
730 input: &[u8],
731 limit: u64,
732 check: &mut impl crate::resources::Monitor,
733) -> Result<Vec<u8>> {
734 let mut stream = Deflate::new(6, false, 15);
735 let mut output = Vec::new();
736 let mut buffer = [0; 65536];
737 loop {
738 check.check()?;
739 let a = stream.total_in();
740 let b = stream.total_out();
741 let status = stream
742 .compress(&input[a as usize..], &mut buffer, DeflateFlush::Finish)
743 .map_err(|_| ErrorCode::Internal)?;
744 bounded_append(
745 &mut output,
746 &buffer[..(stream.total_out() - b) as usize],
747 limit,
748 )?;
749 if status == Status::StreamEnd {
750 return Ok(output);
751 }
752 if a == stream.total_in() && b == stream.total_out() {
753 return Err(ErrorCode::Internal);
754 }
755 }
756}
757fn put16(v: &mut Vec<u8>, n: u16) {
758 v.extend(n.to_le_bytes());
759}
760fn put32(v: &mut Vec<u8>, n: u32) {
761 v.extend(n.to_le_bytes());
762}
763pub fn create_zip(
764 members: &[Member],
765 method: Method,
766 limits: Limits,
767 check: &mut impl crate::resources::Monitor,
768) -> Result<Vec<u8>> {
769 create_zip_with_password(members, method, limits, None, check)
770}
771pub fn create_zip_with_password(
772 members: &[Member],
773 method: Method,
774 limits: Limits,
775 password: Option<&[u8]>,
776 check: &mut impl crate::resources::Monitor,
777) -> Result<Vec<u8>> {
778 if !limits.valid() {
779 return Err(ErrorCode::Limit);
780 }
781 let limits = limits.legacy();
782 if members.len() > limits.entries as usize || members.len() >= 65535 {
783 return Err(ErrorCode::Limit);
784 }
785 validate_members(members)?;
786 let mut out = Vec::new();
787 let mut cd = Vec::new();
788 let mut total = 0u64;
789 for m in members {
790 check.check()?;
791 total = total
792 .checked_add(m.data.len() as u64)
793 .filter(|n| *n <= limits.output)
794 .ok_or(ErrorCode::Limit)?;
795 if m.entry.kind != EntryKind::File {
796 return Err(ErrorCode::UnsupportedFeature);
797 }
798 let name = m.entry.name.as_bytes();
799 let crc = if password.is_some() {
800 0
801 } else {
802 crc32(0, &m.data)
803 };
804 let offset = out.len() as u32;
805 let packed = match method {
806 Method::Store => m.data.clone(),
807 Method::Deflate => deflate(&m.data, limits.output, check)?,
808 };
809 let method = match method {
810 Method::Store => 0,
811 Method::Deflate => 8,
812 };
813 let mut extra = Vec::new();
814 let flags = if password.is_some() { 0x0801 } else { 0x0800 };
815 let version = if password.is_some() { 51 } else { 20 };
816 let (method, packed) = if let Some(password) = password {
817 put16(&mut extra, 0x9901);
818 put16(&mut extra, 7);
819 put16(&mut extra, 2);
820 extra.extend(b"AE");
821 extra.push(3);
822 put16(&mut extra, method);
823 (99, crate::crypto::aes_encrypt(&packed, password, check)?)
824 } else {
825 (method, packed)
826 };
827 out.extend(b"PK\x03\x04");
828 put16(&mut out, version);
829 put16(&mut out, flags);
830 put16(&mut out, method);
831 put16(&mut out, 0);
832 put16(&mut out, 33);
833 put32(&mut out, crc);
834 put32(&mut out, packed.len() as u32);
835 put32(&mut out, m.data.len() as u32);
836 put16(&mut out, name.len() as u16);
837 put16(&mut out, extra.len() as u16);
838 out.extend(name);
839 out.extend(&extra);
840 bounded_append(&mut out, &packed, limits.output)?;
841 cd.extend(b"PK\x01\x02");
842 put16(&mut cd, 0x0314);
843 put16(&mut cd, version);
844 put16(&mut cd, flags);
845 put16(&mut cd, method);
846 put16(&mut cd, 0);
847 put16(&mut cd, 33);
848 put32(&mut cd, crc);
849 put32(&mut cd, packed.len() as u32);
850 put32(&mut cd, m.data.len() as u32);
851 put16(&mut cd, name.len() as u16);
852 put16(&mut cd, extra.len() as u16);
853 put16(&mut cd, 0);
854 put16(&mut cd, 0);
855 put16(&mut cd, 0);
856 put32(&mut cd, 0o100600 << 16);
857 put32(&mut cd, offset);
858 cd.extend(name);
859 cd.extend(&extra);
860 }
861 let offset = out.len();
862 bounded_append(&mut out, &cd, limits.output)?;
863 let mut end = Vec::new();
864 end.extend(b"PK\x05\x06");
865 put16(&mut end, 0);
866 put16(&mut end, 0);
867 put16(&mut end, members.len() as u16);
868 put16(&mut end, members.len() as u16);
869 put32(&mut end, cd.len() as u32);
870 put32(&mut end, offset as u32);
871 put16(&mut end, 0);
872 bounded_append(&mut out, &end, limits.output)?;
873 Ok(out)
874}
875
876#[cfg(test)]
877#[path = "../../../tests/rust-archive-worker/metadata_policy.rs"]
878mod metadata_tests;