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