team-ljyzipelo

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