team-ljyzipelo

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