| 1 | use crate::{ |
| 2 | archive::{Member, MetadataBudget, valid_name, validate_members_with}, |
| 3 | protocol::*, |
| 4 | }; |
| 5 | use std::collections::BTreeSet; |
| 6 | use zlib_rs::crc32::crc32; |
| 7 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 8 | struct Reader<'a> { |
| 9 | bytes: &'a [u8], |
| 10 | at: usize, |
| 11 | } |
| 12 | impl<'a> Reader<'a> { |
| 13 | fn new(bytes: &'a [u8]) -> Self { |
| 14 | Self { bytes, at: 0 } |
| 15 | } |
| 16 | fn take(&mut self, n: usize) -> Result<&'a [u8]> { |
| 17 | let end = self.at.checked_add(n).ok_or(ErrorCode::Integrity)?; |
| 18 | let bytes = self.bytes.get(self.at..end).ok_or(ErrorCode::Integrity)?; |
| 19 | self.at = end; |
| 20 | Ok(bytes) |
| 21 | } |
| 22 | fn byte(&mut self) -> Result<u8> { |
| 23 | Ok(self.take(1)?[0]) |
| 24 | } |
| 25 | fn expect(&mut self, id: u8) -> Result<()> { |
| 26 | if self.byte()? == id { |
| 27 | Ok(()) |
| 28 | } else { |
| 29 | Err(ErrorCode::Integrity) |
| 30 | } |
| 31 | } |
| 32 | fn integer(&mut self) -> Result<u64> { |
| 33 | let first = self.byte()?; |
| 34 | let mut mask = 0x80; |
| 35 | let mut value = 0; |
| 36 | for i in 0..8 { |
| 37 | if first & mask == 0 { |
| 38 | return Ok(value | (((first & (mask - 1)) as u64) << (8 * i))); |
| 39 | } |
| 40 | value |= (self.byte()? as u64) << (8 * i); |
| 41 | mask >>= 1; |
| 42 | } |
| 43 | Ok(value) |
| 44 | } |
| 45 | fn number(&mut self, limit: usize) -> Result<usize> { |
| 46 | usize::try_from(self.integer()?) |
| 47 | .ok() |
| 48 | .filter(|n| *n <= limit) |
| 49 | .ok_or(ErrorCode::Limit) |
| 50 | } |
| 51 | fn bits(&mut self, count: usize) -> Result<Vec<bool>> { |
| 52 | let bytes = self.take(count.div_ceil(8))?; |
| 53 | Ok((0..count) |
| 54 | .map(|i| bytes[i / 8] & (0x80 >> (i % 8)) != 0) |
| 55 | .collect()) |
| 56 | } |
| 57 | fn defined(&mut self, count: usize) -> Result<Vec<bool>> { |
| 58 | match self.byte()? { |
| 59 | 0 => self.bits(count), |
| 60 | 1 => Ok(vec![true; count]), |
| 61 | _ => Err(ErrorCode::Integrity), |
| 62 | } |
| 63 | } |
| 64 | fn digests(&mut self, count: usize) -> Result<Vec<Option<u32>>> { |
| 65 | self.defined(count)? |
| 66 | .into_iter() |
| 67 | .map(|set| { |
| 68 | if set { |
| 69 | Ok(Some(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))) |
| 70 | } else { |
| 71 | Ok(None) |
| 72 | } |
| 73 | }) |
| 74 | .collect() |
| 75 | } |
| 76 | fn end(&self) -> Result<()> { |
| 77 | if self.at == self.bytes.len() { |
| 78 | Ok(()) |
| 79 | } else { |
| 80 | Err(ErrorCode::Integrity) |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | const AES: [u8; 4] = [6, 0xf1, 7, 1]; |
| 85 | struct Folder { |
| 86 | method: Vec<u8>, |
| 87 | properties: Vec<u8>, |
| 88 | /// 7zAES 코더가 있으면 그 속성. 묶음 스트림을 복호화한 뒤 `method`로 풂. |
| 89 | encryption: Option<crate::crypto::SevenZipAes>, |
| 90 | /// 복호화한 뒤 `method` 코더에 넘기는 크기. 암호가 없으면 묶음 크기와 같음. |
| 91 | inner: usize, |
| 92 | size: usize, |
| 93 | crc: Option<u32>, |
| 94 | sizes: Vec<usize>, |
| 95 | crcs: Vec<Option<u32>>, |
| 96 | } |
| 97 | struct Streams { |
| 98 | position: usize, |
| 99 | packed: Vec<usize>, |
| 100 | packed_crcs: Vec<Option<u32>>, |
| 101 | folders: Vec<Folder>, |
| 102 | } |
| 103 | impl Streams { |
| 104 | fn read( |
| 105 | r: &mut Reader<'_>, |
| 106 | limits: Limits, |
| 107 | check: &mut impl crate::resources::Monitor, |
| 108 | ) -> Result<Self> { |
| 109 | r.expect(6)?; |
| 110 | let position = r.number(limits.input as usize)?; |
| 111 | let count = r.number(limits.entries as usize)?; |
| 112 | r.expect(9)?; |
| 113 | let packed = (0..count) |
| 114 | .map(|_| crate::resources::completed(r.number(limits.input as usize), check)) |
| 115 | .collect::<Result<Vec<_>>>()?; |
| 116 | let mut tag = r.byte()?; |
| 117 | let packed_crcs = if tag == 10 { |
| 118 | tag = 255; |
| 119 | r.digests(count)? |
| 120 | } else { |
| 121 | vec![None; count] |
| 122 | }; |
| 123 | if tag == 255 { |
| 124 | tag = r.byte()?; |
| 125 | } |
| 126 | if tag != 0 { |
| 127 | return Err(ErrorCode::Integrity); |
| 128 | } |
| 129 | r.expect(7)?; |
| 130 | r.expect(11)?; |
| 131 | let num = r.number(limits.entries as usize)?; |
| 132 | if num != count { |
| 133 | return Err(ErrorCode::UnsupportedFeature); |
| 134 | } |
| 135 | if r.byte()? != 0 { |
| 136 | return Err(ErrorCode::UnsupportedFeature); |
| 137 | } |
| 138 | let mut folders = Vec::new(); |
| 139 | let mut layouts = Vec::new(); |
| 140 | for _ in 0..num { |
| 141 | // 단일 코더이거나, 7zAES와 Copy/LZMA/LZMA2를 묶은 `7z a -p`의 두 코더 구성만 받음. |
| 142 | let coders = r.integer()?; |
| 143 | if !(1..=2).contains(&coders) { |
| 144 | return Err(ErrorCode::UnsupportedFeature); |
| 145 | } |
| 146 | let mut list = Vec::new(); |
| 147 | for _ in 0..coders { |
| 148 | let flags = r.byte()?; |
| 149 | let len = (flags & 15) as usize; |
| 150 | if flags & 0xc0 != 0 || len == 0 { |
| 151 | return Err(ErrorCode::UnsupportedFeature); |
| 152 | } |
| 153 | let method = r.take(len)?.to_vec(); |
| 154 | if flags & 0x10 != 0 && (r.integer()? != 1 || r.integer()? != 1) { |
| 155 | return Err(ErrorCode::UnsupportedFeature); |
| 156 | } |
| 157 | let properties = if flags & 0x20 != 0 { |
| 158 | let n = r.number(64)?; |
| 159 | r.take(n)?.to_vec() |
| 160 | } else { |
| 161 | Vec::new() |
| 162 | }; |
| 163 | if !matches!(method.as_slice(), [0] | [3, 1, 1] | [0x21]) && method != AES { |
| 164 | return Err(ErrorCode::UnsupportedFeature); |
| 165 | } |
| 166 | list.push((method, properties)); |
| 167 | } |
| 168 | let aes = list.iter().position(|(method, _)| *method == AES); |
| 169 | let main = if coders == 2 { |
| 170 | // 결합 쌍은 주 코더의 입력을 7zAES의 출력에 잇고, 남은 7zAES 입력이 묶음 스트림임. |
| 171 | let input = r.integer()?; |
| 172 | let output = r.integer()?; |
| 173 | let (Some(aes), main) = (aes, aes.map_or(0, |a| 1 - a)) else { |
| 174 | return Err(ErrorCode::UnsupportedFeature); |
| 175 | }; |
| 176 | if list[main].0 == AES || input != main as u64 || output != aes as u64 { |
| 177 | return Err(ErrorCode::UnsupportedFeature); |
| 178 | } |
| 179 | main |
| 180 | } else { |
| 181 | 0 |
| 182 | }; |
| 183 | let encryption = aes |
| 184 | .map(|index| crate::crypto::SevenZipAes::parse(&list[index].1)) |
| 185 | .transpose()?; |
| 186 | let (method, properties) = if coders == 1 && encryption.is_some() { |
| 187 | (vec![0], Vec::new()) |
| 188 | } else { |
| 189 | list.swap_remove(main) |
| 190 | }; |
| 191 | layouts.push((coders as usize, main, aes)); |
| 192 | folders.push(Folder { |
| 193 | method, |
| 194 | properties, |
| 195 | encryption, |
| 196 | inner: 0, |
| 197 | size: 0, |
| 198 | crc: None, |
| 199 | sizes: Vec::new(), |
| 200 | crcs: Vec::new(), |
| 201 | }); |
| 202 | crate::resources::completed(Ok(()), check)?; |
| 203 | } |
| 204 | r.expect(12)?; |
| 205 | let mut total = 0usize; |
| 206 | for (folder, (coders, main, aes)) in folders.iter_mut().zip(&layouts) { |
| 207 | let mut sizes = [0; 2]; |
| 208 | for size in &mut sizes[..*coders] { |
| 209 | *size = r.number(limits.output as usize)?; |
| 210 | } |
| 211 | folder.size = sizes[*main]; |
| 212 | folder.inner = match aes { |
| 213 | Some(aes) if *coders == 2 => sizes[*aes], |
| 214 | _ => folder.size, |
| 215 | }; |
| 216 | total = total |
| 217 | .checked_add(folder.size) |
| 218 | .filter(|n| *n <= limits.output as usize) |
| 219 | .ok_or(ErrorCode::Limit)?; |
| 220 | crate::resources::completed(Ok(()), check)?; |
| 221 | } |
| 222 | let mut tag = r.byte()?; |
| 223 | if tag == 10 { |
| 224 | for (f, crc) in folders.iter_mut().zip(r.digests(num)?) { |
| 225 | f.crc = crc; |
| 226 | crate::resources::completed(Ok(()), check)?; |
| 227 | } |
| 228 | tag = r.byte()?; |
| 229 | } |
| 230 | if tag != 0 { |
| 231 | return Err(ErrorCode::Integrity); |
| 232 | } |
| 233 | let mut counts = vec![1usize; num]; |
| 234 | let mut supplied_sizes = false; |
| 235 | let mut tag = r.byte()?; |
| 236 | if tag == 8 { |
| 237 | tag = r.byte()?; |
| 238 | if tag == 13 { |
| 239 | let mut total = 0usize; |
| 240 | for n in &mut counts { |
| 241 | *n = r.number(limits.entries as usize)?; |
| 242 | total = total |
| 243 | .checked_add(*n) |
| 244 | .filter(|n| *n <= limits.entries as usize) |
| 245 | .ok_or(ErrorCode::Limit)?; |
| 246 | crate::resources::completed(Ok(()), check)?; |
| 247 | } |
| 248 | tag = r.byte()?; |
| 249 | } |
| 250 | if tag == 9 { |
| 251 | supplied_sizes = true; |
| 252 | for (folder, count) in folders.iter_mut().zip(&counts) { |
| 253 | let mut total = 0usize; |
| 254 | for _ in 1..*count { |
| 255 | let n = r.number(folder.size)?; |
| 256 | total = total |
| 257 | .checked_add(n) |
| 258 | .filter(|n| *n <= folder.size) |
| 259 | .ok_or(ErrorCode::Integrity)?; |
| 260 | folder.sizes.push(n); |
| 261 | crate::resources::completed(Ok(()), check)?; |
| 262 | } |
| 263 | if *count > 0 { |
| 264 | folder.sizes.push(folder.size - total); |
| 265 | } |
| 266 | } |
| 267 | tag = r.byte()?; |
| 268 | } |
| 269 | let digest_count = folders |
| 270 | .iter() |
| 271 | .zip(&counts) |
| 272 | .map(|(f, n)| if *n == 1 && f.crc.is_some() { 0 } else { *n }) |
| 273 | .sum(); |
| 274 | let mut digests = if tag == 10 { |
| 275 | let d = r.digests(digest_count)?; |
| 276 | tag = r.byte()?; |
| 277 | d.into_iter() |
| 278 | } else { |
| 279 | vec![None; digest_count].into_iter() |
| 280 | }; |
| 281 | for (f, n) in folders.iter_mut().zip(&counts) { |
| 282 | f.crcs = if *n == 1 && f.crc.is_some() { |
| 283 | vec![f.crc] |
| 284 | } else { |
| 285 | (0..*n).map(|_| digests.next().unwrap()).collect() |
| 286 | }; |
| 287 | crate::resources::completed(Ok(()), check)?; |
| 288 | } |
| 289 | if tag != 0 { |
| 290 | return Err(ErrorCode::Integrity); |
| 291 | } |
| 292 | tag = r.byte()?; |
| 293 | } else { |
| 294 | for f in &mut folders { |
| 295 | f.crcs.push(f.crc); |
| 296 | crate::resources::completed(Ok(()), check)?; |
| 297 | } |
| 298 | } |
| 299 | if tag != 0 { |
| 300 | return Err(ErrorCode::Integrity); |
| 301 | } |
| 302 | for (f, n) in folders.iter_mut().zip(&counts) { |
| 303 | if !supplied_sizes { |
| 304 | if *n > 1 { |
| 305 | return Err(ErrorCode::Integrity); |
| 306 | } |
| 307 | if *n == 1 { |
| 308 | f.sizes.push(f.size); |
| 309 | } |
| 310 | } |
| 311 | if *n == 0 && f.size != 0 { |
| 312 | return Err(ErrorCode::Integrity); |
| 313 | } |
| 314 | // 틀린 암호의 출력을 CRC로 가려내야 하므로 CRC가 없는 암호 폴더는 받지 않음. |
| 315 | if f.encryption.is_some() && f.crc.is_none() && f.crcs.iter().any(|c| c.is_none()) { |
| 316 | return Err(ErrorCode::UnsupportedFeature); |
| 317 | } |
| 318 | crate::resources::completed(Ok(()), check)?; |
| 319 | } |
| 320 | Ok(Self { |
| 321 | position, |
| 322 | packed, |
| 323 | packed_crcs, |
| 324 | folders, |
| 325 | }) |
| 326 | } |
| 327 | fn ranges( |
| 328 | &self, |
| 329 | input: &mut (impl std::io::Read + std::io::Seek), |
| 330 | data_end: u64, |
| 331 | check: &mut impl crate::resources::Monitor, |
| 332 | ) -> Result<Vec<(u64, u64)>> { |
| 333 | let mut at = 32u64 |
| 334 | .checked_add(self.position as u64) |
| 335 | .ok_or(ErrorCode::Integrity)?; |
| 336 | let mut ranges = Vec::new(); |
| 337 | for (size, expected) in self.packed.iter().zip(&self.packed_crcs) { |
| 338 | let size = *size as u64; |
| 339 | let end = at |
| 340 | .checked_add(size) |
| 341 | .filter(|n| *n <= data_end) |
| 342 | .ok_or(ErrorCode::Integrity)?; |
| 343 | if let Some(expected) = expected { |
| 344 | if digest(input, at, size, check)? != *expected { |
| 345 | return Err(ErrorCode::Integrity); |
| 346 | } |
| 347 | } |
| 348 | ranges.push((at, size)); |
| 349 | at = end; |
| 350 | crate::resources::completed(Ok(()), check)?; |
| 351 | } |
| 352 | Ok(ranges) |
| 353 | } |
| 354 | fn decode_file( |
| 355 | &self, |
| 356 | input: &mut (impl std::io::Read + std::io::Seek), |
| 357 | ranges: &[(u64, u64)], |
| 358 | output: &mut std::fs::File, |
| 359 | selected: Option<usize>, |
| 360 | keys: &mut Keys<'_>, |
| 361 | check: &mut impl crate::resources::Monitor, |
| 362 | ) -> Result<()> { |
| 363 | use std::io::{Read, Seek, SeekFrom}; |
| 364 | let total = self |
| 365 | .folders |
| 366 | .iter() |
| 367 | .enumerate() |
| 368 | .filter(|(index, _)| selected.is_none_or(|id| id == *index)) |
| 369 | .try_fold(0u64, |sum, (_, f)| { |
| 370 | crate::resources::completed( |
| 371 | sum.checked_add(f.size as u64).ok_or(ErrorCode::Limit), |
| 372 | check, |
| 373 | ) |
| 374 | })?; |
| 375 | crate::space::ensure(output, total)?; |
| 376 | for (index, (f, (start, size))) in self.folders.iter().zip(ranges).enumerate() { |
| 377 | check.check()?; |
| 378 | if selected.is_some_and(|id| id != index) { |
| 379 | crate::resources::completed(Ok(()), check)?; |
| 380 | continue; |
| 381 | } |
| 382 | let base = output.stream_position().map_err(crate::space::io_error)?; |
| 383 | check.observe( |
| 384 | ResourceUsage { |
| 385 | compressed_bytes: Some(*size), |
| 386 | ratio_output_bytes: Some(f.size as u64), |
| 387 | ..ResourceUsage::default() |
| 388 | }, |
| 389 | Some(output), |
| 390 | )?; |
| 391 | input |
| 392 | .seek(SeekFrom::Start(*start)) |
| 393 | .map_err(crate::space::io_error)?; |
| 394 | match &f.encryption { |
| 395 | None => decode_folder(input, *size, f, output, base, check)?, |
| 396 | Some(aes) => { |
| 397 | let key = keys.key(aes, check)?; |
| 398 | let mut reader = crate::crypto::SevenZipReader::new( |
| 399 | input.by_ref().take(*size), |
| 400 | *size, |
| 401 | f.inner as u64, |
| 402 | aes, |
| 403 | &key, |
| 404 | )?; |
| 405 | // 복호화한 뒤의 해제 실패나 CRC 불일치는 틀린 암호로 보고함. LZMA2는 청크 |
| 406 | // 머리의 속성도 암호문에서 나오므로 미지원 속성도 틀린 암호로 봄. |
| 407 | decode_folder(&mut reader, f.inner as u64, f, output, base, check).map_err( |
| 408 | |error| match error { |
| 409 | ErrorCode::Integrity => ErrorCode::WrongPassword, |
| 410 | ErrorCode::UnsupportedFeature if f.method == [0x21] => { |
| 411 | ErrorCode::WrongPassword |
| 412 | } |
| 413 | error => error, |
| 414 | }, |
| 415 | )? |
| 416 | } |
| 417 | } |
| 418 | } |
| 419 | Ok(()) |
| 420 | } |
| 421 | } |
| 422 | /// 한 번 여는 동안 받은 암호와, 같은 반복 횟수와 솔트로 이미 유도한 키를 보관함. |
| 423 | pub(crate) struct Keys<'a> { |
| 424 | password: Option<&'a [u8]>, |
| 425 | cached: Option<(crate::crypto::SevenZipAes, zeroize::Zeroizing<[u8; 32]>)>, |
| 426 | } |
| 427 | impl<'a> Keys<'a> { |
| 428 | fn new(password: Option<&'a [u8]>) -> Self { |
| 429 | Self { |
| 430 | password, |
| 431 | cached: None, |
| 432 | } |
| 433 | } |
| 434 | fn key( |
| 435 | &mut self, |
| 436 | aes: &crate::crypto::SevenZipAes, |
| 437 | check: &mut impl crate::resources::Monitor, |
| 438 | ) -> Result<zeroize::Zeroizing<[u8; 32]>> { |
| 439 | if let Some((known, key)) = &self.cached { |
| 440 | if known.same_key(aes) { |
| 441 | return Ok(key.clone()); |
| 442 | } |
| 443 | } |
| 444 | // 암호 없이 암호 폴더를 만나면 호출자가 암호를 물어 다시 열도록 틀린 암호로 보고함. |
| 445 | let key = aes.key(self.password.ok_or(ErrorCode::WrongPassword)?, check)?; |
| 446 | self.cached = Some((aes.clone(), key.clone())); |
| 447 | Ok(key) |
| 448 | } |
| 449 | } |
| 450 | fn decode_folder( |
| 451 | input: &mut impl std::io::Read, |
| 452 | size: u64, |
| 453 | f: &Folder, |
| 454 | output: &mut std::fs::File, |
| 455 | base: u64, |
| 456 | check: &mut impl crate::resources::Monitor, |
| 457 | ) -> Result<()> { |
| 458 | use std::io::{Seek, SeekFrom, Write}; |
| 459 | match f.method.as_slice() { |
| 460 | [0] => { |
| 461 | if !f.properties.is_empty() || size != f.size as u64 { |
| 462 | return Err(ErrorCode::Integrity); |
| 463 | } |
| 464 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 465 | let mut remaining = size; |
| 466 | while remaining != 0 { |
| 467 | check.check()?; |
| 468 | let n = remaining.min(buffer.len() as u64) as usize; |
| 469 | input |
| 470 | .read_exact(&mut buffer[..n]) |
| 471 | .map_err(|_| ErrorCode::Integrity)?; |
| 472 | crate::space::ensure(output, n as u64)?; |
| 473 | output |
| 474 | .write_all(&buffer[..n]) |
| 475 | .map_err(crate::space::io_error)?; |
| 476 | remaining -= n as u64; |
| 477 | crate::resources::completed(Ok(()), check)?; |
| 478 | } |
| 479 | } |
| 480 | [3, 1, 1] | [0x21] => crate::lzma::decode_stream( |
| 481 | input, |
| 482 | size, |
| 483 | &f.properties, |
| 484 | f.method == [0x21], |
| 485 | f.size as u64, |
| 486 | output, |
| 487 | check, |
| 488 | )?, |
| 489 | _ => return Err(ErrorCode::UnsupportedFeature), |
| 490 | } |
| 491 | let single = f.sizes.len() == 1 && f.sizes[0] == f.size; |
| 492 | let folder_crc = if f.crc.is_some() || single && f.crcs[0].is_some() { |
| 493 | Some(digest(output, base, f.size as u64, check)?) |
| 494 | } else { |
| 495 | None |
| 496 | }; |
| 497 | if f.crc.is_some() && f.crc != folder_crc { |
| 498 | return Err(ErrorCode::Integrity); |
| 499 | } |
| 500 | let mut at = base; |
| 501 | for (size, expected) in f.sizes.iter().zip(&f.crcs) { |
| 502 | if let Some(expected) = expected { |
| 503 | let actual = if single { |
| 504 | folder_crc.ok_or(ErrorCode::Internal)? |
| 505 | } else { |
| 506 | digest(output, at, *size as u64, check)? |
| 507 | }; |
| 508 | if actual != *expected { |
| 509 | return Err(ErrorCode::Integrity); |
| 510 | } |
| 511 | } |
| 512 | at = at.checked_add(*size as u64).ok_or(ErrorCode::Integrity)?; |
| 513 | crate::resources::completed(Ok(()), check)?; |
| 514 | } |
| 515 | crate::resources::completed( |
| 516 | output |
| 517 | .seek(SeekFrom::Start(base + f.size as u64)) |
| 518 | .map_err(crate::space::io_error), |
| 519 | check, |
| 520 | )?; |
| 521 | Ok(()) |
| 522 | } |
| 523 | fn digest( |
| 524 | file: &mut (impl std::io::Read + std::io::Seek), |
| 525 | start: u64, |
| 526 | size: u64, |
| 527 | check: &mut impl crate::resources::Monitor, |
| 528 | ) -> Result<u32> { |
| 529 | use std::io::SeekFrom; |
| 530 | file.seek(SeekFrom::Start(start)) |
| 531 | .map_err(crate::space::io_error)?; |
| 532 | let mut crc = 0; |
| 533 | let mut remaining = size; |
| 534 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 535 | while remaining != 0 { |
| 536 | check.check()?; |
| 537 | let n = remaining.min(buffer.len() as u64) as usize; |
| 538 | file.read_exact(&mut buffer[..n]) |
| 539 | .map_err(crate::space::io_error)?; |
| 540 | crc = crc32(crc, &buffer[..n]); |
| 541 | remaining -= n as u64; |
| 542 | crate::resources::completed(Ok(()), check)?; |
| 543 | } |
| 544 | Ok(crc) |
| 545 | } |
| 546 | fn files( |
| 547 | r: &mut Reader<'_>, |
| 548 | limits: Limits, |
| 549 | streams: Option<&Streams>, |
| 550 | check: &mut impl crate::resources::Monitor, |
| 551 | ) -> Result<(Vec<Member>, Vec<usize>)> { |
| 552 | let count = r.number(limits.entries as usize)?; |
| 553 | let mut empty = vec![false; count]; |
| 554 | let mut empty_file = Vec::new(); |
| 555 | let mut names = None; |
| 556 | let mut attrs = vec![None; count]; |
| 557 | let mut seen = BTreeSet::new(); |
| 558 | loop { |
| 559 | let property = r.byte()?; |
| 560 | if property == 0 { |
| 561 | break; |
| 562 | } |
| 563 | // 7-Zip은 정렬용 kDummy(25)를 한 헤더에 여러 번 쓸 수 있음. |
| 564 | if property != 25 && !seen.insert(property) { |
| 565 | return Err(ErrorCode::Integrity); |
| 566 | } |
| 567 | let len = r.number(check.metadata_limits().bytes)?; |
| 568 | let mut value = Reader::new(r.take(len)?); |
| 569 | match property { |
| 570 | 14 => { |
| 571 | empty = value.bits(count)?; |
| 572 | } |
| 573 | 15 => { |
| 574 | empty_file = value.bits(empty.iter().filter(|e| **e).count())?; |
| 575 | } |
| 576 | 16 => { |
| 577 | if value |
| 578 | .bits(empty.iter().filter(|e| **e).count())? |
| 579 | .iter() |
| 580 | .any(|b| *b) |
| 581 | { |
| 582 | return Err(ErrorCode::UnsupportedFeature); |
| 583 | } |
| 584 | } |
| 585 | 17 => { |
| 586 | if value.byte()? != 0 { |
| 587 | return Err(ErrorCode::UnsupportedFeature); |
| 588 | } |
| 589 | let mut decoded = Vec::new(); |
| 590 | let mut budget = MetadataBudget::default(); |
| 591 | for _ in 0..count { |
| 592 | check.check()?; |
| 593 | let mut units = Vec::new(); |
| 594 | loop { |
| 595 | let n = u16::from_le_bytes(value.take(2)?.try_into().unwrap()); |
| 596 | if n == 0 { |
| 597 | break; |
| 598 | } |
| 599 | if units.len() >= 4096 { |
| 600 | return Err(ErrorCode::Limit); |
| 601 | } |
| 602 | units.push(n); |
| 603 | } |
| 604 | let name = String::from_utf16(&units).map_err(|_| ErrorCode::Integrity)?; |
| 605 | budget.charge_with(&name, check.metadata_limits())?; |
| 606 | decoded.push(name); |
| 607 | crate::resources::completed(Ok(()), check)?; |
| 608 | } |
| 609 | names = Some(decoded); |
| 610 | } |
| 611 | 21 => { |
| 612 | let defined = value.defined(count)?; |
| 613 | if value.byte()? != 0 { |
| 614 | return Err(ErrorCode::UnsupportedFeature); |
| 615 | } |
| 616 | for (attr, set) in attrs.iter_mut().zip(defined) { |
| 617 | if set { |
| 618 | *attr = Some(u32::from_le_bytes(value.take(4)?.try_into().unwrap())); |
| 619 | } |
| 620 | crate::resources::completed(Ok(()), check)?; |
| 621 | } |
| 622 | } |
| 623 | 18..=20 => { |
| 624 | let defined = value.defined(count)?; |
| 625 | if value.byte()? != 0 { |
| 626 | return Err(ErrorCode::UnsupportedFeature); |
| 627 | } |
| 628 | value.take(defined.iter().filter(|b| **b).count() * 8)?; |
| 629 | } |
| 630 | 25 => { |
| 631 | if value.take(len)?.iter().any(|b| *b != 0) { |
| 632 | return Err(ErrorCode::Integrity); |
| 633 | } |
| 634 | } |
| 635 | _ => return Err(ErrorCode::UnsupportedFeature), |
| 636 | } |
| 637 | value.end()?; |
| 638 | } |
| 639 | let names = names.unwrap_or_default(); |
| 640 | if names.len() != count { |
| 641 | return Err(ErrorCode::Integrity); |
| 642 | } |
| 643 | if !empty_file.is_empty() && empty_file.len() != empty.iter().filter(|e| **e).count() { |
| 644 | return Err(ErrorCode::Integrity); |
| 645 | } |
| 646 | let mut descriptions = Vec::new(); |
| 647 | if let Some(streams) = streams { |
| 648 | for (folder, compressed) in streams.folders.iter().zip(&streams.packed) { |
| 649 | for (i, size) in folder.sizes.iter().enumerate() { |
| 650 | descriptions.push(( |
| 651 | *size, |
| 652 | if i == 0 { *compressed } else { 0 }, |
| 653 | folder.encryption.is_some(), |
| 654 | )); |
| 655 | crate::resources::completed(Ok(()), check)?; |
| 656 | } |
| 657 | } |
| 658 | } |
| 659 | let mut descriptions = descriptions.into_iter(); |
| 660 | let mut empty_flags = empty_file.into_iter(); |
| 661 | let mut members = Vec::new(); |
| 662 | let mut stream_indices = Vec::new(); |
| 663 | for (index, ((name, empty), attr)) in names.into_iter().zip(empty).zip(attrs).enumerate() { |
| 664 | let kind = if empty && !empty_flags.next().unwrap_or(false) { |
| 665 | EntryKind::Directory |
| 666 | } else { |
| 667 | EntryKind::File |
| 668 | }; |
| 669 | if let Some(attr) = attr { |
| 670 | let mode = attr >> 16; |
| 671 | if attr & 0x400 != 0 |
| 672 | || (attr & 0x8000 != 0 && !matches!(mode & 0xf000, 0 | 0x4000 | 0x8000)) |
| 673 | { |
| 674 | return Err(ErrorCode::UnsafePath); |
| 675 | } |
| 676 | if (attr & 0x10 != 0 || attr & 0x8000 != 0 && mode & 0xf000 == 0x4000) |
| 677 | && kind != EntryKind::Directory |
| 678 | { |
| 679 | return Err(ErrorCode::Integrity); |
| 680 | } |
| 681 | } |
| 682 | let name = valid_name(&name, kind == EntryKind::Directory)?; |
| 683 | if !empty { |
| 684 | stream_indices.push(index); |
| 685 | } |
| 686 | let (size, compressed_size, encrypted) = if empty { |
| 687 | (0, 0, false) |
| 688 | } else { |
| 689 | descriptions.next().ok_or(ErrorCode::Integrity)? |
| 690 | }; |
| 691 | members.push(Member { |
| 692 | entry: Entry { |
| 693 | entry_id: index as u32, |
| 694 | name, |
| 695 | kind, |
| 696 | size: size as u64, |
| 697 | compressed_size: compressed_size as u64, |
| 698 | encrypted, |
| 699 | }, |
| 700 | data: Vec::new(), |
| 701 | }); |
| 702 | crate::resources::completed(Ok(()), check)?; |
| 703 | } |
| 704 | if descriptions.next().is_some() { |
| 705 | return Err(ErrorCode::Integrity); |
| 706 | } |
| 707 | validate_members_with(&members, check)?; |
| 708 | Ok((members, stream_indices)) |
| 709 | } |
| 710 | pub(crate) fn open( |
| 711 | input: &mut (impl std::io::Read + std::io::Seek), |
| 712 | length: u64, |
| 713 | limits: Limits, |
| 714 | decode: bool, |
| 715 | check: &mut impl crate::resources::Monitor, |
| 716 | ) -> Result<crate::streaming::Catalog> { |
| 717 | open_selected(input, length, limits, decode, None, None, check) |
| 718 | } |
| 719 | /// 암호화된 헤더나 항목을 받은 암호로 엶. 암호가 필요한데 없으면 WrongPassword를 돌려줌. |
| 720 | pub(crate) fn open_with_password( |
| 721 | input: &mut (impl std::io::Read + std::io::Seek), |
| 722 | length: u64, |
| 723 | limits: Limits, |
| 724 | password: Option<&[u8]>, |
| 725 | check: &mut impl crate::resources::Monitor, |
| 726 | ) -> Result<crate::streaming::Catalog> { |
| 727 | open_selected(input, length, limits, false, password, None, check) |
| 728 | } |
| 729 | pub(crate) fn open_selected( |
| 730 | input: &mut (impl std::io::Read + std::io::Seek), |
| 731 | length: u64, |
| 732 | limits: Limits, |
| 733 | decode: bool, |
| 734 | password: Option<&[u8]>, |
| 735 | selected: Option<u32>, |
| 736 | check: &mut impl crate::resources::Monitor, |
| 737 | ) -> Result<crate::streaming::Catalog> { |
| 738 | use std::io::{Read, Seek, SeekFrom}; |
| 739 | check.check()?; |
| 740 | let mut keys = Keys::new(password); |
| 741 | if length > limits.input { |
| 742 | return Err(ErrorCode::Limit); |
| 743 | } |
| 744 | input.rewind().map_err(crate::space::io_error)?; |
| 745 | let mut header = [0; 32]; |
| 746 | input |
| 747 | .read_exact(&mut header) |
| 748 | .map_err(|_| ErrorCode::Integrity)?; |
| 749 | if &header[..6] != b"7z\xbc\xaf\x27\x1c" { |
| 750 | return Err(ErrorCode::Integrity); |
| 751 | } |
| 752 | if header[6] != 0 || header[7] > 4 { |
| 753 | return Err(ErrorCode::UnsupportedFeature); |
| 754 | } |
| 755 | if crc32(0, &header[12..32]) != u32::from_le_bytes(header[8..12].try_into().unwrap()) { |
| 756 | return Err(ErrorCode::Integrity); |
| 757 | } |
| 758 | let offset = u64::from_le_bytes(header[12..20].try_into().unwrap()); |
| 759 | let len = u64::from_le_bytes(header[20..28].try_into().unwrap()); |
| 760 | if len > check.metadata_limits().bytes as u64 { |
| 761 | return Err(ErrorCode::Limit); |
| 762 | } |
| 763 | let start = offset.checked_add(32).ok_or(ErrorCode::Integrity)?; |
| 764 | if start.checked_add(len) != Some(length) { |
| 765 | return Err(ErrorCode::Integrity); |
| 766 | } |
| 767 | input |
| 768 | .seek(SeekFrom::Start(start)) |
| 769 | .map_err(crate::space::io_error)?; |
| 770 | let mut bytes = vec![0; len as usize]; |
| 771 | input |
| 772 | .read_exact(&mut bytes) |
| 773 | .map_err(|_| ErrorCode::Integrity)?; |
| 774 | if crc32(0, &bytes) != u32::from_le_bytes(header[28..32].try_into().unwrap()) { |
| 775 | return Err(ErrorCode::Integrity); |
| 776 | } |
| 777 | let mut data = crate::spool::temporary()?; |
| 778 | if bytes.is_empty() { |
| 779 | if start != 32 { |
| 780 | return Err(ErrorCode::Integrity); |
| 781 | } |
| 782 | return Ok(crate::streaming::Catalog { |
| 783 | format: Format::SevenZip, |
| 784 | members: Vec::new(), |
| 785 | offsets: Vec::new(), |
| 786 | data, |
| 787 | }); |
| 788 | } |
| 789 | let mut data_end = start; |
| 790 | if bytes[0] == 23 { |
| 791 | let mut r = Reader::new(&bytes[1..]); |
| 792 | let header_limits = Limits { |
| 793 | output: check.metadata_limits().bytes as u64, |
| 794 | ..limits |
| 795 | }; |
| 796 | let streams = Streams::read(&mut r, header_limits, check)?; |
| 797 | r.end()?; |
| 798 | if streams.folders.len() != 1 || streams.folders[0].sizes.len() != 1 { |
| 799 | return Err(ErrorCode::UnsupportedFeature); |
| 800 | } |
| 801 | let ranges = streams.ranges(input, data_end, check)?; |
| 802 | streams.decode_file( |
| 803 | input, |
| 804 | &ranges, |
| 805 | &mut data, |
| 806 | None, |
| 807 | &mut keys, |
| 808 | &mut crate::resources::MetadataMonitor(check), |
| 809 | )?; |
| 810 | data_end = 32u64 |
| 811 | .checked_add(streams.position as u64) |
| 812 | .ok_or(ErrorCode::Integrity)?; |
| 813 | data.rewind().map_err(crate::space::io_error)?; |
| 814 | bytes.clear(); |
| 815 | data.read_to_end(&mut bytes) |
| 816 | .map_err(crate::space::io_error)?; |
| 817 | data = crate::spool::temporary()?; |
| 818 | } |
| 819 | let mut r = Reader::new(&bytes); |
| 820 | r.expect(1)?; |
| 821 | let mut streams = None; |
| 822 | let mut tag = r.byte()?; |
| 823 | if tag == 2 { |
| 824 | while r.byte()? != 0 { |
| 825 | let len = r.number(check.metadata_limits().bytes)?; |
| 826 | r.take(len)?; |
| 827 | } |
| 828 | tag = r.byte()?; |
| 829 | } |
| 830 | if tag == 3 { |
| 831 | return Err(ErrorCode::UnsupportedFeature); |
| 832 | } |
| 833 | if tag == 4 { |
| 834 | streams = Some(Streams::read(&mut r, limits, check)?); |
| 835 | tag = r.byte()?; |
| 836 | } |
| 837 | let (members, stream_indices) = if tag == 5 { |
| 838 | let f = files(&mut r, limits, streams.as_ref(), check)?; |
| 839 | tag = r.byte()?; |
| 840 | f |
| 841 | } else { |
| 842 | (Vec::new(), Vec::new()) |
| 843 | }; |
| 844 | if tag != 0 { |
| 845 | return Err(ErrorCode::Integrity); |
| 846 | } |
| 847 | r.end()?; |
| 848 | let total = members.iter().try_fold(0u64, |n, m| { |
| 849 | crate::resources::completed(n.checked_add(m.entry.size).ok_or(ErrorCode::Limit), check) |
| 850 | })?; |
| 851 | let packed = streams |
| 852 | .as_ref() |
| 853 | .map(|s| { |
| 854 | s.packed.iter().try_fold(0u64, |sum, size| { |
| 855 | crate::resources::completed( |
| 856 | sum.checked_add(*size as u64).ok_or(ErrorCode::Integrity), |
| 857 | check, |
| 858 | ) |
| 859 | }) |
| 860 | }) |
| 861 | .transpose()?; |
| 862 | check.observe( |
| 863 | ResourceUsage { |
| 864 | estimated_bytes: Some(total), |
| 865 | estimated_entries: Some(members.len() as u32), |
| 866 | compressed_bytes: packed, |
| 867 | ratio_output_bytes: Some(total), |
| 868 | ..ResourceUsage::default() |
| 869 | }, |
| 870 | Some(&data), |
| 871 | )?; |
| 872 | crate::resources::completed(Ok(()), check)?; |
| 873 | let mut offsets = vec![0; members.len()]; |
| 874 | if let Some(streams) = streams { |
| 875 | if streams.folders.iter().map(|f| f.sizes.len()).sum::<usize>() != stream_indices.len() { |
| 876 | return Err(ErrorCode::Integrity); |
| 877 | } |
| 878 | let ranges = streams.ranges(input, data_end, check)?; |
| 879 | let mut at = 0u64; |
| 880 | let mut ids = stream_indices.into_iter(); |
| 881 | let mut selected_folder = None; |
| 882 | for (folder, f) in streams.folders.iter().enumerate() { |
| 883 | let base = at; |
| 884 | for size in &f.sizes { |
| 885 | let id = ids.next().ok_or(ErrorCode::Integrity)?; |
| 886 | offsets[id] = if selected.is_some() { at - base } else { at }; |
| 887 | if selected == Some(id as u32) { |
| 888 | selected_folder = Some(folder); |
| 889 | } |
| 890 | at = at.checked_add(*size as u64).ok_or(ErrorCode::Limit)?; |
| 891 | crate::resources::completed(Ok(()), check)?; |
| 892 | } |
| 893 | } |
| 894 | if at > limits.output { |
| 895 | return Err(ErrorCode::Limit); |
| 896 | } |
| 897 | if decode && (selected.is_none() || selected_folder.is_some()) { |
| 898 | streams.decode_file(input, &ranges, &mut data, selected_folder, &mut keys, check)?; |
| 899 | } |
| 900 | } |
| 901 | Ok(crate::streaming::Catalog { |
| 902 | format: Format::SevenZip, |
| 903 | members, |
| 904 | offsets, |
| 905 | data, |
| 906 | }) |
| 907 | } |