team-ljyzipelo

공개
872줄29 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}
132
133fn zip64_bounds(source: &mut File, end: u64) -> Result<Option<(u64, u64)>> {
134 if end < 20 {
135 return Ok(None);
136 }
137 let locator_at = end - 20;
138 let locator = bytes(source, locator_at, 20, end)?;
139 if &locator[..4] != b"PK\x06\x07" || u32at(&locator, 4) != 0 || u32at(&locator, 16) != 1 {
140 return Ok(None);
141 }
142 let record_at = u64::from_le_bytes(locator[8..16].try_into().unwrap());
143 if record_at.checked_add(56).is_none_or(|n| n > locator_at) {
144 return Ok(None);
145 }
146 let record = bytes(source, record_at, 56, locator_at)?;
147 let length = u64::from_le_bytes(record[4..12].try_into().unwrap());
148 if &record[..4] != b"PK\x06\x06"
149 || length < 44
150 || record_at
151 .checked_add(12)
152 .and_then(|n| n.checked_add(length))
153 != Some(locator_at)
154 {
155 return Ok(None);
156 }
157 let size = u64::from_le_bytes(record[40..48].try_into().unwrap());
158 let offset = u64::from_le_bytes(record[48..56].try_into().unwrap());
159 Ok((offset.checked_add(size) == Some(record_at)).then_some((offset, size)))
160}
161
162fn directory_span(
163 source: &mut File,
164 mut at: u64,
165 end: u64,
166 check: &mut impl Monitor,
167) -> Result<bool> {
168 let mut count = 0u32;
169 while at < end {
170 check.check()?;
171 if end - at < 46 {
172 return Ok(false);
173 }
174 let header = bytes(source, at, 46, end)?;
175 if &header[..4] != b"PK\x01\x02" {
176 return Ok(false);
177 }
178 let next = add(
179 at,
180 46 + u16at(&header, 28) as u64 + u16at(&header, 30) as u64 + u16at(&header, 32) as u64,
181 )?;
182 if next > end {
183 return Ok(false);
184 }
185 count += 1;
186 if count > u16::MAX as u32 {
187 return Err(ErrorCode::UnsupportedFeature);
188 }
189 at = next;
190 }
191 Ok(true)
192}
193
194fn end_record(
195 source: &mut File,
196 tail: &[u8],
197 tail_at: u64,
198 check: &mut impl Monitor,
199) -> Result<Option<usize>> {
200 for end in (0..=tail.len() - 22).rev() {
201 if &tail[end..end + 4] != b"PK\x05\x06"
202 || end + 22 + u16at(tail, end + 20) as usize != tail.len()
203 {
204 continue;
205 }
206 check.check()?;
207 let h = &tail[end..];
208 let at = tail_at + end as u64;
209 let mut offset = u32at(h, 16) as u64;
210 let mut size = u32at(h, 12) as u64;
211 let zip64 = offset == u32::MAX as u64 || size == u32::MAX as u64;
212 if zip64 {
213 let Some(bounds) = zip64_bounds(source, at)? else {
214 continue;
215 };
216 (offset, size) = bounds;
217 }
218 let Some(stop) = offset.checked_add(size).filter(|&n| n <= at) else {
219 continue;
220 };
221 if size < 46 || bytes(source, offset, 4, stop)? != b"PK\x01\x02" {
222 continue;
223 }
224 // 주석 안 후보는 중앙 목록 또는 실제 ZIP64 경계와 이어지지 않으면 제외함.
225 if stop != at && !zip64 {
226 let adjacent_locator =
227 at.checked_sub(20) == Some(stop) && bytes(source, stop, 4, at)? == b"PK\x06\x07";
228 if !adjacent_locator && zip64_bounds(source, at)? != Some((offset, size)) {
229 continue;
230 }
231 }
232 if !directory_span(source, offset, stop, check)? {
233 continue;
234 }
235 return Ok(Some(end));
236 }
237 Ok(None)
238}
239
240fn central(
241 source: &mut File,
242 len: u64,
243 limits: Limits,
244 check: &mut impl Monitor,
245) -> Result<Option<(Vec<Candidate>, bool)>> {
246 if len < 22 {
247 return Ok(None);
248 }
249 let mut metadata = MetadataBudget::default();
250 metadata.charge_bytes(len.min(65557) as usize, check.metadata_limits())?;
251 let tail_at = len.saturating_sub(65557);
252 let tail = bytes(source, tail_at, (len - tail_at) as usize, len)?;
253 let Some(end) = end_record(source, &tail, tail_at, check)? else {
254 return Ok(None);
255 };
256 let h = &tail[end..];
257 let count = u16at(h, 10) as u32;
258 if u16at(h, 4) != 0
259 || u16at(h, 6) != 0
260 || u16at(h, 8) as u32 != count
261 || count == u16::MAX as u32
262 || u32at(h, 12) == u32::MAX
263 || u32at(h, 16) == u32::MAX
264 {
265 return Err(ErrorCode::UnsupportedFeature);
266 }
267 let cd = u32at(h, 16) as u64;
268 let cd_end = tail_at + end as u64;
269 let declared_cd_end = add(cd, u32at(h, 12) as u64)?;
270 // 중앙 목록의 주석을 ZIP64 locator로 오인하지 않음.
271 if cd_end >= 20
272 && declared_cd_end <= cd_end - 20
273 && bytes(source, cd_end - 20, 4, len)? == b"PK\x06\x07"
274 {
275 return Err(ErrorCode::UnsupportedFeature);
276 }
277 if declared_cd_end != cd_end {
278 return Err(ErrorCode::Integrity);
279 }
280 if count > limits.entries {
281 return Err(ErrorCode::Limit);
282 }
283 check.observe(
284 ResourceUsage {
285 estimated_entries: Some(count),
286 ..ResourceUsage::default()
287 },
288 Some(source),
289 )?;
290 let mut items = Vec::new();
291 let mut at = cd;
292 for _ in 0..count {
293 check.check()?;
294 let h = bytes(source, at, 46, cd_end)?;
295 if &h[..4] != b"PK\x01\x02" {
296 return Err(ErrorCode::Integrity);
297 }
298 if u16at(&h, 34) != 0 || u32at(&h, 42) == u32::MAX {
299 return Err(ErrorCode::UnsupportedFeature);
300 }
301 let flags = u16at(&h, 8);
302 if flags & 0x2040 != 0 {
303 return Err(ErrorCode::UnsupportedFeature);
304 }
305 let nn = u16at(&h, 28) as usize;
306 let ne = u16at(&h, 30) as usize;
307 let next = add(at, 46 + nn as u64 + ne as u64 + u16at(&h, 32) as u64)?;
308 if next > cd_end {
309 return Err(ErrorCode::Integrity);
310 }
311 charge(&mut metadata, nn, ne, check)?;
312 let raw = bytes(source, at + 46, nn, cd_end)?;
313 let ext = bytes(source, at + 46 + nn as u64, ne, cd_end)?;
314 extra(&ext)?;
315 let (size, packed) = declared(u32at(&h, 24), u32at(&h, 20))?;
316 let unix_kind = (u32at(&h, 38) >> 16) & 0xf000;
317 let kind = match unix_kind {
318 0 | 0x8000 => {
319 if raw.ends_with(b"/") {
320 EntryKind::Directory
321 } else {
322 EntryKind::File
323 }
324 }
325 0x4000 => EntryKind::Directory,
326 _ => return Err(ErrorCode::UnsafePath),
327 };
328 let name = named(&raw, flags, &ext, kind)?;
329 metadata.charge_with(&name, check.metadata_limits())?;
330 let offset = u32at(&h, 42) as u64;
331 let mut item = candidate(
332 offset,
333 name,
334 kind,
335 size,
336 packed,
337 u32at(&h, 16),
338 u16at(&h, 10),
339 flags,
340 );
341 if add(offset, 30)? > cd {
342 return Err(ErrorCode::Integrity);
343 }
344 let local = bytes(source, offset, 30, cd)?;
345 declared(u32at(&local, 22), u32at(&local, 18))?;
346 let ln = u16at(&local, 26) as usize;
347 let le = u16at(&local, 28) as usize;
348 charge(&mut metadata, ln, le, check)?;
349 let start = add(offset, 30 + ln as u64 + le as u64)?;
350 if start > cd {
351 return Err(ErrorCode::Integrity);
352 }
353 let local_raw = bytes(source, offset + 30, ln, cd)?;
354 let local_extra = bytes(source, offset + 30 + ln as u64, le, cd)?;
355 extra(&local_extra)?;
356 let mut stop = add(start, packed)?;
357 if stop > cd {
358 return Err(ErrorCode::Integrity);
359 }
360 item.start = start;
361 item.boundary =
362 raw == local_raw && flags == u16at(&local, 6) && item.method == u16at(&local, 8);
363 item.repaired = &local[..4] != b"PK\x03\x04"
364 || (flags & 8 == 0
365 && (u32at(&local, 14) != item.crc
366 || u32at(&local, 18) as u64 != packed
367 || u32at(&local, 22) as u64 != size));
368 if flags & 8 != 0 {
369 let descriptor = bytes(source, stop, 12, cd)?;
370 let skip = if &descriptor[..4] == b"PK\x07\x08" {
371 4
372 } else {
373 0
374 };
375 let d = bytes(source, stop + skip, 12, cd)?;
376 if u32at(&d, 0) != item.crc
377 || u32at(&d, 4) as u64 != packed
378 || u32at(&d, 8) as u64 != size
379 {
380 item.boundary = false;
381 }
382 stop = add(stop, 12 + skip)?;
383 }
384 item.stop = stop;
385 if kind == EntryKind::Directory && size != 0 {
386 item.boundary = false;
387 }
388 items.push(item);
389 at = next;
390 completed(Ok(()), check)?;
391 }
392 if at != cd_end {
393 return Err(ErrorCode::Integrity);
394 }
395 items.sort_by_key(|c| c.finding.source_offset);
396 let mut cursor = 0;
397 let mut complete = true;
398 for c in &items {
399 if c.finding.source_offset < cursor {
400 return Err(ErrorCode::Integrity);
401 }
402 complete &= c.finding.source_offset == cursor && c.boundary;
403 cursor = c.stop;
404 }
405 complete &= cursor == cd;
406 Ok(Some((items, complete)))
407}
408fn local(
409 source: &mut File,
410 len: u64,
411 limits: Limits,
412 check: &mut impl Monitor,
413) -> Result<Vec<Candidate>> {
414 let mut at = 0;
415 let mut items = Vec::new();
416 let mut metadata = MetadataBudget::default();
417 while at < len {
418 check.check()?;
419 if len - at < 30 {
420 break;
421 }
422 let h = bytes(source, at, 30, len)?;
423 if &h[..4] != b"PK\x03\x04" {
424 if at == 0
425 && (h.starts_with(b"MZ")
426 || h.starts_with(b"PK\x07\x08")
427 || h.starts_with(b"PK\x06"))
428 {
429 return Err(ErrorCode::UnsupportedFeature);
430 }
431 break;
432 }
433 let count = u32::try_from(items.len() + 1).map_err(|_| ErrorCode::Limit)?;
434 if count > limits.entries {
435 return Err(ErrorCode::Limit);
436 }
437 check.observe(
438 ResourceUsage {
439 actual_entries: Some(count),
440 ..ResourceUsage::default()
441 },
442 Some(source),
443 )?;
444 let flags = u16at(&h, 6);
445 if flags & 0x2040 != 0 {
446 return Err(ErrorCode::UnsupportedFeature);
447 }
448 let nn = u16at(&h, 26) as usize;
449 let ne = u16at(&h, 28) as usize;
450 charge(&mut metadata, nn, ne, check)?;
451 let start = add(at, 30 + nn as u64 + ne as u64)?;
452 if start > len {
453 break;
454 }
455 let raw = bytes(source, at + 30, nn, len)?;
456 let ext = bytes(source, at + 30 + nn as u64, ne, len)?;
457 extra(&ext)?;
458 let kind = if raw.ends_with(b"/") {
459 EntryKind::Directory
460 } else {
461 EntryKind::File
462 };
463 let name = named(&raw, flags, &ext, kind)?;
464 metadata.charge_with(&name, check.metadata_limits())?;
465 let (size, packed) = declared(u32at(&h, 22), u32at(&h, 18))?;
466 let mut c = candidate(
467 at,
468 name,
469 kind,
470 size,
471 packed,
472 u32at(&h, 14),
473 u16at(&h, 8),
474 flags,
475 );
476 c.start = start;
477 c.stop = add(start, packed)?;
478 if flags & 8 != 0 {
479 c.finding.declared_size = None;
480 items.push(c);
481 break;
482 }
483 c.boundary = true;
484 let next = c.stop;
485 items.push(c);
486 if next > len {
487 break;
488 }
489 at = next;
490 completed(Ok(()), check)?;
491 }
492 Ok(items)
493}
494
495pub(crate) struct Recovery {
496 source: Input,
497 path: PathBuf,
498 modified: Option<SystemTime>,
499 pub snapshot: spool::Snapshot,
500 pub findings: Vec<RecoveryEntry>,
501 pub summary: RecoveryEnd,
502 pub data: File,
503 pub offsets: Vec<u64>,
504}
505impl Recovery {
506 pub fn open(path: &Path, limits: Limits, check: &mut impl Monitor) -> Result<Self> {
507 let mut source = completed(Input::open(path), check)?;
508 let meta = io(source.file.metadata())?;
509 if !meta.is_file() {
510 return Err(ErrorCode::InvalidRequest);
511 }
512 if meta.len() > INPUT_CAP {
513 return Err(ErrorCode::UnsupportedFeature);
514 }
515 let prefix = bytes(&mut source.file, 0, meta.len().min(4) as usize, meta.len())?;
516 if prefix.starts_with(b"MZ")
517 || prefix.starts_with(b"PK\x07\x08")
518 || prefix.starts_with(b"PK\x06")
519 {
520 return Err(ErrorCode::UnsupportedFeature);
521 }
522 let mut snapshot =
523 spool::Snapshot::capture(&mut source.file, limits.input.min(INPUT_CAP), check)?;
524 let named = completed(Input::open(path), check)?;
525 if filesystem::object(&named.file)? != snapshot.object {
526 return Err(ErrorCode::SourceChanged);
527 }
528 let discovered = central(&mut snapshot.file, snapshot.len, limits, check);
529 let (mut candidates, mode, known) = match discovered {
530 Ok(Some((items, complete))) => (items, RecoveryMode::CentralDirectory, complete),
531 Ok(None) | Err(ErrorCode::Integrity) => (
532 local(&mut snapshot.file, snapshot.len, limits, check)?,
533 RecoveryMode::LocalChain,
534 false,
535 ),
536 Err(error) => return Err(error),
537 };
538 let mut names = Vec::new();
539 let mut budget = MetadataBudget::default();
540 for (id, c) in candidates.iter_mut().enumerate() {
541 c.finding.candidate_id = id as u32;
542 let name = c.finding.name.as_ref().ok_or(ErrorCode::Internal)?;
543 budget.charge_with(name, check.metadata_limits())?;
544 names.push(Member {
545 entry: Entry {
546 entry_id: id as u32,
547 name: name.clone(),
548 kind: c.finding.kind.unwrap(),
549 size: c.finding.declared_size.unwrap_or(0),
550 compressed_size: c.packed,
551 encrypted: false,
552 },
553 data: Vec::new(),
554 });
555 }
556 archive::validate_members_with(&names, check)?;
557 drop(names);
558 let mut data = spool::temporary()?;
559 let mut findings = Vec::new();
560 let mut offsets = Vec::new();
561 let mut used = 0u64;
562 let mut verified = 0;
563 let mut lost = 0;
564 let mut unverified = 0;
565 let mut repaired = false;
566 for c in candidates {
567 check.check()?;
568 let base = io(data.stream_position())?;
569 offsets.push(base);
570 let mut finding = c.finding;
571 if !c.boundary {
572 finding.reason = RecoveryReason::BoundaryUnknown;
573 } else if !c.supported {
574 finding.reason = RecoveryReason::UnsupportedFeature;
575 } else if c.stop > snapshot.len {
576 finding.status = RecoveryStatus::Lost;
577 finding.reason = RecoveryReason::Truncated;
578 } else {
579 let size = finding.declared_size.ok_or(ErrorCode::Internal)?;
580 if used.checked_add(size).is_none_or(|n| n > limits.output) {
581 return Err(ErrorCode::Limit);
582 }
583 check.observe(
584 ResourceUsage {
585 estimated_bytes: Some(used + size),
586 actual_entries: Some(finding.candidate_id + 1),
587 compressed_bytes: Some(c.packed),
588 ratio_output_bytes: Some(size),
589 ..ResourceUsage::default()
590 },
591 Some(&data),
592 )?;
593 io(snapshot.file.seek(SeekFrom::Start(c.start)))?;
594 let decoded = decode(
595 &mut snapshot.file,
596 c.packed,
597 c.method,
598 size,
599 &mut data,
600 &mut used,
601 limits,
602 check,
603 );
604 match decoded {
605 Ok((length, crc, hash))
606 if length == size
607 && crc == c.crc
608 && (finding.kind != Some(EntryKind::Directory) || size == 0) =>
609 {
610 finding.status = RecoveryStatus::Verified;
611 finding.reason = if c.repaired {
612 RecoveryReason::HeaderRebuilt
613 } else if mode == RecoveryMode::LocalChain {
614 RecoveryReason::MetadataMissing
615 } else {
616 RecoveryReason::None
617 };
618 finding.verified_size = Some(size);
619 finding.sha256 = if finding.kind == Some(EntryKind::File) {
620 Some(hash)
621 } else {
622 None
623 };
624 }
625 Ok((length, _, _)) => {
626 finding.status = RecoveryStatus::Lost;
627 finding.reason = if length == size {
628 RecoveryReason::CrcMismatch
629 } else {
630 RecoveryReason::DecodeFailure
631 };
632 }
633 Err(ErrorCode::Integrity) => {
634 finding.status = RecoveryStatus::Lost;
635 finding.reason = RecoveryReason::DecodeFailure;
636 }
637 Err(error) => return Err(error),
638 }
639 if finding.status != RecoveryStatus::Verified {
640 io(data.set_len(base))?;
641 io(data.seek(SeekFrom::Start(base)))?;
642 }
643 }
644 repaired |= c.repaired;
645 match finding.status {
646 RecoveryStatus::Verified => verified += 1,
647 RecoveryStatus::Lost => lost += 1,
648 RecoveryStatus::Unverified => unverified += 1,
649 }
650 check.progress(Stage::Verify, used, None, finding.candidate_id + 1)?;
651 findings.push(finding);
652 }
653 if known && verified as usize == findings.len() && !repaired {
654 return Err(ErrorCode::InvalidRequest);
655 }
656 let summary = RecoveryEnd {
657 mode,
658 source_bytes: snapshot.len,
659 source_sha256: snapshot.hash,
660 known_entries: if known {
661 Some(findings.len() as u32)
662 } else {
663 None
664 },
665 verified_entries: verified,
666 lost_entries: lost,
667 unverified_entries: unverified,
668 unknown_loss: !known,
669 };
670 Ok(Self {
671 source,
672 path: path.to_owned(),
673 modified: meta.modified().ok(),
674 snapshot,
675 findings,
676 summary,
677 data,
678 offsets,
679 })
680 }
681 pub fn build(&mut self, limits: Limits, check: &mut impl Monitor) -> Result<(File, u64)> {
682 let (mut output, len) =
683 crate::create::recovered_zip(&self.findings, &self.offsets, &mut self.data, check)?;
684 let mut replay = Replay(check);
685 let mut catalog =
686 crate::streaming::Catalog::open(&mut output, len, limits, true, None, &mut replay)?;
687 if catalog.format != Format::Zip
688 || catalog.members.len() != self.summary.verified_entries as usize
689 {
690 return Err(ErrorCode::Integrity);
691 }
692 for ((member, offset), finding) in catalog.members.iter().zip(&catalog.offsets).zip(
693 self.findings
694 .iter()
695 .filter(|e| e.status == RecoveryStatus::Verified),
696 ) {
697 if Some(&member.entry.name) != finding.name.as_ref()
698 || Some(member.entry.kind) != finding.kind
699 || Some(member.entry.size) != finding.verified_size
700 {
701 return Err(ErrorCode::Integrity);
702 }
703 if member.entry.kind == EntryKind::File {
704 io(catalog.data.seek(SeekFrom::Start(*offset)))?;
705 let mut input = (&mut catalog.data).take(member.entry.size);
706 let mut hash = Sha256::new();
707 let mut buffer = [0; 65536];
708 loop {
709 replay.check()?;
710 let n = completed(io(input.read(&mut buffer)), &mut replay)?;
711 if n == 0 {
712 break;
713 }
714 hash.update(&buffer[..n]);
715 }
716 if input.limit() != 0 || Some(<[u8; 32]>::from(hash.finalize())) != finding.sha256 {
717 return Err(ErrorCode::Integrity);
718 }
719 }
720 }
721 io(output.rewind())?;
722 Ok((output, len))
723 }
724 pub fn verify_source(&mut self, check: &mut impl Monitor) -> Result<()> {
725 let mut named = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
726 let before = io(named.file.metadata())?;
727 let pinned = io(self.source.file.metadata())?;
728 if filesystem::object(&named.file)? != self.snapshot.object
729 || before.len() != self.snapshot.len
730 || before.modified().ok() != self.modified
731 || pinned.len() != self.snapshot.len
732 || pinned.modified().ok() != self.modified
733 {
734 return Err(ErrorCode::SourceChanged);
735 }
736 let mut hash = Sha256::new();
737 let mut buffer = [0; 65536];
738 let mut length = 0;
739 loop {
740 check.check()?;
741 let n = completed(io(named.file.read(&mut buffer)), check)?;
742 if n == 0 {
743 break;
744 }
745 length = add(length, n as u64)?;
746 hash.update(&buffer[..n]);
747 check.progress(
748 Stage::Verify,
749 length,
750 Some(self.snapshot.len),
751 self.findings.len() as u32,
752 )?;
753 }
754 let after = io(named.file.metadata())?;
755 let current = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
756 if length != self.snapshot.len
757 || <[u8; 32]>::from(hash.finalize()) != self.snapshot.hash
758 || after.len() != self.snapshot.len
759 || after.modified().ok() != self.modified
760 || filesystem::object(&current.file)? != self.snapshot.object
761 {
762 return Err(ErrorCode::SourceChanged);
763 }
764 Ok(())
765 }
766}
767fn decode(
768 input: &mut File,
769 length: u64,
770 method: u16,
771 declared: u64,
772 output: &mut File,
773 used: &mut u64,
774 limits: Limits,
775 check: &mut impl Monitor,
776) -> Result<(u64, u32, [u8; 32])> {
777 let mut input = input.take(length);
778 let mut stream = Inflate::new(false, 15);
779 let mut buffer = [0; 65536];
780 let mut plain = [0; 65536];
781 let mut have = 0;
782 let mut at = 0;
783 let mut total = 0u64;
784 let mut crc = 0;
785 let mut hash = Sha256::new();
786 loop {
787 check.check()?;
788 if at == have && input.limit() != 0 {
789 have = completed(io(input.read(&mut buffer)), check)?;
790 at = 0;
791 if have == 0 {
792 return Err(ErrorCode::Integrity);
793 }
794 }
795 let (n, status, consumed, corrupt) = if method == 0 {
796 plain[..have].copy_from_slice(&buffer[..have]);
797 (
798 have,
799 if input.limit() == 0 {
800 Status::StreamEnd
801 } else {
802 Status::Ok
803 },
804 have,
805 false,
806 )
807 } else {
808 let before_in = stream.total_in();
809 let before_out = stream.total_out();
810 let status = stream.decompress(&buffer[at..have], &mut plain, InflateFlush::NoFlush);
811 let corrupt = status.is_err();
812 (
813 (stream.total_out() - before_out) as usize,
814 status.unwrap_or(Status::Ok),
815 (stream.total_in() - before_in) as usize,
816 corrupt,
817 )
818 };
819 at += consumed;
820 total = total.checked_add(n as u64).ok_or(ErrorCode::Limit)?;
821 *used = used
822 .checked_add(n as u64)
823 .filter(|n| *n <= limits.output)
824 .ok_or(ErrorCode::Limit)?;
825 check.observe(
826 ResourceUsage {
827 actual_bytes: Some(*used),
828 compressed_bytes: Some(length),
829 ratio_output_bytes: Some(total),
830 ..ResourceUsage::default()
831 },
832 Some(output),
833 )?;
834 if corrupt || total > declared {
835 return Err(ErrorCode::Integrity);
836 }
837 crc = crc32(crc, &plain[..n]);
838 hash.update(&plain[..n]);
839 crate::space::ensure(output, n as u64)?;
840 completed(io(output.write_all(&plain[..n])), check)?;
841 if status == Status::StreamEnd {
842 if input.limit() != 0 || at != have {
843 return Err(ErrorCode::Integrity);
844 }
845 break;
846 }
847 if n == 0 && consumed == 0 {
848 return Err(ErrorCode::Integrity);
849 }
850 }
851 Ok((total, crc, hash.finalize().into()))
852}
853
854struct Replay<'a, M>(&'a mut M);
855impl<M: Monitor> Monitor for Replay<'_, M> {
856 fn metadata_limits(&self) -> archive::MetadataLimits {
857 self.0.metadata_limits()
858 }
859 fn check(&mut self) -> Result<()> {
860 self.0.check()
861 }
862 fn activity(&mut self) -> Result<()> {
863 self.0.activity()
864 }
865 fn observe(&mut self, _usage: ResourceUsage, _storage: Option<&File>) -> Result<()> {
866 self.0.check()
867 }
868}
869
870#[cfg(test)]
871#[path = "../../../tests/rust-archive-worker/recovery_checks.rs"]
872mod tests;