team-ljyzipelo

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