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