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