team-ljyzipelo

공개
1,023줄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 declared(u32at(&local, 22), u32at(&local, 18))?;
473 let ln = u16at(&local, 26) as usize;
474 let le = u16at(&local, 28) as usize;
475 charge(&mut metadata, ln, le, check)?;
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 local_extra = bytes(source, offset + 30 + ln as u64, le, cd)?;
482 extra(&local_extra)?;
483 let mut stop = add(start, packed)?;
484 if stop > cd {
485 return Err(ErrorCode::Integrity);
486 }
487 item.start = start;
488 item.boundary =
489 raw == local_raw && flags == u16at(&local, 6) && item.method == u16at(&local, 8);
490 item.repaired = &local[..4] != b"PK\x03\x04"
491 || (flags & 8 == 0
492 && (u32at(&local, 14) != item.crc
493 || u32at(&local, 18) as u64 != packed
494 || u32at(&local, 22) as u64 != size));
495 if flags & 8 != 0 {
496 let descriptor = bytes(source, stop, 12, cd)?;
497 let skip = if &descriptor[..4] == b"PK\x07\x08" {
498 4
499 } else {
500 0
501 };
502 let d = bytes(source, stop + skip, 12, cd)?;
503 if u32at(&d, 0) != item.crc
504 || u32at(&d, 4) as u64 != packed
505 || u32at(&d, 8) as u64 != size
506 {
507 item.boundary = false;
508 }
509 stop = add(stop, 12 + skip)?;
510 }
511 item.stop = stop;
512 if kind == EntryKind::Directory && size != 0 {
513 item.boundary = false;
514 }
515 items.push(item);
516 at = next;
517 completed(Ok(()), check)?;
518 }
519 if at != cd_end {
520 return Err(ErrorCode::Integrity);
521 }
522 items.sort_by_key(|c| c.finding.source_offset);
523 let mut cursor = 0;
524 let mut complete = true;
525 for c in &items {
526 if c.finding.source_offset < cursor {
527 return Err(ErrorCode::Integrity);
528 }
529 complete &= c.finding.source_offset == cursor && c.boundary;
530 cursor = c.stop;
531 }
532 complete &= cursor == cd;
533 Ok(Some((items, complete)))
534}
535fn local(
536 source: &mut File,
537 len: u64,
538 limits: Limits,
539 check: &mut impl Monitor,
540) -> Result<Vec<Candidate>> {
541 let mut at = 0;
542 let mut items = Vec::new();
543 let mut metadata = MetadataBudget::default();
544 while at < len {
545 check.check()?;
546 if len - at < 30 {
547 break;
548 }
549 let h = bytes(source, at, 30, len)?;
550 if &h[..4] != b"PK\x03\x04" {
551 if at == 0
552 && (h.starts_with(b"MZ")
553 || h.starts_with(b"PK\x07\x08")
554 || h.starts_with(b"PK\x06"))
555 {
556 return Err(ErrorCode::UnsupportedFeature);
557 }
558 break;
559 }
560 let count = u32::try_from(items.len() + 1).map_err(|_| ErrorCode::Limit)?;
561 if count > limits.entries {
562 return Err(ErrorCode::Limit);
563 }
564 check.observe(
565 ResourceUsage {
566 actual_entries: Some(count),
567 ..ResourceUsage::default()
568 },
569 Some(source),
570 )?;
571 let flags = u16at(&h, 6);
572 if flags & 0x2040 != 0 {
573 return Err(ErrorCode::UnsupportedFeature);
574 }
575 let nn = u16at(&h, 26) as usize;
576 let ne = u16at(&h, 28) as usize;
577 charge(&mut metadata, nn, ne, check)?;
578 let start = add(at, 30 + nn as u64 + ne as u64)?;
579 if start > len {
580 break;
581 }
582 let raw = bytes(source, at + 30, nn, len)?;
583 let ext = bytes(source, at + 30 + nn as u64, ne, len)?;
584 extra(&ext)?;
585 let kind = if raw.ends_with(b"/") {
586 EntryKind::Directory
587 } else {
588 EntryKind::File
589 };
590 let name = named(&raw, flags, &ext, kind)?;
591 metadata.charge_with(&name, check.metadata_limits())?;
592 let (size, packed) = declared(u32at(&h, 22), u32at(&h, 18))?;
593 let mut c = candidate(
594 at,
595 name,
596 kind,
597 size,
598 packed,
599 u32at(&h, 14),
600 u16at(&h, 8),
601 flags,
602 );
603 c.start = start;
604 c.stop = add(start, packed)?;
605 if flags & 8 != 0 {
606 c.finding.declared_size = None;
607 items.push(c);
608 break;
609 }
610 c.boundary = true;
611 let next = c.stop;
612 items.push(c);
613 if next > len {
614 break;
615 }
616 at = next;
617 completed(Ok(()), check)?;
618 }
619 Ok(items)
620}
621
622pub(crate) struct Recovery {
623 source: Input,
624 path: PathBuf,
625 modified: Option<SystemTime>,
626 pub snapshot: spool::Snapshot,
627 pub findings: Vec<RecoveryEntry>,
628 pub summary: RecoveryEnd,
629 pub data: File,
630 pub offsets: Vec<u64>,
631}
632impl Recovery {
633 pub fn open(path: &Path, limits: Limits, check: &mut impl Monitor) -> Result<Self> {
634 let mut source = completed(Input::open(path), check)?;
635 let meta = io(source.file.metadata())?;
636 if !meta.is_file() {
637 return Err(ErrorCode::InvalidRequest);
638 }
639 if meta.len() > INPUT_CAP {
640 return Err(ErrorCode::UnsupportedFeature);
641 }
642 let prefix = bytes(&mut source.file, 0, meta.len().min(4) as usize, meta.len())?;
643 if prefix.starts_with(b"MZ")
644 || prefix.starts_with(b"PK\x07\x08")
645 || prefix.starts_with(b"PK\x06")
646 {
647 return Err(ErrorCode::UnsupportedFeature);
648 }
649 let mut snapshot =
650 spool::Snapshot::capture(&mut source.file, limits.input.min(INPUT_CAP), check)?;
651 let named = completed(Input::open(path), check)?;
652 if filesystem::object(&named.file)? != snapshot.object {
653 return Err(ErrorCode::SourceChanged);
654 }
655 let discovered = central(&mut snapshot.file, snapshot.len, limits, check);
656 let (mut candidates, mode, known) = match discovered {
657 Ok(Some((items, complete))) => (items, RecoveryMode::CentralDirectory, complete),
658 Ok(None) | Err(ErrorCode::Integrity) => (
659 local(&mut snapshot.file, snapshot.len, limits, check)?,
660 RecoveryMode::LocalChain,
661 false,
662 ),
663 Err(error) => return Err(error),
664 };
665 let mut names = Vec::new();
666 let mut budget = MetadataBudget::default();
667 for (id, c) in candidates.iter_mut().enumerate() {
668 c.finding.candidate_id = id as u32;
669 let name = c.finding.name.as_ref().ok_or(ErrorCode::Internal)?;
670 budget.charge_with(name, check.metadata_limits())?;
671 names.push(Member {
672 entry: Entry {
673 entry_id: id as u32,
674 name: name.clone(),
675 kind: c.finding.kind.unwrap(),
676 size: c.finding.declared_size.unwrap_or(0),
677 compressed_size: c.packed,
678 encrypted: false,
679 },
680 data: Vec::new(),
681 });
682 }
683 archive::validate_members_with(&names, check)?;
684 drop(names);
685 let mut data = spool::temporary()?;
686 let mut findings = Vec::new();
687 let mut offsets = Vec::new();
688 let mut used = 0u64;
689 let mut verified = 0;
690 let mut lost = 0;
691 let mut unverified = 0;
692 let mut repaired = false;
693 for c in candidates {
694 check.check()?;
695 let base = io(data.stream_position())?;
696 offsets.push(base);
697 let mut finding = c.finding;
698 if !c.boundary {
699 finding.reason = RecoveryReason::BoundaryUnknown;
700 } else if !c.supported {
701 finding.reason = RecoveryReason::UnsupportedFeature;
702 } else if c.stop > snapshot.len {
703 finding.status = RecoveryStatus::Lost;
704 finding.reason = RecoveryReason::Truncated;
705 } else {
706 let size = finding.declared_size.ok_or(ErrorCode::Internal)?;
707 if used.checked_add(size).is_none_or(|n| n > limits.output) {
708 return Err(ErrorCode::Limit);
709 }
710 check.observe(
711 ResourceUsage {
712 estimated_bytes: Some(used + size),
713 actual_entries: Some(finding.candidate_id + 1),
714 compressed_bytes: Some(c.packed),
715 ratio_output_bytes: Some(size),
716 ..ResourceUsage::default()
717 },
718 Some(&data),
719 )?;
720 io(snapshot.file.seek(SeekFrom::Start(c.start)))?;
721 let decoded = decode(
722 &mut snapshot.file,
723 c.packed,
724 c.method,
725 size,
726 &mut data,
727 &mut used,
728 limits,
729 check,
730 );
731 match decoded {
732 Ok((length, crc, hash))
733 if length == size
734 && crc == c.crc
735 && (finding.kind != Some(EntryKind::Directory) || size == 0) =>
736 {
737 finding.status = RecoveryStatus::Verified;
738 finding.reason = if c.repaired {
739 RecoveryReason::HeaderRebuilt
740 } else if mode == RecoveryMode::LocalChain {
741 RecoveryReason::MetadataMissing
742 } else {
743 RecoveryReason::None
744 };
745 finding.verified_size = Some(size);
746 finding.sha256 = if finding.kind == Some(EntryKind::File) {
747 Some(hash)
748 } else {
749 None
750 };
751 }
752 Ok((length, _, _)) => {
753 finding.status = RecoveryStatus::Lost;
754 finding.reason = if length == size {
755 RecoveryReason::CrcMismatch
756 } else {
757 RecoveryReason::DecodeFailure
758 };
759 }
760 Err(ErrorCode::Integrity) => {
761 finding.status = RecoveryStatus::Lost;
762 finding.reason = RecoveryReason::DecodeFailure;
763 }
764 Err(error) => return Err(error),
765 }
766 if finding.status != RecoveryStatus::Verified {
767 io(data.set_len(base))?;
768 io(data.seek(SeekFrom::Start(base)))?;
769 }
770 }
771 repaired |= c.repaired;
772 match finding.status {
773 RecoveryStatus::Verified => verified += 1,
774 RecoveryStatus::Lost => lost += 1,
775 RecoveryStatus::Unverified => unverified += 1,
776 }
777 check.progress(Stage::Verify, used, None, finding.candidate_id + 1)?;
778 findings.push(finding);
779 }
780 if known && verified as usize == findings.len() && !repaired {
781 return Err(ErrorCode::InvalidRequest);
782 }
783 let summary = RecoveryEnd {
784 mode,
785 source_bytes: snapshot.len,
786 source_sha256: snapshot.hash,
787 known_entries: if known {
788 Some(findings.len() as u32)
789 } else {
790 None
791 },
792 verified_entries: verified,
793 lost_entries: lost,
794 unverified_entries: unverified,
795 unknown_loss: !known,
796 };
797 Ok(Self {
798 source,
799 path: path.to_owned(),
800 modified: meta.modified().ok(),
801 snapshot,
802 findings,
803 summary,
804 data,
805 offsets,
806 })
807 }
808 pub fn build(&mut self, limits: Limits, check: &mut impl Monitor) -> Result<(File, u64)> {
809 let (mut output, len) =
810 crate::create::recovered_zip(&self.findings, &self.offsets, &mut self.data, check)?;
811 let mut replay = Replay(check);
812 let mut catalog =
813 crate::streaming::Catalog::open(&mut output, len, limits, true, None, &mut replay)?;
814 if catalog.format != Format::Zip
815 || catalog.members.len() != self.summary.verified_entries as usize
816 {
817 return Err(ErrorCode::Integrity);
818 }
819 for ((member, offset), finding) in catalog.members.iter().zip(&catalog.offsets).zip(
820 self.findings
821 .iter()
822 .filter(|e| e.status == RecoveryStatus::Verified),
823 ) {
824 if Some(&member.entry.name) != finding.name.as_ref()
825 || Some(member.entry.kind) != finding.kind
826 || Some(member.entry.size) != finding.verified_size
827 {
828 return Err(ErrorCode::Integrity);
829 }
830 if member.entry.kind == EntryKind::File {
831 io(catalog.data.seek(SeekFrom::Start(*offset)))?;
832 let mut input = (&mut catalog.data).take(member.entry.size);
833 let mut hash = Sha256::new();
834 let mut buffer = [0; 65536];
835 loop {
836 replay.check()?;
837 let n = completed(io(input.read(&mut buffer)), &mut replay)?;
838 if n == 0 {
839 break;
840 }
841 hash.update(&buffer[..n]);
842 }
843 if input.limit() != 0 || Some(<[u8; 32]>::from(hash.finalize())) != finding.sha256 {
844 return Err(ErrorCode::Integrity);
845 }
846 }
847 }
848 io(output.rewind())?;
849 Ok((output, len))
850 }
851 pub fn verify_source(&mut self, check: &mut impl Monitor) -> Result<()> {
852 let mut named = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
853 let before = io(named.file.metadata())?;
854 let pinned = io(self.source.file.metadata())?;
855 if filesystem::object(&named.file)? != self.snapshot.object
856 || before.len() != self.snapshot.len
857 || before.modified().ok() != self.modified
858 || pinned.len() != self.snapshot.len
859 || pinned.modified().ok() != self.modified
860 {
861 return Err(ErrorCode::SourceChanged);
862 }
863 let mut hash = Sha256::new();
864 let mut buffer = [0; 65536];
865 let mut length = 0;
866 loop {
867 check.check()?;
868 let n = completed(io(named.file.read(&mut buffer)), check)?;
869 if n == 0 {
870 break;
871 }
872 length = add(length, n as u64)?;
873 hash.update(&buffer[..n]);
874 check.progress(
875 Stage::Verify,
876 length,
877 Some(self.snapshot.len),
878 self.findings.len() as u32,
879 )?;
880 }
881 let after = io(named.file.metadata())?;
882 let current = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
883 if length != self.snapshot.len
884 || <[u8; 32]>::from(hash.finalize()) != self.snapshot.hash
885 || after.len() != self.snapshot.len
886 || after.modified().ok() != self.modified
887 || filesystem::object(&current.file)? != self.snapshot.object
888 {
889 return Err(ErrorCode::SourceChanged);
890 }
891 Ok(())
892 }
893}
894fn decode(
895 input: &mut File,
896 length: u64,
897 method: u16,
898 declared: u64,
899 output: &mut File,
900 used: &mut u64,
901 limits: Limits,
902 check: &mut impl Monitor,
903) -> Result<(u64, u32, [u8; 32])> {
904 decode_to(
905 input,
906 length,
907 method,
908 declared,
909 Some(output),
910 used,
911 limits,
912 check,
913 )
914}
915
916fn decode_to(
917 input: &mut File,
918 length: u64,
919 method: u16,
920 declared: u64,
921 mut output: Option<&mut File>,
922 used: &mut u64,
923 limits: Limits,
924 check: &mut impl Monitor,
925) -> Result<(u64, u32, [u8; 32])> {
926 let mut input = input.take(length);
927 let mut stream = Inflate::new(false, 15);
928 let mut buffer = [0; 65536];
929 let mut plain = [0; 65536];
930 let mut have = 0;
931 let mut at = 0;
932 let mut total = 0u64;
933 let mut crc = 0;
934 let mut hash = Sha256::new();
935 loop {
936 check.check()?;
937 if at == have && input.limit() != 0 {
938 have = completed(io(input.read(&mut buffer)), check)?;
939 at = 0;
940 if have == 0 {
941 return Err(ErrorCode::Integrity);
942 }
943 }
944 let (n, status, consumed, corrupt) = if method == 0 {
945 plain[..have].copy_from_slice(&buffer[..have]);
946 (
947 have,
948 if input.limit() == 0 {
949 Status::StreamEnd
950 } else {
951 Status::Ok
952 },
953 have,
954 false,
955 )
956 } else {
957 let before_in = stream.total_in();
958 let before_out = stream.total_out();
959 let status = stream.decompress(&buffer[at..have], &mut plain, InflateFlush::NoFlush);
960 let corrupt = status.is_err();
961 (
962 (stream.total_out() - before_out) as usize,
963 status.unwrap_or(Status::Ok),
964 (stream.total_in() - before_in) as usize,
965 corrupt,
966 )
967 };
968 at += consumed;
969 total = total.checked_add(n as u64).ok_or(ErrorCode::Limit)?;
970 *used = used
971 .checked_add(n as u64)
972 .filter(|n| *n <= limits.output)
973 .ok_or(ErrorCode::Limit)?;
974 check.observe(
975 ResourceUsage {
976 actual_bytes: Some(*used),
977 compressed_bytes: Some(length),
978 ratio_output_bytes: Some(total),
979 ..ResourceUsage::default()
980 },
981 output.as_deref(),
982 )?;
983 if corrupt || total > declared {
984 return Err(ErrorCode::Integrity);
985 }
986 crc = crc32(crc, &plain[..n]);
987 hash.update(&plain[..n]);
988 if let Some(file) = output.as_deref_mut() {
989 crate::space::ensure(file, n as u64)?;
990 completed(io(file.write_all(&plain[..n])), check)?;
991 }
992 if status == Status::StreamEnd {
993 if input.limit() != 0 || at != have {
994 return Err(ErrorCode::Integrity);
995 }
996 break;
997 }
998 if n == 0 && consumed == 0 {
999 return Err(ErrorCode::Integrity);
1000 }
1001 }
1002 Ok((total, crc, hash.finalize().into()))
1003}
1004
1005struct Replay<'a, M>(&'a mut M);
1006impl<M: Monitor> Monitor for Replay<'_, M> {
1007 fn metadata_limits(&self) -> archive::MetadataLimits {
1008 self.0.metadata_limits()
1009 }
1010 fn check(&mut self) -> Result<()> {
1011 self.0.check()
1012 }
1013 fn activity(&mut self) -> Result<()> {
1014 self.0.activity()
1015 }
1016 fn observe(&mut self, _usage: ResourceUsage, _storage: Option<&File>) -> Result<()> {
1017 self.0.check()
1018 }
1019}
1020
1021#[cfg(test)]
1022#[path = "../../../tests/rust-archive-worker/recovery_checks.rs"]
1023mod tests;