team-ljyzipelo

공개
830줄28 KB
1use crate::{
2 archive::{self, Member, MetadataBudget},
3 crypto,
4 protocol::*,
5 spool,
6};
7use std::{
8 fs::File,
9 io::{Read, Seek, SeekFrom, Write},
10};
11use zeroize::Zeroizing;
12use zlib_rs::{Inflate, InflateFlush, Status, crc32::crc32};
13
14type Result<T> = std::result::Result<T, ErrorCode>;
15const CHUNK: usize = 65536;
16fn at(file: &mut File, offset: u64, bytes: &mut [u8]) -> Result<()> {
17 file.seek(SeekFrom::Start(offset))
18 .map_err(|_| ErrorCode::Io)?;
19 file.read_exact(bytes).map_err(|_| ErrorCode::Integrity)
20}
21fn bytes(file: &mut File, offset: u64, size: usize) -> Result<Vec<u8>> {
22 let mut result = vec![0; size];
23 at(file, offset, &mut result)?;
24 Ok(result)
25}
26fn u16at(b: &[u8], at: usize) -> u16 {
27 u16::from_le_bytes(b[at..at + 2].try_into().unwrap())
28}
29fn u32at(b: &[u8], at: usize) -> u32 {
30 u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
31}
32fn u64at(b: &[u8], at: usize) -> u64 {
33 u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
34}
35fn add(a: u64, b: u64) -> Result<u64> {
36 a.checked_add(b).ok_or(ErrorCode::Integrity)
37}
38fn io<T>(v: std::io::Result<T>) -> Result<T> {
39 v.map_err(crate::space::io_error)
40}
41
42pub(crate) struct Catalog {
43 pub format: Format,
44 pub members: Vec<Member>,
45 pub offsets: Vec<u64>,
46 pub data: File,
47}
48impl Catalog {
49 pub fn open(
50 source: &mut File,
51 len: u64,
52 limits: Limits,
53 decode: bool,
54 password: Option<&[u8]>,
55 check: &mut impl crate::resources::Monitor,
56 ) -> Result<Self> {
57 Self::open_selected(source, len, limits, decode, password, None, check)
58 }
59 pub fn preview(
60 source: &mut File,
61 len: u64,
62 limits: Limits,
63 password: Option<&[u8]>,
64 entry_id: u32,
65 check: &mut impl crate::resources::Monitor,
66 ) -> Result<Self> {
67 Self::open_selected(source, len, limits, true, password, Some(entry_id), check)
68 }
69 fn open_selected(
70 source: &mut File,
71 len: u64,
72 limits: Limits,
73 decode: bool,
74 password: Option<&[u8]>,
75 selected: Option<u32>,
76 check: &mut impl crate::resources::Monitor,
77 ) -> Result<Self> {
78 let mut magic = [0; 6];
79 let n = len.min(6) as usize;
80 at(source, 0, &mut magic[..n])?;
81 if magic.starts_with(b"7z\xbc\xaf\x27\x1c") {
82 return crate::seven_zip::open_selected(source, len, limits, decode, selected, check);
83 }
84 if magic.starts_with(b"PK\x03\x04")
85 || magic.starts_with(b"PK\x05\x06")
86 || magic.starts_with(b"PK\x06\x06")
87 {
88 return zip(source, len, limits, decode, password, selected, check);
89 }
90 let compression = if magic.starts_with(b"BZh") {
91 Some(crate::compressed_tar::Compression::Bzip2)
92 } else if &magic == b"\xfd7zXZ\0" {
93 Some(crate::compressed_tar::Compression::Xz)
94 } else {
95 None
96 };
97 if let Some(compression) = compression {
98 let (data, expanded) =
99 crate::compressed_tar::decode(source, compression, limits.output, check)?;
100 if expanded < 1024 {
101 return Err(ErrorCode::Integrity);
102 }
103 return tar(data, expanded, limits, Format::Tar, check);
104 }
105 if magic.starts_with(&[31, 139]) {
106 let mut data = spool::temporary()?;
107 io(source.rewind())?;
108 let expanded = inflate(source, len, true, limits.output, &mut data, check)?.0;
109 let mut header = [0; 512];
110 if expanded >= 512 {
111 at(&mut data, 0, &mut header)?;
112 if matches!(&header[257..263], b"ustar\0" | b"ustar ") {
113 return tar(data, expanded, limits, Format::TarGzip, check);
114 }
115 }
116 return Ok(Self {
117 format: Format::Gzip,
118 members: vec![Member {
119 entry: Entry {
120 entry_id: 0,
121 name: "GZip stream".to_owned(),
122 kind: EntryKind::File,
123 size: expanded,
124 compressed_size: len,
125 encrypted: false,
126 },
127 data: Vec::new(),
128 }],
129 offsets: vec![0],
130 data,
131 });
132 }
133 if len >= 512 {
134 return tar(io(source.try_clone())?, len, limits, Format::Tar, check);
135 }
136 Err(ErrorCode::UnsupportedFormat)
137 }
138}
139
140fn tar(
141 mut data: File,
142 len: u64,
143 limits: Limits,
144 format: Format,
145 check: &mut impl crate::resources::Monitor,
146) -> Result<Catalog> {
147 let mut cursor = 0u64;
148 let mut total = 0u64;
149 let mut members = Vec::new();
150 let mut offsets = Vec::new();
151 let mut metadata = MetadataBudget::default();
152 loop {
153 check.check()?;
154 let mut header = [0; 512];
155 if add(cursor, 512)? > len {
156 return Err(ErrorCode::Integrity);
157 }
158 crate::resources::completed(at(&mut data, cursor, &mut header), check)?;
159 if header.iter().all(|b| *b == 0) {
160 if add(cursor, 1024)? > len || len % 512 != 0 {
161 return Err(ErrorCode::Integrity);
162 }
163 let mut buffer = Zeroizing::new([0; CHUNK]);
164 let mut remaining = len - cursor - 512;
165 while remaining != 0 {
166 check.check()?;
167 let n = remaining.min(CHUNK as u64) as usize;
168 io(data.read_exact(&mut buffer[..n]))?;
169 if buffer[..n].iter().any(|b| *b != 0) {
170 return Err(ErrorCode::Integrity);
171 }
172 remaining -= n as u64;
173 crate::resources::completed(Ok(()), check)?;
174 }
175 break;
176 }
177 if members.len() >= limits.entries as usize {
178 return Err(ErrorCode::Limit);
179 }
180 let sum = header
181 .iter()
182 .enumerate()
183 .map(|(i, b)| {
184 if (148..156).contains(&i) {
185 32
186 } else {
187 *b as u64
188 }
189 })
190 .sum::<u64>();
191 if sum != archive::octal(&header[148..156])? {
192 return Err(ErrorCode::Integrity);
193 }
194 let mut name = archive::tar_string(&header[..100])?;
195 if matches!(&header[257..263], b"ustar\0" | b"ustar ") {
196 let prefix = archive::tar_string(&header[345..500])?;
197 if !prefix.is_empty() {
198 name = format!("{prefix}/{name}");
199 }
200 } else if header[257..263].iter().any(|b| *b != 0) {
201 return Err(ErrorCode::UnsupportedFeature);
202 }
203 let kind = match header[156] {
204 0 | b'0' => EntryKind::File,
205 b'5' => EntryKind::Directory,
206 b'1' | b'2' => EntryKind::Link,
207 b'x' | b'g' | b'L' | b'K' => return Err(ErrorCode::UnsupportedFeature),
208 _ => EntryKind::Other,
209 };
210 let size = archive::octal(&header[124..136])?;
211 if kind != EntryKind::File && size != 0 {
212 return Err(ErrorCode::Integrity);
213 }
214 total = total
215 .checked_add(size)
216 .filter(|n| *n <= limits.output)
217 .ok_or(ErrorCode::Limit)?;
218 check.observe(
219 ResourceUsage {
220 estimated_bytes: Some(total),
221 actual_entries: Some(members.len() as u32 + 1),
222 ..ResourceUsage::default()
223 },
224 Some(&data),
225 )?;
226 crate::resources::completed(Ok(()), check)?;
227 let start = add(cursor, 512)?;
228 cursor = add(
229 start,
230 size.checked_add(511).ok_or(ErrorCode::Integrity)? / 512 * 512,
231 )?;
232 if cursor > len {
233 return Err(ErrorCode::Integrity);
234 }
235 metadata.charge_with(&name, check.metadata_limits())?;
236 let name = archive::valid_name(&name, kind == EntryKind::Directory)?;
237 offsets.push(start);
238 members.push(Member {
239 entry: Entry {
240 entry_id: members.len() as u32,
241 name,
242 kind,
243 size,
244 compressed_size: size,
245 encrypted: false,
246 },
247 data: Vec::new(),
248 });
249 crate::resources::completed(Ok(()), check)?;
250 }
251 archive::validate_members_with(&members, check)?;
252 Ok(Catalog {
253 format,
254 members,
255 offsets,
256 data,
257 })
258}
259
260// ZIP 항목과 연결 GZip 스트림의 해제 총량을 제한함.
261fn inflate(
262 input: &mut impl Read,
263 length: u64,
264 gzip: bool,
265 limit: u64,
266 output: &mut File,
267 check: &mut impl crate::resources::Monitor,
268) -> Result<(u64, u32)> {
269 let base = io(output.stream_position())?;
270 let mut remaining = length;
271 let mut buffer = Zeroizing::new([0; CHUNK]);
272 let mut plain = Zeroizing::new([0; CHUNK]);
273 let mut have = 0;
274 let mut used = 0;
275 let mut total = 0u64;
276 let mut crc = 0;
277 loop {
278 let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 });
279 loop {
280 check.check()?;
281 if used == have && remaining != 0 {
282 have = input
283 .read(&mut buffer[..remaining.min(CHUNK as u64) as usize])
284 .map_err(|_| ErrorCode::Io)?;
285 if have == 0 {
286 return Err(ErrorCode::Integrity);
287 }
288 remaining -= have as u64;
289 used = 0;
290 crate::resources::completed(Ok(()), check)?;
291 }
292 let a = stream.total_in();
293 let b = stream.total_out();
294 let status = stream
295 .decompress(&buffer[used..have], &mut plain[..], InflateFlush::NoFlush)
296 .map_err(|_| ErrorCode::Integrity)?;
297 used += (stream.total_in() - a) as usize;
298 let n = (stream.total_out() - b) as usize;
299 total = total
300 .checked_add(n as u64)
301 .filter(|n| *n <= limit)
302 .ok_or(ErrorCode::Limit)?;
303 check.observe(
304 ResourceUsage {
305 actual_bytes: Some(base.checked_add(total).ok_or(ErrorCode::Limit)?),
306 compressed_bytes: Some(length),
307 ratio_output_bytes: Some(total),
308 ..ResourceUsage::default()
309 },
310 Some(output),
311 )?;
312 if n != 0 || stream.total_in() != a {
313 crate::resources::completed(Ok(()), check)?;
314 }
315 crc = crc32(crc, &plain[..n]);
316 crate::space::ensure(output, n as u64)?;
317 if n != 0 {
318 crate::resources::completed(io(output.write_all(&plain[..n])), check)?;
319 }
320 if status == Status::StreamEnd {
321 break;
322 }
323 if a == stream.total_in() && b == stream.total_out() {
324 return Err(ErrorCode::Integrity);
325 }
326 }
327 if remaining == 0 && used == have {
328 break;
329 }
330 if !gzip {
331 return Err(ErrorCode::Integrity);
332 }
333 }
334 Ok((total, crc))
335}
336
337struct Packed {
338 offset: u64,
339 size: u64,
340 method: u16,
341 crc: Option<u32>,
342 flags: u16,
343 verifier: u8,
344 aes: bool,
345}
346
347fn extra(bytes: &[u8]) -> Result<(Option<archive::AesExtra>, Option<Vec<u8>>)> {
348 let mut at = 0;
349 let mut aes = Vec::new();
350 let mut large = None;
351 while at < bytes.len() {
352 if bytes.len() - at < 4 {
353 return Err(ErrorCode::Integrity);
354 }
355 let tag = u16at(bytes, at);
356 let len = u16at(bytes, at + 2) as usize;
357 let end = at + 4 + len;
358 if end > bytes.len() {
359 return Err(ErrorCode::Integrity);
360 }
361 if tag == 1 {
362 if large.is_some() {
363 return Err(ErrorCode::Integrity);
364 }
365 large = Some(bytes[at + 4..end].to_vec());
366 } else {
367 aes.extend_from_slice(&bytes[at..end]);
368 }
369 at = end;
370 }
371 Ok((archive::aes_extra(&aes)?, large))
372}
373fn large_value(value: u32, extra: &mut &[u8]) -> Result<u64> {
374 if value != u32::MAX {
375 return Ok(value as u64);
376 }
377 if extra.len() < 8 {
378 return Err(ErrorCode::Integrity);
379 }
380 let result = u64at(extra, 0);
381 *extra = &extra[8..];
382 Ok(result)
383}
384fn expanded(value: u64, maximum: u64, large: u64) -> Result<u64> {
385 if value == maximum || value == large {
386 Ok(large)
387 } else {
388 Err(ErrorCode::Integrity)
389 }
390}
391fn disk_start(value: u16, extra: &mut &[u8]) -> Result<u32> {
392 if value != u16::MAX {
393 return Ok(value as u32);
394 }
395 if extra.len() < 4 {
396 return Err(ErrorCode::Integrity);
397 }
398 let result = u32at(extra, 0);
399 *extra = &extra[4..];
400 Ok(result)
401}
402fn local_sizes(size: u32, compressed: u32, extra: Option<&[u8]>) -> Result<(u64, u64)> {
403 if let Some(extra) = extra {
404 // 로컬 ZIP64 추가 필드에는 두 크기가 함께 들어감.
405 if extra.len() < 16 {
406 return Err(ErrorCode::Integrity);
407 }
408 Ok((
409 expanded(size as u64, u32::MAX as u64, u64at(extra, 0))?,
410 expanded(compressed as u64, u32::MAX as u64, u64at(extra, 8))?,
411 ))
412 } else if size == u32::MAX || compressed == u32::MAX {
413 Err(ErrorCode::Integrity)
414 } else {
415 Ok((size as u64, compressed as u64))
416 }
417}
418fn descriptor_size(
419 bytes: &[u8],
420 crc: u32,
421 compressed: u64,
422 size: u64,
423 wide_required: bool,
424) -> Result<usize> {
425 // 일반 크기 헤더와 64비트 디스크립터를 함께 기록하는 도구도 있음.
426 if bytes.len() >= 20
427 && u32at(bytes, 0) == crc
428 && u64at(bytes, 4) == compressed
429 && u64at(bytes, 12) == size
430 {
431 return Ok(20);
432 }
433 if !wide_required
434 && bytes.len() >= 12
435 && u32at(bytes, 0) == crc
436 && u32at(bytes, 4) as u64 == compressed
437 && u32at(bytes, 8) as u64 == size
438 {
439 return Ok(12);
440 }
441 Err(ErrorCode::Integrity)
442}
443fn zip(
444 source: &mut File,
445 len: u64,
446 limits: Limits,
447 decode: bool,
448 password: Option<&[u8]>,
449 selected: Option<u32>,
450 check: &mut impl crate::resources::Monitor,
451) -> Result<Catalog> {
452 if len < 22 {
453 return Err(ErrorCode::Integrity);
454 }
455 let tail_at = len.saturating_sub(65557);
456 let tail = bytes(source, tail_at, (len - tail_at) as usize)?;
457 let end = (0..=tail.len() - 22)
458 .rev()
459 .find(|&i| {
460 &tail[i..i + 4] == b"PK\x05\x06" && i + 22 + u16at(&tail, i + 20) as usize == tail.len()
461 })
462 .ok_or(ErrorCode::Integrity)?;
463 let h = &tail[end..];
464 let mut disk = u16at(h, 4) as u64;
465 let mut central_disk = u16at(h, 6) as u64;
466 let mut entries_on_disk = u16at(h, 8) as u64;
467 let mut count = u16at(h, 10) as u64;
468 let mut central_size = u32at(h, 12) as u64;
469 let mut central = u32at(h, 16) as u64;
470 let mut central_end = tail_at + end as u64;
471 let required_zip64 = [disk, central_disk, entries_on_disk, count].contains(&(u16::MAX as u64))
472 || central_size == u32::MAX as u64
473 || central == u32::MAX as u64;
474 let locator = if central_end >= 20 {
475 bytes(source, central_end - 20, 20)?
476 } else {
477 Vec::new()
478 };
479 // 중앙 디렉터리 주석의 동일 서명을 locator로 오인하지 않음
480 let has_locator =
481 locator.starts_with(b"PK\x06\x07") && add(central, central_size)? != central_end;
482 if required_zip64 || has_locator {
483 if locator.len() != 20 {
484 return Err(ErrorCode::Integrity);
485 }
486 if &locator[..4] != b"PK\x06\x07" || u32at(&locator, 4) != 0 || u32at(&locator, 16) != 1 {
487 return Err(ErrorCode::UnsupportedFeature);
488 }
489 let offset = u64at(&locator, 8);
490 if add(offset, 56)? > central_end - 20 {
491 return Err(ErrorCode::Integrity);
492 }
493 let large = bytes(source, offset, 56)?;
494 if &large[..4] != b"PK\x06\x06"
495 || u64at(&large, 4) < 44
496 || add(offset, add(12, u64at(&large, 4))?)? != central_end - 20
497 {
498 return Err(ErrorCode::Integrity);
499 }
500 // 각 필드의 확장값을 해석한 뒤 단일 디스크 조건을 검사함.
501 disk = expanded(disk, u16::MAX as u64, u32at(&large, 16) as u64)?;
502 central_disk = expanded(central_disk, u16::MAX as u64, u32at(&large, 20) as u64)?;
503 entries_on_disk = expanded(entries_on_disk, u16::MAX as u64, u64at(&large, 24))?;
504 count = expanded(count, u16::MAX as u64, u64at(&large, 32))?;
505 central_size = expanded(central_size, u32::MAX as u64, u64at(&large, 40))?;
506 central = expanded(central, u32::MAX as u64, u64at(&large, 48))?;
507 central_end = offset;
508 }
509 if disk != 0 || central_disk != 0 || entries_on_disk != count {
510 return Err(ErrorCode::UnsupportedFeature);
511 }
512 if count > limits.entries as u64 {
513 return Err(ErrorCode::Limit);
514 }
515 check.observe(
516 ResourceUsage {
517 estimated_entries: Some(count as u32),
518 ..ResourceUsage::default()
519 },
520 Some(source),
521 )?;
522 if add(central, central_size)? != central_end {
523 return Err(ErrorCode::Integrity);
524 }
525 let mut cursor = central;
526 let mut total = 0u64;
527 let mut compressed_total = 0u64;
528 let mut metadata = MetadataBudget::default();
529 let mut members = Vec::new();
530 let mut packed = Vec::new();
531 let mut spans = Vec::new();
532 for id in 0..count {
533 check.check()?;
534 if add(cursor, 46)? > central_end {
535 return Err(ErrorCode::Integrity);
536 }
537 let h = bytes(source, cursor, 46)?;
538 crate::resources::completed(Ok(()), check)?;
539 if &h[..4] != b"PK\x01\x02" {
540 return Err(ErrorCode::Integrity);
541 }
542 let flags = u16at(&h, 8);
543 let method = u16at(&h, 10);
544 if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) {
545 return Err(ErrorCode::UnsupportedFeature);
546 }
547 let crc = u32at(&h, 16);
548 let (nn, ne, nc) = (
549 u16at(&h, 28) as u64,
550 u16at(&h, 30) as u64,
551 u16at(&h, 32) as u64,
552 );
553 let next = add(cursor, 46 + nn + ne + nc)?;
554 if next > central_end {
555 return Err(ErrorCode::Integrity);
556 }
557 if nn > 4096 {
558 return Err(ErrorCode::UnsafePath);
559 }
560 let raw = bytes(source, cursor + 46, nn as usize)?;
561 let central_extra = bytes(source, cursor + 46 + nn, ne as usize)?;
562 let (aes, large) = extra(&central_extra)?;
563 let name = archive::zip_name(&raw, flags, &central_extra)?;
564 let name = name.as_str();
565 let mut large = large.as_deref().unwrap_or(&[]);
566 let size = large_value(u32at(&h, 24), &mut large)?;
567 let compressed = large_value(u32at(&h, 20), &mut large)?;
568 let local = large_value(u32at(&h, 42), &mut large)?;
569 if disk_start(u16at(&h, 34), &mut large)? != 0 {
570 return Err(ErrorCode::UnsupportedFeature);
571 }
572 let encrypted = flags & 1 != 0;
573 if (method == 99) != aes.is_some()
574 || (method == 99 && !encrypted)
575 || (aes.is_some_and(|a| a.version == 2) && crc != 0)
576 {
577 return Err(ErrorCode::Integrity);
578 }
579 let overhead = if !encrypted {
580 0
581 } else if aes.is_some() {
582 28
583 } else {
584 12
585 };
586 let payload = compressed
587 .checked_sub(overhead)
588 .ok_or(ErrorCode::Integrity)?;
589 compressed_total = add(compressed_total, payload)?;
590 total = total
591 .checked_add(size)
592 .filter(|n| *n <= limits.output)
593 .ok_or(ErrorCode::Limit)?;
594 check.observe(
595 ResourceUsage {
596 estimated_bytes: Some(total),
597 estimated_entries: Some(count as u32),
598 compressed_bytes: Some(payload),
599 ratio_output_bytes: Some(size),
600 ..ResourceUsage::default()
601 },
602 Some(source),
603 )?;
604 crate::resources::completed(Ok(()), check)?;
605 let mode = u32at(&h, 38) >> 16;
606 let kind = match mode & 0xf000 {
607 0xa000 => EntryKind::Link,
608 0x4000 => EntryKind::Directory,
609 0 | 0x8000 => {
610 if name.ends_with('/') {
611 EntryKind::Directory
612 } else {
613 EntryKind::File
614 }
615 }
616 _ => EntryKind::Other,
617 };
618 if kind == EntryKind::Directory && size != 0 {
619 return Err(ErrorCode::Integrity);
620 }
621 metadata.charge_with(name, check.metadata_limits())?;
622 let name = archive::valid_name(name, kind == EntryKind::Directory)?;
623 if add(local, 30)? > central {
624 return Err(ErrorCode::Integrity);
625 }
626 let lh = bytes(source, local, 30)?;
627 crate::resources::completed(Ok(()), check)?;
628 if &lh[..4] != b"PK\x03\x04"
629 || u16at(&lh, 6) != flags
630 || u16at(&lh, 8) != method
631 || u16at(&lh, 10) != u16at(&h, 12)
632 {
633 return Err(ErrorCode::Integrity);
634 }
635 let (ln, le) = (u16at(&lh, 26) as u64, u16at(&lh, 28) as u64);
636 let start = add(local, 30 + ln + le)?;
637 if start > central || ln != nn {
638 return Err(ErrorCode::Integrity);
639 }
640 if bytes(source, local + 30, ln as usize)? != raw {
641 return Err(ErrorCode::Integrity);
642 }
643 let (local_aes, local_large) = extra(&bytes(source, local + 30 + ln, le as usize)?)?;
644 if local_aes != aes || local_large.as_ref().is_some_and(|values| values.len() < 16) {
645 return Err(ErrorCode::Integrity);
646 }
647 let size_zip64 = u32at(&h, 20) == u32::MAX
648 || u32at(&h, 24) == u32::MAX
649 || u32at(&lh, 18) == u32::MAX
650 || u32at(&lh, 22) == u32::MAX
651 || local_large.is_some();
652 if flags & 8 == 0 {
653 let (local_size, local_compressed) =
654 local_sizes(u32at(&lh, 22), u32at(&lh, 18), local_large.as_deref())?;
655 if u32at(&lh, 14) != crc || local_size != size || local_compressed != compressed {
656 return Err(ErrorCode::Integrity);
657 }
658 }
659 let mut stop = add(start, compressed)?;
660 if stop > central {
661 return Err(ErrorCode::Integrity);
662 }
663 if flags & 8 != 0 {
664 let descriptor_len = if size_zip64 { 20 } else { 12 };
665 if add(stop, descriptor_len)? > central {
666 return Err(ErrorCode::Integrity);
667 }
668 let signature = bytes(source, stop, 4)?;
669 if signature == b"PK\x07\x08" {
670 stop = add(stop, 4)?;
671 }
672 let d = bytes(source, stop, (central - stop).min(20) as usize)?;
673 let descriptor_len = descriptor_size(&d, crc, compressed, size, size_zip64)?;
674 stop = add(stop, descriptor_len as u64)?;
675 }
676 spans.push((local, stop));
677 packed.push(Packed {
678 offset: start,
679 size: compressed,
680 method: aes.map_or(method, |a| a.method),
681 crc: if aes.is_some_and(|a| a.version == 2) {
682 None
683 } else {
684 Some(crc)
685 },
686 flags,
687 verifier: if flags & 8 != 0 {
688 (u16at(&h, 12) >> 8) as u8
689 } else {
690 (crc >> 24) as u8
691 },
692 aes: aes.is_some(),
693 });
694 members.push(Member {
695 entry: Entry {
696 entry_id: id as u32,
697 name,
698 kind,
699 size,
700 compressed_size: compressed,
701 encrypted,
702 },
703 data: Vec::new(),
704 });
705 cursor = next;
706 crate::resources::completed(Ok(()), check)?;
707 }
708 if cursor != central_end {
709 return Err(ErrorCode::Integrity);
710 }
711 spans.sort_unstable();
712 let mut next = 0;
713 for (a, b) in spans {
714 if a != next {
715 return Err(ErrorCode::Integrity);
716 }
717 next = b;
718 crate::resources::completed(Ok(()), check)?;
719 }
720 if next != central {
721 return Err(ErrorCode::Integrity);
722 }
723 archive::validate_members_with(&members, check)?;
724 // 작은 항목으로 나뉜 고압축 입력도 디코딩 전에 합계로 확인함.
725 check.observe(
726 ResourceUsage {
727 estimated_bytes: Some(total),
728 estimated_entries: Some(count as u32),
729 compressed_bytes: Some(compressed_total),
730 ratio_output_bytes: Some(total),
731 ..ResourceUsage::default()
732 },
733 Some(source),
734 )?;
735 let mut data = spool::temporary()?;
736 if decode {
737 let required = if let Some(id) = selected {
738 members
739 .get(id as usize)
740 .ok_or(ErrorCode::InvalidRequest)?
741 .entry
742 .size
743 } else {
744 total
745 };
746 crate::space::ensure(&data, required)?;
747 }
748 let mut offsets = Vec::new();
749 for (member, packed) in members.iter().zip(packed) {
750 check.check()?;
751 offsets.push(io(data.stream_position())?);
752 if !decode || selected.is_some_and(|id| id != member.entry.entry_id) {
753 crate::resources::completed(Ok(()), check)?;
754 continue;
755 }
756 let (decoder, start, length) = if packed.flags & 1 != 0 {
757 crypto::Decryptor::prepare(
758 source,
759 packed.offset,
760 packed.size,
761 password.ok_or(ErrorCode::WrongPassword)?,
762 packed.aes,
763 packed.verifier,
764 check,
765 )?
766 } else {
767 (crypto::Decryptor::Plain, packed.offset, packed.size)
768 };
769 io(source.seek(SeekFrom::Start(start)))?;
770 let mut reader = Decoded {
771 reader: source.take(length),
772 decoder,
773 };
774 let (size, crc) = if packed.method == 8 {
775 inflate(
776 &mut reader,
777 length,
778 false,
779 member.entry.size,
780 &mut data,
781 check,
782 )?
783 } else {
784 let mut buffer = Zeroizing::new([0; CHUNK]);
785 let mut total = 0u64;
786 let mut crc = 0;
787 loop {
788 check.check()?;
789 let n = io(reader.read(&mut buffer[..]))?;
790 if n == 0 {
791 break;
792 }
793 total = total
794 .checked_add(n as u64)
795 .filter(|n| *n <= member.entry.size)
796 .ok_or(ErrorCode::Integrity)?;
797 crate::resources::completed(Ok(()), check)?;
798 crate::space::ensure(&data, n as u64)?;
799 crc = crc32(crc, &buffer[..n]);
800 crate::resources::completed(io(data.write_all(&buffer[..n])), check)?;
801 }
802 (total, crc)
803 };
804 if size != member.entry.size || packed.crc.is_some_and(|c| c != crc) {
805 return Err(ErrorCode::Integrity);
806 }
807 crate::resources::completed(Ok(()), check)?;
808 }
809 Ok(Catalog {
810 format: Format::Zip,
811 members,
812 offsets,
813 data,
814 })
815}
816struct Decoded<R> {
817 reader: R,
818 decoder: crypto::Decryptor,
819}
820impl<R: Read> Read for Decoded<R> {
821 fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
822 let n = self.reader.read(output)?;
823 self.decoder.apply(&mut output[..n]);
824 Ok(n)
825 }
826}
827
828#[cfg(test)]
829#[path = "../../../tests/rust-archive-worker/streaming_bounds.rs"]
830mod bounds;