team-ljyzipelo

공개
776줄25 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 at(&mut data, cursor, &mut header)?;
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 check.activity()?;
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 check.activity()?;
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(&name)?;
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 }
229 archive::validate_members(&members)?;
230 Ok(Catalog {
231 format,
232 members,
233 offsets,
234 data,
235 })
236}
237
238// ZIP 항목과 연결 GZip 스트림의 해제 총량을 제한함.
239fn inflate(
240 input: &mut impl Read,
241 length: u64,
242 gzip: bool,
243 limit: u64,
244 output: &mut File,
245 check: &mut impl crate::resources::Monitor,
246) -> Result<(u64, u32)> {
247 let base = io(output.stream_position())?;
248 let mut remaining = length;
249 let mut buffer = Zeroizing::new([0; CHUNK]);
250 let mut plain = Zeroizing::new([0; CHUNK]);
251 let mut have = 0;
252 let mut used = 0;
253 let mut total = 0u64;
254 let mut crc = 0;
255 loop {
256 let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 });
257 loop {
258 check.check()?;
259 if used == have && remaining != 0 {
260 have = input
261 .read(&mut buffer[..remaining.min(CHUNK as u64) as usize])
262 .map_err(|_| ErrorCode::Io)?;
263 if have == 0 {
264 return Err(ErrorCode::Integrity);
265 }
266 remaining -= have as u64;
267 used = 0;
268 }
269 let a = stream.total_in();
270 let b = stream.total_out();
271 let status = stream
272 .decompress(&buffer[used..have], &mut plain[..], InflateFlush::NoFlush)
273 .map_err(|_| ErrorCode::Integrity)?;
274 used += (stream.total_in() - a) as usize;
275 let n = (stream.total_out() - b) as usize;
276 total = total
277 .checked_add(n as u64)
278 .filter(|n| *n <= limit)
279 .ok_or(ErrorCode::Limit)?;
280 check.observe(
281 ResourceUsage {
282 actual_bytes: Some(base.checked_add(total).ok_or(ErrorCode::Limit)?),
283 compressed_bytes: Some(length),
284 ratio_output_bytes: Some(total),
285 ..ResourceUsage::default()
286 },
287 Some(output),
288 )?;
289 if n != 0 {
290 check.activity()?;
291 }
292 crc = crc32(crc, &plain[..n]);
293 crate::space::ensure(output, n as u64)?;
294 io(output.write_all(&plain[..n]))?;
295 if status == Status::StreamEnd {
296 break;
297 }
298 if a == stream.total_in() && b == stream.total_out() {
299 return Err(ErrorCode::Integrity);
300 }
301 }
302 if remaining == 0 && used == have {
303 break;
304 }
305 if !gzip {
306 return Err(ErrorCode::Integrity);
307 }
308 }
309 Ok((total, crc))
310}
311
312struct Packed {
313 offset: u64,
314 size: u64,
315 method: u16,
316 crc: Option<u32>,
317 flags: u16,
318 verifier: u8,
319 aes: bool,
320}
321
322fn extra(bytes: &[u8]) -> Result<(Option<archive::AesExtra>, Option<Vec<u8>>)> {
323 let mut at = 0;
324 let mut aes = Vec::new();
325 let mut large = None;
326 while at < bytes.len() {
327 if bytes.len() - at < 4 {
328 return Err(ErrorCode::Integrity);
329 }
330 let tag = u16at(bytes, at);
331 let len = u16at(bytes, at + 2) as usize;
332 let end = at + 4 + len;
333 if end > bytes.len() {
334 return Err(ErrorCode::Integrity);
335 }
336 if tag == 1 {
337 if large.is_some() {
338 return Err(ErrorCode::Integrity);
339 }
340 large = Some(bytes[at + 4..end].to_vec());
341 } else {
342 aes.extend_from_slice(&bytes[at..end]);
343 }
344 at = end;
345 }
346 Ok((archive::aes_extra(&aes)?, large))
347}
348fn large_value(value: u32, extra: &mut &[u8]) -> Result<u64> {
349 if value != u32::MAX {
350 return Ok(value as u64);
351 }
352 if extra.len() < 8 {
353 return Err(ErrorCode::Integrity);
354 }
355 let result = u64at(extra, 0);
356 *extra = &extra[8..];
357 Ok(result)
358}
359fn expanded(value: u64, maximum: u64, large: u64) -> Result<u64> {
360 if value == maximum || value == large {
361 Ok(large)
362 } else {
363 Err(ErrorCode::Integrity)
364 }
365}
366fn disk_start(value: u16, extra: &mut &[u8]) -> Result<u32> {
367 if value != u16::MAX {
368 return Ok(value as u32);
369 }
370 if extra.len() < 4 {
371 return Err(ErrorCode::Integrity);
372 }
373 let result = u32at(extra, 0);
374 *extra = &extra[4..];
375 Ok(result)
376}
377fn local_sizes(size: u32, compressed: u32, extra: Option<&[u8]>) -> Result<(u64, u64)> {
378 if let Some(extra) = extra {
379 // 로컬 ZIP64 추가 필드에는 두 크기가 함께 들어감.
380 if extra.len() < 16 {
381 return Err(ErrorCode::Integrity);
382 }
383 Ok((
384 expanded(size as u64, u32::MAX as u64, u64at(extra, 0))?,
385 expanded(compressed as u64, u32::MAX as u64, u64at(extra, 8))?,
386 ))
387 } else if size == u32::MAX || compressed == u32::MAX {
388 Err(ErrorCode::Integrity)
389 } else {
390 Ok((size as u64, compressed as u64))
391 }
392}
393fn descriptor_size(
394 bytes: &[u8],
395 crc: u32,
396 compressed: u64,
397 size: u64,
398 wide_required: bool,
399) -> Result<usize> {
400 // 일반 크기 헤더와 64비트 디스크립터를 함께 기록하는 도구도 있음.
401 if bytes.len() >= 20
402 && u32at(bytes, 0) == crc
403 && u64at(bytes, 4) == compressed
404 && u64at(bytes, 12) == size
405 {
406 return Ok(20);
407 }
408 if !wide_required
409 && bytes.len() >= 12
410 && u32at(bytes, 0) == crc
411 && u32at(bytes, 4) as u64 == compressed
412 && u32at(bytes, 8) as u64 == size
413 {
414 return Ok(12);
415 }
416 Err(ErrorCode::Integrity)
417}
418fn zip(
419 source: &mut File,
420 len: u64,
421 limits: Limits,
422 decode: bool,
423 password: Option<&[u8]>,
424 check: &mut impl crate::resources::Monitor,
425) -> Result<Catalog> {
426 if len < 22 {
427 return Err(ErrorCode::Integrity);
428 }
429 let tail_at = len.saturating_sub(65557);
430 let tail = bytes(source, tail_at, (len - tail_at) as usize)?;
431 let end = (0..=tail.len() - 22)
432 .rev()
433 .find(|&i| {
434 &tail[i..i + 4] == b"PK\x05\x06" && i + 22 + u16at(&tail, i + 20) as usize == tail.len()
435 })
436 .ok_or(ErrorCode::Integrity)?;
437 let h = &tail[end..];
438 let mut disk = u16at(h, 4) as u64;
439 let mut central_disk = u16at(h, 6) as u64;
440 let mut entries_on_disk = u16at(h, 8) as u64;
441 let mut count = u16at(h, 10) as u64;
442 let mut central_size = u32at(h, 12) as u64;
443 let mut central = u32at(h, 16) as u64;
444 let mut central_end = tail_at + end as u64;
445 let required_zip64 = [disk, central_disk, entries_on_disk, count].contains(&(u16::MAX as u64))
446 || central_size == u32::MAX as u64
447 || central == u32::MAX as u64;
448 let locator = if central_end >= 20 {
449 bytes(source, central_end - 20, 20)?
450 } else {
451 Vec::new()
452 };
453 // 중앙 디렉터리 주석의 동일 서명을 locator로 오인하지 않음
454 let has_locator =
455 locator.starts_with(b"PK\x06\x07") && add(central, central_size)? != central_end;
456 if required_zip64 || has_locator {
457 if locator.len() != 20 {
458 return Err(ErrorCode::Integrity);
459 }
460 if &locator[..4] != b"PK\x06\x07" || u32at(&locator, 4) != 0 || u32at(&locator, 16) != 1 {
461 return Err(ErrorCode::UnsupportedFeature);
462 }
463 let offset = u64at(&locator, 8);
464 if add(offset, 56)? > central_end - 20 {
465 return Err(ErrorCode::Integrity);
466 }
467 let large = bytes(source, offset, 56)?;
468 if &large[..4] != b"PK\x06\x06"
469 || u64at(&large, 4) < 44
470 || add(offset, add(12, u64at(&large, 4))?)? != central_end - 20
471 {
472 return Err(ErrorCode::Integrity);
473 }
474 // 각 필드의 확장값을 해석한 뒤 단일 디스크 조건을 검사함.
475 disk = expanded(disk, u16::MAX as u64, u32at(&large, 16) as u64)?;
476 central_disk = expanded(central_disk, u16::MAX as u64, u32at(&large, 20) as u64)?;
477 entries_on_disk = expanded(entries_on_disk, u16::MAX as u64, u64at(&large, 24))?;
478 count = expanded(count, u16::MAX as u64, u64at(&large, 32))?;
479 central_size = expanded(central_size, u32::MAX as u64, u64at(&large, 40))?;
480 central = expanded(central, u32::MAX as u64, u64at(&large, 48))?;
481 central_end = offset;
482 }
483 if disk != 0 || central_disk != 0 || entries_on_disk != count {
484 return Err(ErrorCode::UnsupportedFeature);
485 }
486 if count > limits.entries as u64 {
487 return Err(ErrorCode::Limit);
488 }
489 check.observe(
490 ResourceUsage {
491 estimated_entries: Some(count as u32),
492 ..ResourceUsage::default()
493 },
494 Some(source),
495 )?;
496 if add(central, central_size)? != central_end {
497 return Err(ErrorCode::Integrity);
498 }
499 let mut cursor = central;
500 let mut total = 0u64;
501 let mut metadata = MetadataBudget::default();
502 let mut members = Vec::new();
503 let mut packed = Vec::new();
504 let mut spans = Vec::new();
505 for id in 0..count {
506 check.check()?;
507 if add(cursor, 46)? > central_end {
508 return Err(ErrorCode::Integrity);
509 }
510 let h = bytes(source, cursor, 46)?;
511 if &h[..4] != b"PK\x01\x02" {
512 return Err(ErrorCode::Integrity);
513 }
514 let flags = u16at(&h, 8);
515 let method = u16at(&h, 10);
516 if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) {
517 return Err(ErrorCode::UnsupportedFeature);
518 }
519 let crc = u32at(&h, 16);
520 let (nn, ne, nc) = (
521 u16at(&h, 28) as u64,
522 u16at(&h, 30) as u64,
523 u16at(&h, 32) as u64,
524 );
525 let next = add(cursor, 46 + nn + ne + nc)?;
526 if next > central_end {
527 return Err(ErrorCode::Integrity);
528 }
529 if nn > 4096 {
530 return Err(ErrorCode::UnsafePath);
531 }
532 let raw = bytes(source, cursor + 46, nn as usize)?;
533 let central_extra = bytes(source, cursor + 46 + nn, ne as usize)?;
534 let (aes, large) = extra(&central_extra)?;
535 let name = archive::zip_name(&raw, flags, &central_extra)?;
536 let name = name.as_str();
537 let mut large = large.as_deref().unwrap_or(&[]);
538 let size = large_value(u32at(&h, 24), &mut large)?;
539 let compressed = large_value(u32at(&h, 20), &mut large)?;
540 let local = large_value(u32at(&h, 42), &mut large)?;
541 if disk_start(u16at(&h, 34), &mut large)? != 0 {
542 return Err(ErrorCode::UnsupportedFeature);
543 }
544 let encrypted = flags & 1 != 0;
545 if (method == 99) != aes.is_some()
546 || (method == 99 && !encrypted)
547 || (aes.is_some_and(|a| a.version == 2) && crc != 0)
548 {
549 return Err(ErrorCode::Integrity);
550 }
551 let overhead = if !encrypted {
552 0
553 } else if aes.is_some() {
554 28
555 } else {
556 12
557 };
558 compressed
559 .checked_sub(overhead)
560 .ok_or(ErrorCode::Integrity)?;
561 total = total
562 .checked_add(size)
563 .filter(|n| *n <= limits.output)
564 .ok_or(ErrorCode::Limit)?;
565 check.observe(
566 ResourceUsage {
567 estimated_bytes: Some(total),
568 estimated_entries: Some(count as u32),
569 compressed_bytes: Some(compressed - overhead),
570 ratio_output_bytes: Some(size),
571 ..ResourceUsage::default()
572 },
573 Some(source),
574 )?;
575 check.activity()?;
576 let mode = u32at(&h, 38) >> 16;
577 let kind = match mode & 0xf000 {
578 0xa000 => EntryKind::Link,
579 0x4000 => EntryKind::Directory,
580 0 | 0x8000 => {
581 if name.ends_with('/') {
582 EntryKind::Directory
583 } else {
584 EntryKind::File
585 }
586 }
587 _ => EntryKind::Other,
588 };
589 if kind == EntryKind::Directory && size != 0 {
590 return Err(ErrorCode::Integrity);
591 }
592 metadata.charge(name)?;
593 let name = archive::valid_name(name, kind == EntryKind::Directory)?;
594 if add(local, 30)? > central {
595 return Err(ErrorCode::Integrity);
596 }
597 let lh = bytes(source, local, 30)?;
598 if &lh[..4] != b"PK\x03\x04"
599 || u16at(&lh, 6) != flags
600 || u16at(&lh, 8) != method
601 || u16at(&lh, 10) != u16at(&h, 12)
602 {
603 return Err(ErrorCode::Integrity);
604 }
605 let (ln, le) = (u16at(&lh, 26) as u64, u16at(&lh, 28) as u64);
606 let start = add(local, 30 + ln + le)?;
607 if start > central || ln != nn {
608 return Err(ErrorCode::Integrity);
609 }
610 if bytes(source, local + 30, ln as usize)? != raw {
611 return Err(ErrorCode::Integrity);
612 }
613 let (local_aes, local_large) = extra(&bytes(source, local + 30 + ln, le as usize)?)?;
614 if local_aes != aes || local_large.as_ref().is_some_and(|values| values.len() < 16) {
615 return Err(ErrorCode::Integrity);
616 }
617 let size_zip64 = u32at(&h, 20) == u32::MAX
618 || u32at(&h, 24) == u32::MAX
619 || u32at(&lh, 18) == u32::MAX
620 || u32at(&lh, 22) == u32::MAX
621 || local_large.is_some();
622 if flags & 8 == 0 {
623 let (local_size, local_compressed) =
624 local_sizes(u32at(&lh, 22), u32at(&lh, 18), local_large.as_deref())?;
625 if u32at(&lh, 14) != crc || local_size != size || local_compressed != compressed {
626 return Err(ErrorCode::Integrity);
627 }
628 }
629 let mut stop = add(start, compressed)?;
630 if stop > central {
631 return Err(ErrorCode::Integrity);
632 }
633 if flags & 8 != 0 {
634 let descriptor_len = if size_zip64 { 20 } else { 12 };
635 if add(stop, descriptor_len)? > central {
636 return Err(ErrorCode::Integrity);
637 }
638 let signature = bytes(source, stop, 4)?;
639 if signature == b"PK\x07\x08" {
640 stop = add(stop, 4)?;
641 }
642 let d = bytes(source, stop, (central - stop).min(20) as usize)?;
643 let descriptor_len = descriptor_size(&d, crc, compressed, size, size_zip64)?;
644 stop = add(stop, descriptor_len as u64)?;
645 }
646 spans.push((local, stop));
647 packed.push(Packed {
648 offset: start,
649 size: compressed,
650 method: aes.map_or(method, |a| a.method),
651 crc: if aes.is_some_and(|a| a.version == 2) {
652 None
653 } else {
654 Some(crc)
655 },
656 flags,
657 verifier: if flags & 8 != 0 {
658 (u16at(&h, 12) >> 8) as u8
659 } else {
660 (crc >> 24) as u8
661 },
662 aes: aes.is_some(),
663 });
664 members.push(Member {
665 entry: Entry {
666 entry_id: id as u32,
667 name,
668 kind,
669 size,
670 compressed_size: compressed,
671 encrypted,
672 },
673 data: Vec::new(),
674 });
675 cursor = next;
676 }
677 if cursor != central_end {
678 return Err(ErrorCode::Integrity);
679 }
680 spans.sort_unstable();
681 let mut next = 0;
682 for (a, b) in spans {
683 if a != next {
684 return Err(ErrorCode::Integrity);
685 }
686 next = b;
687 }
688 if next != central {
689 return Err(ErrorCode::Integrity);
690 }
691 archive::validate_members(&members)?;
692 let mut data = spool::temporary()?;
693 if decode {
694 crate::space::ensure(&data, total)?;
695 }
696 let mut offsets = Vec::new();
697 for (member, packed) in members.iter().zip(packed) {
698 check.check()?;
699 offsets.push(io(data.stream_position())?);
700 if !decode {
701 continue;
702 }
703 let (decoder, start, length) = if packed.flags & 1 != 0 {
704 crypto::Decryptor::prepare(
705 source,
706 packed.offset,
707 packed.size,
708 password.ok_or(ErrorCode::WrongPassword)?,
709 packed.aes,
710 packed.verifier,
711 check,
712 )?
713 } else {
714 (crypto::Decryptor::Plain, packed.offset, packed.size)
715 };
716 io(source.seek(SeekFrom::Start(start)))?;
717 let mut reader = Decoded {
718 reader: source.take(length),
719 decoder,
720 };
721 let (size, crc) = if packed.method == 8 {
722 inflate(
723 &mut reader,
724 length,
725 false,
726 member.entry.size,
727 &mut data,
728 check,
729 )?
730 } else {
731 let mut buffer = Zeroizing::new([0; CHUNK]);
732 let mut total = 0u64;
733 let mut crc = 0;
734 loop {
735 check.check()?;
736 let n = io(reader.read(&mut buffer[..]))?;
737 if n == 0 {
738 break;
739 }
740 total = total
741 .checked_add(n as u64)
742 .filter(|n| *n <= member.entry.size)
743 .ok_or(ErrorCode::Integrity)?;
744 check.activity()?;
745 crate::space::ensure(&data, n as u64)?;
746 crc = crc32(crc, &buffer[..n]);
747 io(data.write_all(&buffer[..n]))?;
748 }
749 (total, crc)
750 };
751 if size != member.entry.size || packed.crc.is_some_and(|c| c != crc) {
752 return Err(ErrorCode::Integrity);
753 }
754 }
755 Ok(Catalog {
756 format: Format::Zip,
757 members,
758 offsets,
759 data,
760 })
761}
762struct Decoded<R> {
763 reader: R,
764 decoder: crypto::Decryptor,
765}
766impl<R: Read> Read for Decoded<R> {
767 fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> {
768 let n = self.reader.read(output)?;
769 self.decoder.apply(&mut output[..n]);
770 Ok(n)
771 }
772}
773
774#[cfg(test)]
775#[path = "../../../tests/rust-archive-worker/streaming_bounds.rs"]
776mod bounds;