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