team-ljyzipelo

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