team-ljyzipelo

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