team-ljyzipelo

공개
766줄26 KB
1use crate::{
2 archive::{self, Member, MetadataBudget},
3 create_sources::Input,
4 filesystem,
5 protocol::*,
6 resources::{Monitor, completed},
7 spool,
8};
9use sha2::{Digest, Sha256};
10use std::{
11 fs::File,
12 io::{Read, Seek, SeekFrom, Write},
13 path::{Path, PathBuf},
14 time::SystemTime,
15};
16use zlib_rs::{Inflate, InflateFlush, Status, crc32::crc32};
17
18type Result<T> = std::result::Result<T, ErrorCode>;
19const INPUT_CAP: u64 = 4 * 1024 * 1024 * 1024;
20fn io<T>(value: std::io::Result<T>) -> Result<T> {
21 value.map_err(crate::space::io_error)
22}
23fn add(a: u64, b: u64) -> Result<u64> {
24 a.checked_add(b).ok_or(ErrorCode::Integrity)
25}
26fn u16at(b: &[u8], i: usize) -> u16 {
27 u16::from_le_bytes(b[i..i + 2].try_into().unwrap())
28}
29fn u32at(b: &[u8], i: usize) -> u32 {
30 u32::from_le_bytes(b[i..i + 4].try_into().unwrap())
31}
32fn bytes(source: &mut File, offset: u64, size: usize, end: u64) -> Result<Vec<u8>> {
33 if add(offset, size as u64)? > end {
34 return Err(ErrorCode::Integrity);
35 }
36 io(source.seek(SeekFrom::Start(offset)))?;
37 let mut data = vec![0; size];
38 io(source.read_exact(&mut data))?;
39 Ok(data)
40}
41fn extra(data: &[u8]) -> Result<()> {
42 let mut at = 0;
43 while at < data.len() {
44 if data.len() - at < 4 {
45 return Err(ErrorCode::Integrity);
46 }
47 let tag = u16at(data, at);
48 let size = u16at(data, at + 2) as usize;
49 if matches!(tag, 1 | 0x0017 | 0x0018) {
50 return Err(ErrorCode::UnsupportedFeature);
51 }
52 at = at
53 .checked_add(4 + size)
54 .filter(|n| *n <= data.len())
55 .ok_or(ErrorCode::Integrity)?;
56 }
57 Ok(())
58}
59struct Candidate {
60 finding: RecoveryEntry,
61 start: u64,
62 stop: u64,
63 packed: u64,
64 crc: u32,
65 method: u16,
66 supported: bool,
67 boundary: bool,
68 repaired: bool,
69}
70fn declared(size: u32, packed: u32) -> Result<(u64, u64)> {
71 if size == u32::MAX || packed == u32::MAX {
72 return Err(ErrorCode::UnsupportedFeature);
73 }
74 Ok((u64::from(size), u64::from(packed)))
75}
76fn named(raw: &[u8], flags: u16, ext: &[u8], kind: EntryKind) -> Result<String> {
77 if !matches!(kind, EntryKind::File | EntryKind::Directory) {
78 return Err(ErrorCode::UnsafePath);
79 }
80 let name = archive::zip_name(raw, flags, ext)?;
81 archive::valid_name(&name, kind == EntryKind::Directory)
82}
83fn candidate(
84 offset: u64,
85 name: String,
86 kind: EntryKind,
87 size: u64,
88 packed: u64,
89 crc: u32,
90 method: u16,
91 flags: u16,
92) -> Candidate {
93 Candidate {
94 finding: RecoveryEntry {
95 candidate_id: 0,
96 source_offset: offset,
97 name: Some(name),
98 kind: Some(kind),
99 status: RecoveryStatus::Unverified,
100 reason: RecoveryReason::BoundaryUnknown,
101 declared_size: Some(size),
102 verified_size: None,
103 sha256: None,
104 },
105 start: 0,
106 stop: offset,
107 packed,
108 crc,
109 method,
110 supported: flags & !0x080e == 0 && matches!(method, 0 | 8),
111 boundary: false,
112 repaired: false,
113 }
114}
115fn charge(
116 metadata: &mut MetadataBudget,
117 name_len: usize,
118 extra_len: usize,
119 check: &mut impl Monitor,
120) -> Result<()> {
121 if name_len > 4096 {
122 return Err(ErrorCode::UnsafePath);
123 }
124 metadata.charge_bytes(
125 name_len
126 .checked_mul(8)
127 .and_then(|n| n.checked_add(extra_len + 1024))
128 .ok_or(ErrorCode::Limit)?,
129 check.metadata_limits(),
130 )
131}
132fn central(
133 source: &mut File,
134 len: u64,
135 limits: Limits,
136 check: &mut impl Monitor,
137) -> Result<Option<(Vec<Candidate>, bool)>> {
138 if len < 22 {
139 return Ok(None);
140 }
141 let mut metadata = MetadataBudget::default();
142 metadata.charge_bytes(len.min(65557) as usize, check.metadata_limits())?;
143 let tail_at = len.saturating_sub(65557);
144 let tail = bytes(source, tail_at, (len - tail_at) as usize, len)?;
145 let Some(end) = (0..=tail.len() - 22).rev().find(|&i| {
146 &tail[i..i + 4] == b"PK\x05\x06" && i + 22 + u16at(&tail, i + 20) as usize == tail.len()
147 }) else {
148 return Ok(None);
149 };
150 let h = &tail[end..];
151 let count = u16at(h, 10) as u32;
152 if u16at(h, 4) != 0
153 || u16at(h, 6) != 0
154 || u16at(h, 8) as u32 != count
155 || count == u16::MAX as u32
156 || u32at(h, 12) == u32::MAX
157 || u32at(h, 16) == u32::MAX
158 {
159 return Err(ErrorCode::UnsupportedFeature);
160 }
161 let cd = u32at(h, 16) as u64;
162 let cd_end = tail_at + end as u64;
163 let declared_cd_end = add(cd, u32at(h, 12) as u64)?;
164 // 중앙 목록의 주석을 ZIP64 locator로 오인하지 않음.
165 if cd_end >= 20
166 && declared_cd_end <= cd_end - 20
167 && bytes(source, cd_end - 20, 4, len)? == b"PK\x06\x07"
168 {
169 return Err(ErrorCode::UnsupportedFeature);
170 }
171 if declared_cd_end != cd_end {
172 return Err(ErrorCode::Integrity);
173 }
174 if count > limits.entries {
175 return Err(ErrorCode::Limit);
176 }
177 check.observe(
178 ResourceUsage {
179 estimated_entries: Some(count),
180 ..ResourceUsage::default()
181 },
182 Some(source),
183 )?;
184 let mut items = Vec::new();
185 let mut at = cd;
186 for _ in 0..count {
187 check.check()?;
188 let h = bytes(source, at, 46, cd_end)?;
189 if &h[..4] != b"PK\x01\x02" {
190 return Err(ErrorCode::Integrity);
191 }
192 if u16at(&h, 34) != 0 || u32at(&h, 42) == u32::MAX {
193 return Err(ErrorCode::UnsupportedFeature);
194 }
195 let flags = u16at(&h, 8);
196 if flags & 0x2040 != 0 {
197 return Err(ErrorCode::UnsupportedFeature);
198 }
199 let nn = u16at(&h, 28) as usize;
200 let ne = u16at(&h, 30) as usize;
201 let next = add(at, 46 + nn as u64 + ne as u64 + u16at(&h, 32) as u64)?;
202 if next > cd_end {
203 return Err(ErrorCode::Integrity);
204 }
205 charge(&mut metadata, nn, ne, check)?;
206 let raw = bytes(source, at + 46, nn, cd_end)?;
207 let ext = bytes(source, at + 46 + nn as u64, ne, cd_end)?;
208 extra(&ext)?;
209 let (size, packed) = declared(u32at(&h, 24), u32at(&h, 20))?;
210 let unix_kind = (u32at(&h, 38) >> 16) & 0xf000;
211 let kind = match unix_kind {
212 0 | 0x8000 => {
213 if raw.ends_with(b"/") {
214 EntryKind::Directory
215 } else {
216 EntryKind::File
217 }
218 }
219 0x4000 => EntryKind::Directory,
220 _ => return Err(ErrorCode::UnsafePath),
221 };
222 let name = named(&raw, flags, &ext, kind)?;
223 metadata.charge_with(&name, check.metadata_limits())?;
224 let offset = u32at(&h, 42) as u64;
225 let mut item = candidate(
226 offset,
227 name,
228 kind,
229 size,
230 packed,
231 u32at(&h, 16),
232 u16at(&h, 10),
233 flags,
234 );
235 if add(offset, 30)? > cd {
236 return Err(ErrorCode::Integrity);
237 }
238 let local = bytes(source, offset, 30, cd)?;
239 declared(u32at(&local, 22), u32at(&local, 18))?;
240 let ln = u16at(&local, 26) as usize;
241 let le = u16at(&local, 28) as usize;
242 charge(&mut metadata, ln, le, check)?;
243 let start = add(offset, 30 + ln as u64 + le as u64)?;
244 if start > cd {
245 return Err(ErrorCode::Integrity);
246 }
247 let local_raw = bytes(source, offset + 30, ln, cd)?;
248 let local_extra = bytes(source, offset + 30 + ln as u64, le, cd)?;
249 extra(&local_extra)?;
250 let mut stop = add(start, packed)?;
251 if stop > cd {
252 return Err(ErrorCode::Integrity);
253 }
254 item.start = start;
255 item.boundary =
256 raw == local_raw && flags == u16at(&local, 6) && item.method == u16at(&local, 8);
257 item.repaired = &local[..4] != b"PK\x03\x04"
258 || (flags & 8 == 0
259 && (u32at(&local, 14) != item.crc
260 || u32at(&local, 18) as u64 != packed
261 || u32at(&local, 22) as u64 != size));
262 if flags & 8 != 0 {
263 let descriptor = bytes(source, stop, 12, cd)?;
264 let skip = if &descriptor[..4] == b"PK\x07\x08" {
265 4
266 } else {
267 0
268 };
269 let d = bytes(source, stop + skip, 12, cd)?;
270 if u32at(&d, 0) != item.crc
271 || u32at(&d, 4) as u64 != packed
272 || u32at(&d, 8) as u64 != size
273 {
274 item.boundary = false;
275 }
276 stop = add(stop, 12 + skip)?;
277 }
278 item.stop = stop;
279 if kind == EntryKind::Directory && size != 0 {
280 item.boundary = false;
281 }
282 items.push(item);
283 at = next;
284 completed(Ok(()), check)?;
285 }
286 if at != cd_end {
287 return Err(ErrorCode::Integrity);
288 }
289 items.sort_by_key(|c| c.finding.source_offset);
290 let mut cursor = 0;
291 let mut complete = true;
292 for c in &items {
293 if c.finding.source_offset < cursor {
294 return Err(ErrorCode::Integrity);
295 }
296 complete &= c.finding.source_offset == cursor && c.boundary;
297 cursor = c.stop;
298 }
299 complete &= cursor == cd;
300 Ok(Some((items, complete)))
301}
302fn local(
303 source: &mut File,
304 len: u64,
305 limits: Limits,
306 check: &mut impl Monitor,
307) -> Result<Vec<Candidate>> {
308 let mut at = 0;
309 let mut items = Vec::new();
310 let mut metadata = MetadataBudget::default();
311 while at < len {
312 check.check()?;
313 if len - at < 30 {
314 break;
315 }
316 let h = bytes(source, at, 30, len)?;
317 if &h[..4] != b"PK\x03\x04" {
318 if at == 0
319 && (h.starts_with(b"MZ")
320 || h.starts_with(b"PK\x07\x08")
321 || h.starts_with(b"PK\x06"))
322 {
323 return Err(ErrorCode::UnsupportedFeature);
324 }
325 break;
326 }
327 let count = u32::try_from(items.len() + 1).map_err(|_| ErrorCode::Limit)?;
328 if count > limits.entries {
329 return Err(ErrorCode::Limit);
330 }
331 check.observe(
332 ResourceUsage {
333 actual_entries: Some(count),
334 ..ResourceUsage::default()
335 },
336 Some(source),
337 )?;
338 let flags = u16at(&h, 6);
339 if flags & 0x2040 != 0 {
340 return Err(ErrorCode::UnsupportedFeature);
341 }
342 let nn = u16at(&h, 26) as usize;
343 let ne = u16at(&h, 28) as usize;
344 charge(&mut metadata, nn, ne, check)?;
345 let start = add(at, 30 + nn as u64 + ne as u64)?;
346 if start > len {
347 break;
348 }
349 let raw = bytes(source, at + 30, nn, len)?;
350 let ext = bytes(source, at + 30 + nn as u64, ne, len)?;
351 extra(&ext)?;
352 let kind = if raw.ends_with(b"/") {
353 EntryKind::Directory
354 } else {
355 EntryKind::File
356 };
357 let name = named(&raw, flags, &ext, kind)?;
358 metadata.charge_with(&name, check.metadata_limits())?;
359 let (size, packed) = declared(u32at(&h, 22), u32at(&h, 18))?;
360 let mut c = candidate(
361 at,
362 name,
363 kind,
364 size,
365 packed,
366 u32at(&h, 14),
367 u16at(&h, 8),
368 flags,
369 );
370 c.start = start;
371 c.stop = add(start, packed)?;
372 if flags & 8 != 0 {
373 c.finding.declared_size = None;
374 items.push(c);
375 break;
376 }
377 c.boundary = true;
378 let next = c.stop;
379 items.push(c);
380 if next > len {
381 break;
382 }
383 at = next;
384 completed(Ok(()), check)?;
385 }
386 Ok(items)
387}
388
389pub(crate) struct Recovery {
390 source: Input,
391 path: PathBuf,
392 modified: Option<SystemTime>,
393 pub snapshot: spool::Snapshot,
394 pub findings: Vec<RecoveryEntry>,
395 pub summary: RecoveryEnd,
396 pub data: File,
397 pub offsets: Vec<u64>,
398}
399impl Recovery {
400 pub fn open(path: &Path, limits: Limits, check: &mut impl Monitor) -> Result<Self> {
401 let mut source = completed(Input::open(path), check)?;
402 let meta = io(source.file.metadata())?;
403 if !meta.is_file() {
404 return Err(ErrorCode::InvalidRequest);
405 }
406 if meta.len() > INPUT_CAP {
407 return Err(ErrorCode::UnsupportedFeature);
408 }
409 let prefix = bytes(&mut source.file, 0, meta.len().min(4) as usize, meta.len())?;
410 if prefix.starts_with(b"MZ")
411 || prefix.starts_with(b"PK\x07\x08")
412 || prefix.starts_with(b"PK\x06")
413 {
414 return Err(ErrorCode::UnsupportedFeature);
415 }
416 let mut snapshot =
417 spool::Snapshot::capture(&mut source.file, limits.input.min(INPUT_CAP), check)?;
418 let named = completed(Input::open(path), check)?;
419 if filesystem::object(&named.file)? != snapshot.object {
420 return Err(ErrorCode::SourceChanged);
421 }
422 let discovered = central(&mut snapshot.file, snapshot.len, limits, check);
423 let (mut candidates, mode, known) = match discovered {
424 Ok(Some((items, complete))) => (items, RecoveryMode::CentralDirectory, complete),
425 Ok(None) | Err(ErrorCode::Integrity) => (
426 local(&mut snapshot.file, snapshot.len, limits, check)?,
427 RecoveryMode::LocalChain,
428 false,
429 ),
430 Err(error) => return Err(error),
431 };
432 let mut names = Vec::new();
433 let mut budget = MetadataBudget::default();
434 for (id, c) in candidates.iter_mut().enumerate() {
435 c.finding.candidate_id = id as u32;
436 let name = c.finding.name.as_ref().ok_or(ErrorCode::Internal)?;
437 budget.charge_with(name, check.metadata_limits())?;
438 names.push(Member {
439 entry: Entry {
440 entry_id: id as u32,
441 name: name.clone(),
442 kind: c.finding.kind.unwrap(),
443 size: c.finding.declared_size.unwrap_or(0),
444 compressed_size: c.packed,
445 encrypted: false,
446 },
447 data: Vec::new(),
448 });
449 }
450 archive::validate_members_with(&names, check)?;
451 drop(names);
452 let mut data = spool::temporary()?;
453 let mut findings = Vec::new();
454 let mut offsets = Vec::new();
455 let mut used = 0u64;
456 let mut verified = 0;
457 let mut lost = 0;
458 let mut unverified = 0;
459 let mut repaired = false;
460 for c in candidates {
461 check.check()?;
462 let base = io(data.stream_position())?;
463 offsets.push(base);
464 let mut finding = c.finding;
465 if !c.boundary {
466 finding.reason = RecoveryReason::BoundaryUnknown;
467 } else if !c.supported {
468 finding.reason = RecoveryReason::UnsupportedFeature;
469 } else if c.stop > snapshot.len {
470 finding.status = RecoveryStatus::Lost;
471 finding.reason = RecoveryReason::Truncated;
472 } else {
473 let size = finding.declared_size.ok_or(ErrorCode::Internal)?;
474 if used.checked_add(size).is_none_or(|n| n > limits.output) {
475 return Err(ErrorCode::Limit);
476 }
477 check.observe(
478 ResourceUsage {
479 estimated_bytes: Some(used + size),
480 actual_entries: Some(finding.candidate_id + 1),
481 compressed_bytes: Some(c.packed),
482 ratio_output_bytes: Some(size),
483 ..ResourceUsage::default()
484 },
485 Some(&data),
486 )?;
487 io(snapshot.file.seek(SeekFrom::Start(c.start)))?;
488 let decoded = decode(
489 &mut snapshot.file,
490 c.packed,
491 c.method,
492 size,
493 &mut data,
494 &mut used,
495 limits,
496 check,
497 );
498 match decoded {
499 Ok((length, crc, hash))
500 if length == size
501 && crc == c.crc
502 && (finding.kind != Some(EntryKind::Directory) || size == 0) =>
503 {
504 finding.status = RecoveryStatus::Verified;
505 finding.reason = if c.repaired {
506 RecoveryReason::HeaderRebuilt
507 } else if mode == RecoveryMode::LocalChain {
508 RecoveryReason::MetadataMissing
509 } else {
510 RecoveryReason::None
511 };
512 finding.verified_size = Some(size);
513 finding.sha256 = if finding.kind == Some(EntryKind::File) {
514 Some(hash)
515 } else {
516 None
517 };
518 }
519 Ok((length, _, _)) => {
520 finding.status = RecoveryStatus::Lost;
521 finding.reason = if length == size {
522 RecoveryReason::CrcMismatch
523 } else {
524 RecoveryReason::DecodeFailure
525 };
526 }
527 Err(ErrorCode::Integrity) => {
528 finding.status = RecoveryStatus::Lost;
529 finding.reason = RecoveryReason::DecodeFailure;
530 }
531 Err(error) => return Err(error),
532 }
533 if finding.status != RecoveryStatus::Verified {
534 io(data.set_len(base))?;
535 io(data.seek(SeekFrom::Start(base)))?;
536 }
537 }
538 repaired |= c.repaired;
539 match finding.status {
540 RecoveryStatus::Verified => verified += 1,
541 RecoveryStatus::Lost => lost += 1,
542 RecoveryStatus::Unverified => unverified += 1,
543 }
544 check.progress(Stage::Verify, used, None, finding.candidate_id + 1)?;
545 findings.push(finding);
546 }
547 if known && verified as usize == findings.len() && !repaired {
548 return Err(ErrorCode::InvalidRequest);
549 }
550 let summary = RecoveryEnd {
551 mode,
552 source_bytes: snapshot.len,
553 source_sha256: snapshot.hash,
554 known_entries: if known {
555 Some(findings.len() as u32)
556 } else {
557 None
558 },
559 verified_entries: verified,
560 lost_entries: lost,
561 unverified_entries: unverified,
562 unknown_loss: !known,
563 };
564 Ok(Self {
565 source,
566 path: path.to_owned(),
567 modified: meta.modified().ok(),
568 snapshot,
569 findings,
570 summary,
571 data,
572 offsets,
573 })
574 }
575 pub fn build(&mut self, limits: Limits, check: &mut impl Monitor) -> Result<(File, u64)> {
576 let (mut output, len) =
577 crate::create::recovered_zip(&self.findings, &self.offsets, &mut self.data, check)?;
578 let mut replay = Replay(check);
579 let mut catalog =
580 crate::streaming::Catalog::open(&mut output, len, limits, true, None, &mut replay)?;
581 if catalog.format != Format::Zip
582 || catalog.members.len() != self.summary.verified_entries as usize
583 {
584 return Err(ErrorCode::Integrity);
585 }
586 for ((member, offset), finding) in catalog.members.iter().zip(&catalog.offsets).zip(
587 self.findings
588 .iter()
589 .filter(|e| e.status == RecoveryStatus::Verified),
590 ) {
591 if Some(&member.entry.name) != finding.name.as_ref()
592 || Some(member.entry.kind) != finding.kind
593 || Some(member.entry.size) != finding.verified_size
594 {
595 return Err(ErrorCode::Integrity);
596 }
597 if member.entry.kind == EntryKind::File {
598 io(catalog.data.seek(SeekFrom::Start(*offset)))?;
599 let mut input = (&mut catalog.data).take(member.entry.size);
600 let mut hash = Sha256::new();
601 let mut buffer = [0; 65536];
602 loop {
603 replay.check()?;
604 let n = completed(io(input.read(&mut buffer)), &mut replay)?;
605 if n == 0 {
606 break;
607 }
608 hash.update(&buffer[..n]);
609 }
610 if input.limit() != 0 || Some(<[u8; 32]>::from(hash.finalize())) != finding.sha256 {
611 return Err(ErrorCode::Integrity);
612 }
613 }
614 }
615 io(output.rewind())?;
616 Ok((output, len))
617 }
618 pub fn verify_source(&mut self, check: &mut impl Monitor) -> Result<()> {
619 let mut named = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
620 let before = io(named.file.metadata())?;
621 let pinned = io(self.source.file.metadata())?;
622 if filesystem::object(&named.file)? != self.snapshot.object
623 || before.len() != self.snapshot.len
624 || before.modified().ok() != self.modified
625 || pinned.len() != self.snapshot.len
626 || pinned.modified().ok() != self.modified
627 {
628 return Err(ErrorCode::SourceChanged);
629 }
630 let mut hash = Sha256::new();
631 let mut buffer = [0; 65536];
632 let mut length = 0;
633 loop {
634 check.check()?;
635 let n = completed(io(named.file.read(&mut buffer)), check)?;
636 if n == 0 {
637 break;
638 }
639 length = add(length, n as u64)?;
640 hash.update(&buffer[..n]);
641 check.progress(
642 Stage::Verify,
643 length,
644 Some(self.snapshot.len),
645 self.findings.len() as u32,
646 )?;
647 }
648 let after = io(named.file.metadata())?;
649 let current = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
650 if length != self.snapshot.len
651 || <[u8; 32]>::from(hash.finalize()) != self.snapshot.hash
652 || after.len() != self.snapshot.len
653 || after.modified().ok() != self.modified
654 || filesystem::object(&current.file)? != self.snapshot.object
655 {
656 return Err(ErrorCode::SourceChanged);
657 }
658 Ok(())
659 }
660}
661fn decode(
662 input: &mut File,
663 length: u64,
664 method: u16,
665 declared: u64,
666 output: &mut File,
667 used: &mut u64,
668 limits: Limits,
669 check: &mut impl Monitor,
670) -> Result<(u64, u32, [u8; 32])> {
671 let mut input = input.take(length);
672 let mut stream = Inflate::new(false, 15);
673 let mut buffer = [0; 65536];
674 let mut plain = [0; 65536];
675 let mut have = 0;
676 let mut at = 0;
677 let mut total = 0u64;
678 let mut crc = 0;
679 let mut hash = Sha256::new();
680 loop {
681 check.check()?;
682 if at == have && input.limit() != 0 {
683 have = completed(io(input.read(&mut buffer)), check)?;
684 at = 0;
685 if have == 0 {
686 return Err(ErrorCode::Integrity);
687 }
688 }
689 let (n, status, consumed, corrupt) = if method == 0 {
690 plain[..have].copy_from_slice(&buffer[..have]);
691 (
692 have,
693 if input.limit() == 0 {
694 Status::StreamEnd
695 } else {
696 Status::Ok
697 },
698 have,
699 false,
700 )
701 } else {
702 let before_in = stream.total_in();
703 let before_out = stream.total_out();
704 let status = stream.decompress(&buffer[at..have], &mut plain, InflateFlush::NoFlush);
705 let corrupt = status.is_err();
706 (
707 (stream.total_out() - before_out) as usize,
708 status.unwrap_or(Status::Ok),
709 (stream.total_in() - before_in) as usize,
710 corrupt,
711 )
712 };
713 at += consumed;
714 total = total.checked_add(n as u64).ok_or(ErrorCode::Limit)?;
715 *used = used
716 .checked_add(n as u64)
717 .filter(|n| *n <= limits.output)
718 .ok_or(ErrorCode::Limit)?;
719 check.observe(
720 ResourceUsage {
721 actual_bytes: Some(*used),
722 compressed_bytes: Some(length),
723 ratio_output_bytes: Some(total),
724 ..ResourceUsage::default()
725 },
726 Some(output),
727 )?;
728 if corrupt || total > declared {
729 return Err(ErrorCode::Integrity);
730 }
731 crc = crc32(crc, &plain[..n]);
732 hash.update(&plain[..n]);
733 crate::space::ensure(output, n as u64)?;
734 completed(io(output.write_all(&plain[..n])), check)?;
735 if status == Status::StreamEnd {
736 if input.limit() != 0 || at != have {
737 return Err(ErrorCode::Integrity);
738 }
739 break;
740 }
741 if n == 0 && consumed == 0 {
742 return Err(ErrorCode::Integrity);
743 }
744 }
745 Ok((total, crc, hash.finalize().into()))
746}
747
748struct Replay<'a, M>(&'a mut M);
749impl<M: Monitor> Monitor for Replay<'_, M> {
750 fn metadata_limits(&self) -> archive::MetadataLimits {
751 self.0.metadata_limits()
752 }
753 fn check(&mut self) -> Result<()> {
754 self.0.check()
755 }
756 fn activity(&mut self) -> Result<()> {
757 self.0.activity()
758 }
759 fn observe(&mut self, _usage: ResourceUsage, _storage: Option<&File>) -> Result<()> {
760 self.0.check()
761 }
762}
763
764#[cfg(test)]
765#[path = "../../../tests/rust-archive-worker/recovery_checks.rs"]
766mod tests;