| 1 | use crate::{ |
| 2 | archive::{self, Member, MetadataBudget}, |
| 3 | crypto, |
| 4 | protocol::*, |
| 5 | spool, |
| 6 | }; |
| 7 | use std::{ |
| 8 | fs::File, |
| 9 | io::{Read, Seek, SeekFrom, Write}, |
| 10 | }; |
| 11 | use zeroize::Zeroizing; |
| 12 | use zlib_rs::{Inflate, InflateFlush, Status, crc32::crc32}; |
| 13 | |
| 14 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 15 | const CHUNK: usize = 65536; |
| 16 | fn at(file: &mut File, offset: u64, bytes: &mut [u8]) -> Result<()> { |
| 17 | file.seek(SeekFrom::Start(offset)) |
| 18 | .map_err(|_| ErrorCode::Io)?; |
| 19 | file.read_exact(bytes).map_err(|_| ErrorCode::Integrity) |
| 20 | } |
| 21 | fn bytes(file: &mut File, offset: u64, size: usize) -> Result<Vec<u8>> { |
| 22 | let mut result = vec![0; size]; |
| 23 | at(file, offset, &mut result)?; |
| 24 | Ok(result) |
| 25 | } |
| 26 | fn u16at(b: &[u8], at: usize) -> u16 { |
| 27 | u16::from_le_bytes(b[at..at + 2].try_into().unwrap()) |
| 28 | } |
| 29 | fn u32at(b: &[u8], at: usize) -> u32 { |
| 30 | u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) |
| 31 | } |
| 32 | fn u64at(b: &[u8], at: usize) -> u64 { |
| 33 | u64::from_le_bytes(b[at..at + 8].try_into().unwrap()) |
| 34 | } |
| 35 | fn add(a: u64, b: u64) -> Result<u64> { |
| 36 | a.checked_add(b).ok_or(ErrorCode::Integrity) |
| 37 | } |
| 38 | fn io<T>(v: std::io::Result<T>) -> Result<T> { |
| 39 | v.map_err(crate::space::io_error) |
| 40 | } |
| 41 | |
| 42 | pub(crate) struct Catalog { |
| 43 | pub format: Format, |
| 44 | pub members: Vec<Member>, |
| 45 | pub offsets: Vec<u64>, |
| 46 | pub data: File, |
| 47 | } |
| 48 | impl Catalog { |
| 49 | pub fn open( |
| 50 | source: &mut File, |
| 51 | len: u64, |
| 52 | limits: Limits, |
| 53 | decode: bool, |
| 54 | password: Option<&[u8]>, |
| 55 | check: &mut impl FnMut() -> Result<()>, |
| 56 | ) -> Result<Self> { |
| 57 | let mut magic = [0; 6]; |
| 58 | let n = len.min(6) as usize; |
| 59 | at(source, 0, &mut magic[..n])?; |
| 60 | if magic.starts_with(b"7z\xbc\xaf\x27\x1c") { |
| 61 | return crate::seven_zip::open(source, len, limits, decode, check); |
| 62 | } |
| 63 | if magic.starts_with(b"PK\x03\x04") |
| 64 | || magic.starts_with(b"PK\x05\x06") |
| 65 | || magic.starts_with(b"PK\x06\x06") |
| 66 | { |
| 67 | return zip(source, len, limits, decode, password, check); |
| 68 | } |
| 69 | if magic.starts_with(&[31, 139]) { |
| 70 | let mut data = spool::temporary()?; |
| 71 | io(source.rewind())?; |
| 72 | let expanded = inflate(source, len, true, limits.output, &mut data, check)?.0; |
| 73 | let mut header = [0; 512]; |
| 74 | if expanded >= 512 { |
| 75 | at(&mut data, 0, &mut header)?; |
| 76 | if matches!(&header[257..263], b"ustar\0" | b"ustar ") { |
| 77 | return tar(data, expanded, limits, Format::TarGzip, check); |
| 78 | } |
| 79 | } |
| 80 | return Ok(Self { |
| 81 | format: Format::Gzip, |
| 82 | members: vec![Member { |
| 83 | entry: Entry { |
| 84 | entry_id: 0, |
| 85 | name: "GZip stream".to_owned(), |
| 86 | kind: EntryKind::File, |
| 87 | size: expanded, |
| 88 | compressed_size: len, |
| 89 | encrypted: false, |
| 90 | }, |
| 91 | data: Vec::new(), |
| 92 | }], |
| 93 | offsets: vec![0], |
| 94 | data, |
| 95 | }); |
| 96 | } |
| 97 | if len >= 512 { |
| 98 | return tar(io(source.try_clone())?, len, limits, Format::Tar, check); |
| 99 | } |
| 100 | Err(ErrorCode::UnsupportedFormat) |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | fn tar( |
| 105 | mut data: File, |
| 106 | len: u64, |
| 107 | limits: Limits, |
| 108 | format: Format, |
| 109 | check: &mut impl FnMut() -> Result<()>, |
| 110 | ) -> Result<Catalog> { |
| 111 | let mut cursor = 0u64; |
| 112 | let mut total = 0u64; |
| 113 | let mut members = Vec::new(); |
| 114 | let mut offsets = Vec::new(); |
| 115 | let mut metadata = MetadataBudget::default(); |
| 116 | loop { |
| 117 | check()?; |
| 118 | let mut header = [0; 512]; |
| 119 | if add(cursor, 512)? > len { |
| 120 | return Err(ErrorCode::Integrity); |
| 121 | } |
| 122 | at(&mut data, cursor, &mut header)?; |
| 123 | if header.iter().all(|b| *b == 0) { |
| 124 | if add(cursor, 1024)? > len || len % 512 != 0 { |
| 125 | return Err(ErrorCode::Integrity); |
| 126 | } |
| 127 | let mut buffer = Zeroizing::new([0; CHUNK]); |
| 128 | let mut remaining = len - cursor - 512; |
| 129 | while remaining != 0 { |
| 130 | check()?; |
| 131 | let n = remaining.min(CHUNK as u64) as usize; |
| 132 | io(data.read_exact(&mut buffer[..n]))?; |
| 133 | if buffer[..n].iter().any(|b| *b != 0) { |
| 134 | return Err(ErrorCode::Integrity); |
| 135 | } |
| 136 | remaining -= n as u64; |
| 137 | } |
| 138 | break; |
| 139 | } |
| 140 | if members.len() >= limits.entries as usize { |
| 141 | return Err(ErrorCode::Limit); |
| 142 | } |
| 143 | let sum = header |
| 144 | .iter() |
| 145 | .enumerate() |
| 146 | .map(|(i, b)| { |
| 147 | if (148..156).contains(&i) { |
| 148 | 32 |
| 149 | } else { |
| 150 | *b as u64 |
| 151 | } |
| 152 | }) |
| 153 | .sum::<u64>(); |
| 154 | if sum != archive::octal(&header[148..156])? { |
| 155 | return Err(ErrorCode::Integrity); |
| 156 | } |
| 157 | let mut name = archive::tar_string(&header[..100])?; |
| 158 | if matches!(&header[257..263], b"ustar\0" | b"ustar ") { |
| 159 | let prefix = archive::tar_string(&header[345..500])?; |
| 160 | if !prefix.is_empty() { |
| 161 | name = format!("{prefix}/{name}"); |
| 162 | } |
| 163 | } else if header[257..263].iter().any(|b| *b != 0) { |
| 164 | return Err(ErrorCode::UnsupportedFeature); |
| 165 | } |
| 166 | let kind = match header[156] { |
| 167 | 0 | b'0' => EntryKind::File, |
| 168 | b'5' => EntryKind::Directory, |
| 169 | b'1' | b'2' => EntryKind::Link, |
| 170 | b'x' | b'g' | b'L' | b'K' => return Err(ErrorCode::UnsupportedFeature), |
| 171 | _ => EntryKind::Other, |
| 172 | }; |
| 173 | let size = archive::octal(&header[124..136])?; |
| 174 | if kind != EntryKind::File && size != 0 { |
| 175 | return Err(ErrorCode::Integrity); |
| 176 | } |
| 177 | total = total |
| 178 | .checked_add(size) |
| 179 | .filter(|n| *n <= limits.output) |
| 180 | .ok_or(ErrorCode::Limit)?; |
| 181 | let start = add(cursor, 512)?; |
| 182 | cursor = add( |
| 183 | start, |
| 184 | size.checked_add(511).ok_or(ErrorCode::Integrity)? / 512 * 512, |
| 185 | )?; |
| 186 | if cursor > len { |
| 187 | return Err(ErrorCode::Integrity); |
| 188 | } |
| 189 | metadata.charge(&name)?; |
| 190 | let name = archive::valid_name(&name, kind == EntryKind::Directory)?; |
| 191 | offsets.push(start); |
| 192 | members.push(Member { |
| 193 | entry: Entry { |
| 194 | entry_id: members.len() as u32, |
| 195 | name, |
| 196 | kind, |
| 197 | size, |
| 198 | compressed_size: size, |
| 199 | encrypted: false, |
| 200 | }, |
| 201 | data: Vec::new(), |
| 202 | }); |
| 203 | } |
| 204 | archive::validate_members(&members)?; |
| 205 | Ok(Catalog { |
| 206 | format, |
| 207 | members, |
| 208 | offsets, |
| 209 | data, |
| 210 | }) |
| 211 | } |
| 212 | |
| 213 | // ZIP 항목과 연결 GZip 스트림의 해제 총량을 제한함. |
| 214 | fn inflate( |
| 215 | input: &mut impl Read, |
| 216 | length: u64, |
| 217 | gzip: bool, |
| 218 | limit: u64, |
| 219 | output: &mut File, |
| 220 | check: &mut impl FnMut() -> Result<()>, |
| 221 | ) -> Result<(u64, u32)> { |
| 222 | let mut remaining = length; |
| 223 | let mut buffer = Zeroizing::new([0; CHUNK]); |
| 224 | let mut plain = Zeroizing::new([0; CHUNK]); |
| 225 | let mut have = 0; |
| 226 | let mut used = 0; |
| 227 | let mut total = 0u64; |
| 228 | let mut crc = 0; |
| 229 | loop { |
| 230 | let mut stream = Inflate::new(gzip, if gzip { 31 } else { 15 }); |
| 231 | loop { |
| 232 | check()?; |
| 233 | if used == have && remaining != 0 { |
| 234 | have = input |
| 235 | .read(&mut buffer[..remaining.min(CHUNK as u64) as usize]) |
| 236 | .map_err(|_| ErrorCode::Io)?; |
| 237 | if have == 0 { |
| 238 | return Err(ErrorCode::Integrity); |
| 239 | } |
| 240 | remaining -= have as u64; |
| 241 | used = 0; |
| 242 | } |
| 243 | let a = stream.total_in(); |
| 244 | let b = stream.total_out(); |
| 245 | let status = stream |
| 246 | .decompress(&buffer[used..have], &mut plain[..], InflateFlush::NoFlush) |
| 247 | .map_err(|_| ErrorCode::Integrity)?; |
| 248 | used += (stream.total_in() - a) as usize; |
| 249 | let n = (stream.total_out() - b) as usize; |
| 250 | total = total |
| 251 | .checked_add(n as u64) |
| 252 | .filter(|n| *n <= limit) |
| 253 | .ok_or(ErrorCode::Limit)?; |
| 254 | crc = crc32(crc, &plain[..n]); |
| 255 | crate::space::ensure(output, n as u64)?; |
| 256 | io(output.write_all(&plain[..n]))?; |
| 257 | if status == Status::StreamEnd { |
| 258 | break; |
| 259 | } |
| 260 | if a == stream.total_in() && b == stream.total_out() { |
| 261 | return Err(ErrorCode::Integrity); |
| 262 | } |
| 263 | } |
| 264 | if remaining == 0 && used == have { |
| 265 | break; |
| 266 | } |
| 267 | if !gzip { |
| 268 | return Err(ErrorCode::Integrity); |
| 269 | } |
| 270 | } |
| 271 | Ok((total, crc)) |
| 272 | } |
| 273 | |
| 274 | struct Packed { |
| 275 | offset: u64, |
| 276 | size: u64, |
| 277 | method: u16, |
| 278 | crc: Option<u32>, |
| 279 | flags: u16, |
| 280 | verifier: u8, |
| 281 | aes: bool, |
| 282 | } |
| 283 | |
| 284 | fn extra(bytes: &[u8]) -> Result<(Option<archive::AesExtra>, Option<Vec<u8>>)> { |
| 285 | let mut at = 0; |
| 286 | let mut aes = Vec::new(); |
| 287 | let mut large = None; |
| 288 | while at < bytes.len() { |
| 289 | if bytes.len() - at < 4 { |
| 290 | return Err(ErrorCode::Integrity); |
| 291 | } |
| 292 | let tag = u16at(bytes, at); |
| 293 | let len = u16at(bytes, at + 2) as usize; |
| 294 | let end = at + 4 + len; |
| 295 | if end > bytes.len() { |
| 296 | return Err(ErrorCode::Integrity); |
| 297 | } |
| 298 | if tag == 1 { |
| 299 | if large.is_some() { |
| 300 | return Err(ErrorCode::Integrity); |
| 301 | } |
| 302 | large = Some(bytes[at + 4..end].to_vec()); |
| 303 | } else { |
| 304 | aes.extend_from_slice(&bytes[at..end]); |
| 305 | } |
| 306 | at = end; |
| 307 | } |
| 308 | Ok((archive::aes_extra(&aes)?, large)) |
| 309 | } |
| 310 | fn large_value(value: u32, extra: &mut &[u8]) -> Result<u64> { |
| 311 | if value != u32::MAX { |
| 312 | return Ok(value as u64); |
| 313 | } |
| 314 | if extra.len() < 8 { |
| 315 | return Err(ErrorCode::Integrity); |
| 316 | } |
| 317 | let result = u64at(extra, 0); |
| 318 | *extra = &extra[8..]; |
| 319 | Ok(result) |
| 320 | } |
| 321 | fn expanded(value: u64, maximum: u64, large: u64) -> Result<u64> { |
| 322 | if value == maximum || value == large { |
| 323 | Ok(large) |
| 324 | } else { |
| 325 | Err(ErrorCode::Integrity) |
| 326 | } |
| 327 | } |
| 328 | fn disk_start(value: u16, extra: &mut &[u8]) -> Result<u32> { |
| 329 | if value != u16::MAX { |
| 330 | return Ok(value as u32); |
| 331 | } |
| 332 | if extra.len() < 4 { |
| 333 | return Err(ErrorCode::Integrity); |
| 334 | } |
| 335 | let result = u32at(extra, 0); |
| 336 | *extra = &extra[4..]; |
| 337 | Ok(result) |
| 338 | } |
| 339 | fn local_sizes(size: u32, compressed: u32, extra: Option<&[u8]>) -> Result<(u64, u64)> { |
| 340 | if let Some(extra) = extra { |
| 341 | // 로컬 ZIP64 추가 필드에는 두 크기가 함께 들어감. |
| 342 | if extra.len() < 16 { |
| 343 | return Err(ErrorCode::Integrity); |
| 344 | } |
| 345 | Ok(( |
| 346 | expanded(size as u64, u32::MAX as u64, u64at(extra, 0))?, |
| 347 | expanded(compressed as u64, u32::MAX as u64, u64at(extra, 8))?, |
| 348 | )) |
| 349 | } else if size == u32::MAX || compressed == u32::MAX { |
| 350 | Err(ErrorCode::Integrity) |
| 351 | } else { |
| 352 | Ok((size as u64, compressed as u64)) |
| 353 | } |
| 354 | } |
| 355 | fn descriptor_size( |
| 356 | bytes: &[u8], |
| 357 | crc: u32, |
| 358 | compressed: u64, |
| 359 | size: u64, |
| 360 | wide_required: bool, |
| 361 | ) -> Result<usize> { |
| 362 | // 일반 크기 헤더와 64비트 디스크립터를 함께 기록하는 도구도 있음. |
| 363 | if bytes.len() >= 20 |
| 364 | && u32at(bytes, 0) == crc |
| 365 | && u64at(bytes, 4) == compressed |
| 366 | && u64at(bytes, 12) == size |
| 367 | { |
| 368 | return Ok(20); |
| 369 | } |
| 370 | if !wide_required |
| 371 | && bytes.len() >= 12 |
| 372 | && u32at(bytes, 0) == crc |
| 373 | && u32at(bytes, 4) as u64 == compressed |
| 374 | && u32at(bytes, 8) as u64 == size |
| 375 | { |
| 376 | return Ok(12); |
| 377 | } |
| 378 | Err(ErrorCode::Integrity) |
| 379 | } |
| 380 | fn zip( |
| 381 | source: &mut File, |
| 382 | len: u64, |
| 383 | limits: Limits, |
| 384 | decode: bool, |
| 385 | password: Option<&[u8]>, |
| 386 | check: &mut impl FnMut() -> Result<()>, |
| 387 | ) -> Result<Catalog> { |
| 388 | if len < 22 { |
| 389 | return Err(ErrorCode::Integrity); |
| 390 | } |
| 391 | let tail_at = len.saturating_sub(65557); |
| 392 | let tail = bytes(source, tail_at, (len - tail_at) as usize)?; |
| 393 | let end = (0..=tail.len() - 22) |
| 394 | .rev() |
| 395 | .find(|&i| { |
| 396 | &tail[i..i + 4] == b"PK\x05\x06" && i + 22 + u16at(&tail, i + 20) as usize == tail.len() |
| 397 | }) |
| 398 | .ok_or(ErrorCode::Integrity)?; |
| 399 | let h = &tail[end..]; |
| 400 | let mut disk = u16at(h, 4) as u64; |
| 401 | let mut central_disk = u16at(h, 6) as u64; |
| 402 | let mut entries_on_disk = u16at(h, 8) as u64; |
| 403 | let mut count = u16at(h, 10) as u64; |
| 404 | let mut central_size = u32at(h, 12) as u64; |
| 405 | let mut central = u32at(h, 16) as u64; |
| 406 | let mut central_end = tail_at + end as u64; |
| 407 | let required_zip64 = [disk, central_disk, entries_on_disk, count].contains(&(u16::MAX as u64)) |
| 408 | || central_size == u32::MAX as u64 |
| 409 | || central == u32::MAX as u64; |
| 410 | let locator = if central_end >= 20 { |
| 411 | bytes(source, central_end - 20, 20)? |
| 412 | } else { |
| 413 | Vec::new() |
| 414 | }; |
| 415 | // 중앙 디렉터리 주석의 동일 서명을 locator로 오인하지 않음 |
| 416 | let has_locator = |
| 417 | locator.starts_with(b"PK\x06\x07") && add(central, central_size)? != central_end; |
| 418 | if required_zip64 || has_locator { |
| 419 | if locator.len() != 20 { |
| 420 | return Err(ErrorCode::Integrity); |
| 421 | } |
| 422 | if &locator[..4] != b"PK\x06\x07" || u32at(&locator, 4) != 0 || u32at(&locator, 16) != 1 { |
| 423 | return Err(ErrorCode::UnsupportedFeature); |
| 424 | } |
| 425 | let offset = u64at(&locator, 8); |
| 426 | if add(offset, 56)? > central_end - 20 { |
| 427 | return Err(ErrorCode::Integrity); |
| 428 | } |
| 429 | let large = bytes(source, offset, 56)?; |
| 430 | if &large[..4] != b"PK\x06\x06" |
| 431 | || u64at(&large, 4) < 44 |
| 432 | || add(offset, add(12, u64at(&large, 4))?)? != central_end - 20 |
| 433 | { |
| 434 | return Err(ErrorCode::Integrity); |
| 435 | } |
| 436 | // 각 필드의 확장값을 해석한 뒤 단일 디스크 조건을 검사함. |
| 437 | disk = expanded(disk, u16::MAX as u64, u32at(&large, 16) as u64)?; |
| 438 | central_disk = expanded(central_disk, u16::MAX as u64, u32at(&large, 20) as u64)?; |
| 439 | entries_on_disk = expanded(entries_on_disk, u16::MAX as u64, u64at(&large, 24))?; |
| 440 | count = expanded(count, u16::MAX as u64, u64at(&large, 32))?; |
| 441 | central_size = expanded(central_size, u32::MAX as u64, u64at(&large, 40))?; |
| 442 | central = expanded(central, u32::MAX as u64, u64at(&large, 48))?; |
| 443 | central_end = offset; |
| 444 | } |
| 445 | if disk != 0 || central_disk != 0 || entries_on_disk != count { |
| 446 | return Err(ErrorCode::UnsupportedFeature); |
| 447 | } |
| 448 | if count > limits.entries as u64 { |
| 449 | return Err(ErrorCode::Limit); |
| 450 | } |
| 451 | if add(central, central_size)? != central_end { |
| 452 | return Err(ErrorCode::Integrity); |
| 453 | } |
| 454 | let mut cursor = central; |
| 455 | let mut total = 0u64; |
| 456 | let mut metadata = MetadataBudget::default(); |
| 457 | let mut members = Vec::new(); |
| 458 | let mut packed = Vec::new(); |
| 459 | let mut spans = Vec::new(); |
| 460 | for id in 0..count { |
| 461 | check()?; |
| 462 | if add(cursor, 46)? > central_end { |
| 463 | return Err(ErrorCode::Integrity); |
| 464 | } |
| 465 | let h = bytes(source, cursor, 46)?; |
| 466 | if &h[..4] != b"PK\x01\x02" { |
| 467 | return Err(ErrorCode::Integrity); |
| 468 | } |
| 469 | let flags = u16at(&h, 8); |
| 470 | let method = u16at(&h, 10); |
| 471 | if flags & !0x080f != 0 || !matches!(method, 0 | 8 | 99) { |
| 472 | return Err(ErrorCode::UnsupportedFeature); |
| 473 | } |
| 474 | let crc = u32at(&h, 16); |
| 475 | let (nn, ne, nc) = ( |
| 476 | u16at(&h, 28) as u64, |
| 477 | u16at(&h, 30) as u64, |
| 478 | u16at(&h, 32) as u64, |
| 479 | ); |
| 480 | let next = add(cursor, 46 + nn + ne + nc)?; |
| 481 | if next > central_end { |
| 482 | return Err(ErrorCode::Integrity); |
| 483 | } |
| 484 | if nn > 4096 { |
| 485 | return Err(ErrorCode::UnsafePath); |
| 486 | } |
| 487 | let raw = bytes(source, cursor + 46, nn as usize)?; |
| 488 | let central_extra = bytes(source, cursor + 46 + nn, ne as usize)?; |
| 489 | let (aes, large) = extra(¢ral_extra)?; |
| 490 | let name = archive::zip_name(&raw, flags, ¢ral_extra)?; |
| 491 | let name = name.as_str(); |
| 492 | let mut large = large.as_deref().unwrap_or(&[]); |
| 493 | let size = large_value(u32at(&h, 24), &mut large)?; |
| 494 | let compressed = large_value(u32at(&h, 20), &mut large)?; |
| 495 | let local = large_value(u32at(&h, 42), &mut large)?; |
| 496 | if disk_start(u16at(&h, 34), &mut large)? != 0 { |
| 497 | return Err(ErrorCode::UnsupportedFeature); |
| 498 | } |
| 499 | let encrypted = flags & 1 != 0; |
| 500 | if (method == 99) != aes.is_some() |
| 501 | || (method == 99 && !encrypted) |
| 502 | || (aes.is_some_and(|a| a.version == 2) && crc != 0) |
| 503 | { |
| 504 | return Err(ErrorCode::Integrity); |
| 505 | } |
| 506 | let overhead = if !encrypted { |
| 507 | 0 |
| 508 | } else if aes.is_some() { |
| 509 | 28 |
| 510 | } else { |
| 511 | 12 |
| 512 | }; |
| 513 | compressed |
| 514 | .checked_sub(overhead) |
| 515 | .ok_or(ErrorCode::Integrity)?; |
| 516 | total = total |
| 517 | .checked_add(size) |
| 518 | .filter(|n| *n <= limits.output) |
| 519 | .ok_or(ErrorCode::Limit)?; |
| 520 | let mode = u32at(&h, 38) >> 16; |
| 521 | let kind = match mode & 0xf000 { |
| 522 | 0xa000 => EntryKind::Link, |
| 523 | 0x4000 => EntryKind::Directory, |
| 524 | 0 | 0x8000 => { |
| 525 | if name.ends_with('/') { |
| 526 | EntryKind::Directory |
| 527 | } else { |
| 528 | EntryKind::File |
| 529 | } |
| 530 | } |
| 531 | _ => EntryKind::Other, |
| 532 | }; |
| 533 | if kind == EntryKind::Directory && size != 0 { |
| 534 | return Err(ErrorCode::Integrity); |
| 535 | } |
| 536 | metadata.charge(name)?; |
| 537 | let name = archive::valid_name(name, kind == EntryKind::Directory)?; |
| 538 | if add(local, 30)? > central { |
| 539 | return Err(ErrorCode::Integrity); |
| 540 | } |
| 541 | let lh = bytes(source, local, 30)?; |
| 542 | if &lh[..4] != b"PK\x03\x04" |
| 543 | || u16at(&lh, 6) != flags |
| 544 | || u16at(&lh, 8) != method |
| 545 | || u16at(&lh, 10) != u16at(&h, 12) |
| 546 | { |
| 547 | return Err(ErrorCode::Integrity); |
| 548 | } |
| 549 | let (ln, le) = (u16at(&lh, 26) as u64, u16at(&lh, 28) as u64); |
| 550 | let start = add(local, 30 + ln + le)?; |
| 551 | if start > central || ln != nn { |
| 552 | return Err(ErrorCode::Integrity); |
| 553 | } |
| 554 | if bytes(source, local + 30, ln as usize)? != raw { |
| 555 | return Err(ErrorCode::Integrity); |
| 556 | } |
| 557 | let (local_aes, local_large) = extra(&bytes(source, local + 30 + ln, le as usize)?)?; |
| 558 | if local_aes != aes || local_large.as_ref().is_some_and(|values| values.len() < 16) { |
| 559 | return Err(ErrorCode::Integrity); |
| 560 | } |
| 561 | let size_zip64 = u32at(&h, 20) == u32::MAX |
| 562 | || u32at(&h, 24) == u32::MAX |
| 563 | || u32at(&lh, 18) == u32::MAX |
| 564 | || u32at(&lh, 22) == u32::MAX |
| 565 | || local_large.is_some(); |
| 566 | if flags & 8 == 0 { |
| 567 | let (local_size, local_compressed) = |
| 568 | local_sizes(u32at(&lh, 22), u32at(&lh, 18), local_large.as_deref())?; |
| 569 | if u32at(&lh, 14) != crc || local_size != size || local_compressed != compressed { |
| 570 | return Err(ErrorCode::Integrity); |
| 571 | } |
| 572 | } |
| 573 | let mut stop = add(start, compressed)?; |
| 574 | if stop > central { |
| 575 | return Err(ErrorCode::Integrity); |
| 576 | } |
| 577 | if flags & 8 != 0 { |
| 578 | let descriptor_len = if size_zip64 { 20 } else { 12 }; |
| 579 | if add(stop, descriptor_len)? > central { |
| 580 | return Err(ErrorCode::Integrity); |
| 581 | } |
| 582 | let signature = bytes(source, stop, 4)?; |
| 583 | if signature == b"PK\x07\x08" { |
| 584 | stop = add(stop, 4)?; |
| 585 | } |
| 586 | let d = bytes(source, stop, (central - stop).min(20) as usize)?; |
| 587 | let descriptor_len = descriptor_size(&d, crc, compressed, size, size_zip64)?; |
| 588 | stop = add(stop, descriptor_len as u64)?; |
| 589 | } |
| 590 | spans.push((local, stop)); |
| 591 | packed.push(Packed { |
| 592 | offset: start, |
| 593 | size: compressed, |
| 594 | method: aes.map_or(method, |a| a.method), |
| 595 | crc: if aes.is_some_and(|a| a.version == 2) { |
| 596 | None |
| 597 | } else { |
| 598 | Some(crc) |
| 599 | }, |
| 600 | flags, |
| 601 | verifier: if flags & 8 != 0 { |
| 602 | (u16at(&h, 12) >> 8) as u8 |
| 603 | } else { |
| 604 | (crc >> 24) as u8 |
| 605 | }, |
| 606 | aes: aes.is_some(), |
| 607 | }); |
| 608 | members.push(Member { |
| 609 | entry: Entry { |
| 610 | entry_id: id as u32, |
| 611 | name, |
| 612 | kind, |
| 613 | size, |
| 614 | compressed_size: compressed, |
| 615 | encrypted, |
| 616 | }, |
| 617 | data: Vec::new(), |
| 618 | }); |
| 619 | cursor = next; |
| 620 | } |
| 621 | if cursor != central_end { |
| 622 | return Err(ErrorCode::Integrity); |
| 623 | } |
| 624 | spans.sort_unstable(); |
| 625 | let mut next = 0; |
| 626 | for (a, b) in spans { |
| 627 | if a != next { |
| 628 | return Err(ErrorCode::Integrity); |
| 629 | } |
| 630 | next = b; |
| 631 | } |
| 632 | if next != central { |
| 633 | return Err(ErrorCode::Integrity); |
| 634 | } |
| 635 | archive::validate_members(&members)?; |
| 636 | let mut data = spool::temporary()?; |
| 637 | if decode { |
| 638 | crate::space::ensure(&data, total)?; |
| 639 | } |
| 640 | let mut offsets = Vec::new(); |
| 641 | for (member, packed) in members.iter().zip(packed) { |
| 642 | check()?; |
| 643 | offsets.push(io(data.stream_position())?); |
| 644 | if !decode { |
| 645 | continue; |
| 646 | } |
| 647 | let (decoder, start, length) = if packed.flags & 1 != 0 { |
| 648 | crypto::Decryptor::prepare( |
| 649 | source, |
| 650 | packed.offset, |
| 651 | packed.size, |
| 652 | password.ok_or(ErrorCode::WrongPassword)?, |
| 653 | packed.aes, |
| 654 | packed.verifier, |
| 655 | check, |
| 656 | )? |
| 657 | } else { |
| 658 | (crypto::Decryptor::Plain, packed.offset, packed.size) |
| 659 | }; |
| 660 | io(source.seek(SeekFrom::Start(start)))?; |
| 661 | let mut reader = Decoded { |
| 662 | reader: source.take(length), |
| 663 | decoder, |
| 664 | }; |
| 665 | let (size, crc) = if packed.method == 8 { |
| 666 | inflate( |
| 667 | &mut reader, |
| 668 | length, |
| 669 | false, |
| 670 | member.entry.size, |
| 671 | &mut data, |
| 672 | check, |
| 673 | )? |
| 674 | } else { |
| 675 | let mut buffer = Zeroizing::new([0; CHUNK]); |
| 676 | let mut total = 0u64; |
| 677 | let mut crc = 0; |
| 678 | loop { |
| 679 | check()?; |
| 680 | let n = io(reader.read(&mut buffer[..]))?; |
| 681 | if n == 0 { |
| 682 | break; |
| 683 | } |
| 684 | total = total |
| 685 | .checked_add(n as u64) |
| 686 | .filter(|n| *n <= member.entry.size) |
| 687 | .ok_or(ErrorCode::Integrity)?; |
| 688 | crc = crc32(crc, &buffer[..n]); |
| 689 | io(data.write_all(&buffer[..n]))?; |
| 690 | } |
| 691 | (total, crc) |
| 692 | }; |
| 693 | if size != member.entry.size || packed.crc.is_some_and(|c| c != crc) { |
| 694 | return Err(ErrorCode::Integrity); |
| 695 | } |
| 696 | } |
| 697 | Ok(Catalog { |
| 698 | format: Format::Zip, |
| 699 | members, |
| 700 | offsets, |
| 701 | data, |
| 702 | }) |
| 703 | } |
| 704 | struct Decoded<R> { |
| 705 | reader: R, |
| 706 | decoder: crypto::Decryptor, |
| 707 | } |
| 708 | impl<R: Read> Read for Decoded<R> { |
| 709 | fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> { |
| 710 | let n = self.reader.read(output)?; |
| 711 | self.decoder.apply(&mut output[..n]); |
| 712 | Ok(n) |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | #[cfg(test)] |
| 717 | #[path = "../../../tests/rust-archive-worker/streaming_bounds.rs"] |
| 718 | mod bounds; |