team-ljyzipelo

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