| 1 | use crate::{create::Plan, protocol::*, resources::Monitor, spool}; |
| 2 | use lzma_rust2::{Lzma2Options, Lzma2Writer}; |
| 3 | use std::{ |
| 4 | fs::File, |
| 5 | io::{Read, Seek, SeekFrom, Write}, |
| 6 | time::{Duration, Instant}, |
| 7 | }; |
| 8 | use zlib_rs::crc32::crc32; |
| 9 | |
| 10 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 11 | const DICTIONARY: u32 = 1024 * 1024; |
| 12 | const DICTIONARY_PROPERTY: u8 = 16; |
| 13 | |
| 14 | fn io<T>(value: std::io::Result<T>) -> Result<T> { |
| 15 | value.map_err(crate::space::io_error) |
| 16 | } |
| 17 | fn options() -> Result<Lzma2Options> { |
| 18 | let mut options = Lzma2Options::with_preset(1); |
| 19 | options.lzma_options.dict_size = DICTIONARY; |
| 20 | let memory = u64::from(options.lzma_options.get_memory_usage()) |
| 21 | .checked_mul(1024) |
| 22 | .ok_or(ErrorCode::Limit)?; |
| 23 | if memory > 32 * 1024 * 1024 { |
| 24 | return Err(ErrorCode::Limit); |
| 25 | } |
| 26 | Ok(options) |
| 27 | } |
| 28 | fn packed_bound(length: u64) -> Result<u64> { |
| 29 | // 한 바이트 이상인 청크의 최대 순증 3바이트와 마지막 종료 바이트를 포함함. |
| 30 | length |
| 31 | .checked_mul(4) |
| 32 | .and_then(|n| n.checked_add(1)) |
| 33 | .ok_or(ErrorCode::Limit) |
| 34 | } |
| 35 | |
| 36 | #[derive(Clone, Copy)] |
| 37 | struct Stream { |
| 38 | size: u64, |
| 39 | packed: u64, |
| 40 | crc: u32, |
| 41 | packed_crc: u32, |
| 42 | } |
| 43 | struct Sink<'a, M> { |
| 44 | file: &'a mut File, |
| 45 | check: &'a mut M, |
| 46 | error: Option<ErrorCode>, |
| 47 | written: u64, |
| 48 | bound: u64, |
| 49 | crc: u32, |
| 50 | base: u64, |
| 51 | entries: u32, |
| 52 | reported: Instant, |
| 53 | } |
| 54 | impl<M: Monitor> Write for Sink<'_, M> { |
| 55 | fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { |
| 56 | let result = (|| { |
| 57 | self.check.check()?; |
| 58 | let bytes = &bytes[..bytes.len().min(65_536)]; |
| 59 | let end = self |
| 60 | .written |
| 61 | .checked_add(bytes.len() as u64) |
| 62 | .ok_or(ErrorCode::Limit)?; |
| 63 | if end > self.bound { |
| 64 | return Err(ErrorCode::Limit); |
| 65 | } |
| 66 | crate::space::ensure(self.file, bytes.len() as u64)?; |
| 67 | let n = io(self.file.write(bytes))?; |
| 68 | self.written += n as u64; |
| 69 | self.crc = crc32(self.crc, &bytes[..n]); |
| 70 | if n != 0 { |
| 71 | crate::resources::completed(Ok(()), self.check)?; |
| 72 | if self.reported.elapsed() >= Duration::from_millis(100) { |
| 73 | self.check.progress( |
| 74 | Stage::Write, |
| 75 | self.base + self.written, |
| 76 | None, |
| 77 | self.entries, |
| 78 | )?; |
| 79 | self.reported = Instant::now(); |
| 80 | } |
| 81 | } |
| 82 | Ok(n) |
| 83 | })(); |
| 84 | result.map_err(|error| { |
| 85 | self.error = Some(error); |
| 86 | std::io::Error::other("7z stream write failed") |
| 87 | }) |
| 88 | } |
| 89 | fn flush(&mut self) -> std::io::Result<()> { |
| 90 | self.file.flush() |
| 91 | } |
| 92 | } |
| 93 | fn pack( |
| 94 | input: &mut File, |
| 95 | length: u64, |
| 96 | output: &mut File, |
| 97 | entries: u32, |
| 98 | check: &mut impl Monitor, |
| 99 | ) -> Result<Stream> { |
| 100 | let settings = options()?; |
| 101 | let base = io(output.stream_position())? |
| 102 | .checked_sub(32) |
| 103 | .ok_or(ErrorCode::Internal)?; |
| 104 | let mut sink = Sink { |
| 105 | file: output, |
| 106 | check, |
| 107 | error: None, |
| 108 | written: 0, |
| 109 | bound: packed_bound(length)?, |
| 110 | crc: 0, |
| 111 | base, |
| 112 | entries, |
| 113 | reported: Instant::now(), |
| 114 | }; |
| 115 | let result = (|| { |
| 116 | io(input.rewind())?; |
| 117 | let mut input = input.take(length); |
| 118 | let mut encoder = Lzma2Writer::new(&mut sink, settings); |
| 119 | let mut buffer = [0; 65_536]; |
| 120 | let mut read = 0u64; |
| 121 | let mut crc = 0; |
| 122 | loop { |
| 123 | encoder.inner_mut().check.check()?; |
| 124 | let n = io(input.read(&mut buffer))?; |
| 125 | if n == 0 { |
| 126 | break; |
| 127 | } |
| 128 | crate::resources::completed(Ok(()), encoder.inner_mut().check)?; |
| 129 | read = read.checked_add(n as u64).ok_or(ErrorCode::Limit)?; |
| 130 | crc = crc32(crc, &buffer[..n]); |
| 131 | io(encoder.write_all(&buffer[..n]))?; |
| 132 | } |
| 133 | if read != length { |
| 134 | return Err(ErrorCode::SourceChanged); |
| 135 | } |
| 136 | encoder.inner_mut().check.check()?; |
| 137 | io(encoder.finish())?; |
| 138 | Ok(crc) |
| 139 | })(); |
| 140 | if let Some(error) = sink.error { |
| 141 | return Err(error); |
| 142 | } |
| 143 | let crc = result?; |
| 144 | sink.check.check()?; |
| 145 | sink.check |
| 146 | .progress(Stage::Write, base + sink.written, None, entries)?; |
| 147 | Ok(Stream { |
| 148 | size: length, |
| 149 | packed: sink.written, |
| 150 | crc, |
| 151 | packed_crc: sink.crc, |
| 152 | }) |
| 153 | } |
| 154 | |
| 155 | struct Header(Vec<u8>); |
| 156 | impl Header { |
| 157 | fn new(capacity: usize) -> Result<Self> { |
| 158 | let mut bytes = Vec::new(); |
| 159 | bytes |
| 160 | .try_reserve_exact(capacity) |
| 161 | .map_err(|_| ErrorCode::Limit)?; |
| 162 | Ok(Self(bytes)) |
| 163 | } |
| 164 | fn put(&mut self, bytes: &[u8]) { |
| 165 | self.0.extend_from_slice(bytes); |
| 166 | } |
| 167 | fn integer(&mut self, value: u64) { |
| 168 | for extra in 0..8 { |
| 169 | if value < (1u64 << (7 * (extra + 1))) { |
| 170 | let prefix = if extra == 0 { 0 } else { 0xffu8 << (8 - extra) }; |
| 171 | self.0.push(prefix | (value >> (8 * extra)) as u8); |
| 172 | self.put(&value.to_le_bytes()[..extra]); |
| 173 | return; |
| 174 | } |
| 175 | } |
| 176 | self.0.push(0xff); |
| 177 | self.put(&value.to_le_bytes()); |
| 178 | } |
| 179 | fn property(&mut self, id: u8, size: usize) { |
| 180 | self.0.push(id); |
| 181 | self.integer(size as u64); |
| 182 | } |
| 183 | fn bits(&mut self, values: impl Iterator<Item = bool>) { |
| 184 | let mut byte = 0; |
| 185 | let mut used = 0; |
| 186 | for value in values { |
| 187 | if value { |
| 188 | byte |= 0x80 >> used; |
| 189 | } |
| 190 | used += 1; |
| 191 | if used == 8 { |
| 192 | self.0.push(byte); |
| 193 | byte = 0; |
| 194 | used = 0; |
| 195 | } |
| 196 | } |
| 197 | if used != 0 { |
| 198 | self.0.push(byte); |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | fn empty(item: &crate::create_sources::Planned) -> bool { |
| 203 | item.member.entry.size == 0 |
| 204 | } |
| 205 | fn header( |
| 206 | plan: &Plan, |
| 207 | streams: &[Stream], |
| 208 | names: usize, |
| 209 | capacity: usize, |
| 210 | check: &mut impl Monitor, |
| 211 | ) -> Result<Header> { |
| 212 | let mut out = Header::new(capacity)?; |
| 213 | out.put(&[1]); |
| 214 | if !streams.is_empty() { |
| 215 | out.put(&[4, 6, 0]); |
| 216 | out.integer(streams.len() as u64); |
| 217 | out.put(&[9]); |
| 218 | for stream in streams { |
| 219 | out.integer(stream.packed); |
| 220 | check.check()?; |
| 221 | } |
| 222 | out.put(&[10, 1]); |
| 223 | for stream in streams { |
| 224 | out.put(&stream.packed_crc.to_le_bytes()); |
| 225 | } |
| 226 | out.put(&[0, 7, 11]); |
| 227 | out.integer(streams.len() as u64); |
| 228 | out.put(&[0]); |
| 229 | for _ in streams { |
| 230 | out.put(&[1, 0x21, 0x21, 1, DICTIONARY_PROPERTY]); |
| 231 | check.check()?; |
| 232 | } |
| 233 | out.put(&[12]); |
| 234 | for stream in streams { |
| 235 | out.integer(stream.size); |
| 236 | } |
| 237 | out.put(&[10, 1]); |
| 238 | for stream in streams { |
| 239 | out.put(&stream.crc.to_le_bytes()); |
| 240 | } |
| 241 | out.put(&[0, 8, 0, 0]); |
| 242 | } |
| 243 | out.put(&[5]); |
| 244 | out.integer(plan.items.len() as u64); |
| 245 | let empties = plan.items.iter().filter(|p| empty(p)).count(); |
| 246 | if empties != 0 { |
| 247 | out.property(14, plan.items.len().div_ceil(8)); |
| 248 | out.bits(plan.items.iter().map(empty)); |
| 249 | out.property(15, empties.div_ceil(8)); |
| 250 | out.bits( |
| 251 | plan.items |
| 252 | .iter() |
| 253 | .filter(|p| empty(p)) |
| 254 | .map(|p| p.member.entry.kind == EntryKind::File), |
| 255 | ); |
| 256 | } |
| 257 | out.property(17, names.checked_add(1).ok_or(ErrorCode::Limit)?); |
| 258 | out.put(&[0]); |
| 259 | for item in &plan.items { |
| 260 | for unit in item |
| 261 | .member |
| 262 | .entry |
| 263 | .name |
| 264 | .encode_utf16() |
| 265 | .chain(std::iter::once(0)) |
| 266 | { |
| 267 | out.put(&unit.to_le_bytes()); |
| 268 | } |
| 269 | crate::resources::completed(Ok(()), check)?; |
| 270 | } |
| 271 | out.property( |
| 272 | 21, |
| 273 | plan.items |
| 274 | .len() |
| 275 | .checked_mul(4) |
| 276 | .and_then(|n| n.checked_add(2)) |
| 277 | .ok_or(ErrorCode::Limit)?, |
| 278 | ); |
| 279 | out.put(&[1, 0]); |
| 280 | for item in &plan.items { |
| 281 | let attributes: u32 = if item.member.entry.kind == EntryKind::Directory { |
| 282 | 0x10 |
| 283 | } else { |
| 284 | 0x20 |
| 285 | }; |
| 286 | out.put(&attributes.to_le_bytes()); |
| 287 | check.check()?; |
| 288 | } |
| 289 | out.put(&[0, 0]); |
| 290 | if out.0.len() > capacity { |
| 291 | return Err(ErrorCode::Internal); |
| 292 | } |
| 293 | Ok(out) |
| 294 | } |
| 295 | fn write(output: &mut File, bytes: &[u8], check: &mut impl Monitor) -> Result<()> { |
| 296 | for chunk in bytes.chunks(65_536) { |
| 297 | check.check()?; |
| 298 | crate::space::ensure(output, chunk.len() as u64)?; |
| 299 | io(output.write_all(chunk))?; |
| 300 | crate::resources::completed(Ok(()), check)?; |
| 301 | } |
| 302 | Ok(()) |
| 303 | } |
| 304 | struct Verify<'a, M>(&'a mut M); |
| 305 | impl<M: Monitor> Monitor for Verify<'_, M> { |
| 306 | fn metadata_limits(&self) -> crate::archive::MetadataLimits { |
| 307 | self.0.metadata_limits() |
| 308 | } |
| 309 | fn check(&mut self) -> Result<()> { |
| 310 | self.0.check() |
| 311 | } |
| 312 | fn activity(&mut self) -> Result<()> { |
| 313 | self.0.activity() |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | pub(crate) fn archive( |
| 318 | plan: &mut Plan, |
| 319 | limits: Limits, |
| 320 | check: &mut impl Monitor, |
| 321 | ) -> Result<(File, u64)> { |
| 322 | if plan.items.is_empty() { |
| 323 | return Err(ErrorCode::InvalidRequest); |
| 324 | } |
| 325 | let mut names = 0usize; |
| 326 | let mut total = 0u64; |
| 327 | for item in &plan.items { |
| 328 | check.check()?; |
| 329 | names = item |
| 330 | .member |
| 331 | .entry |
| 332 | .name |
| 333 | .encode_utf16() |
| 334 | .count() |
| 335 | .checked_add(1) |
| 336 | .and_then(|n| n.checked_mul(2)) |
| 337 | .and_then(|n| names.checked_add(n)) |
| 338 | .ok_or(ErrorCode::Limit)?; |
| 339 | total = total |
| 340 | .checked_add(item.member.entry.size) |
| 341 | .filter(|n| *n <= limits.input.min(limits.output)) |
| 342 | .ok_or(ErrorCode::Limit)?; |
| 343 | } |
| 344 | let capacity = plan |
| 345 | .items |
| 346 | .len() |
| 347 | .checked_mul(96) |
| 348 | .and_then(|n| n.checked_add(names)) |
| 349 | .and_then(|n| n.checked_add(128)) |
| 350 | .ok_or(ErrorCode::Limit)?; |
| 351 | // 헤더 두 사본, 검증 목록과 스트림 배열을 기존 계획 예산에 함께 반영함. |
| 352 | let metadata = capacity |
| 353 | .checked_mul(3) |
| 354 | .and_then(|n| n.checked_add(plan.items.len().checked_mul(256)?)) |
| 355 | .ok_or(ErrorCode::Limit)?; |
| 356 | plan.reserve_metadata(metadata, check)?; |
| 357 | let mut streams = Vec::new(); |
| 358 | streams |
| 359 | .try_reserve_exact(plan.items.len()) |
| 360 | .map_err(|_| ErrorCode::Limit)?; |
| 361 | let mut output = spool::temporary()?; |
| 362 | write(&mut output, &[0; 32], check)?; |
| 363 | let mut read = 0u64; |
| 364 | for (index, source) in plan.items.iter().enumerate() { |
| 365 | check.check()?; |
| 366 | let length = source.member.entry.size; |
| 367 | let mut input = crate::resources::completed(source.open(), check)?; |
| 368 | if !empty(source) { |
| 369 | let required = length |
| 370 | .checked_add(packed_bound(length)?) |
| 371 | .and_then(|n| n.checked_add(capacity as u64)) |
| 372 | .ok_or(ErrorCode::Limit)?; |
| 373 | crate::space::ensure(&output, required)?; |
| 374 | check.progress(Stage::Read, read, Some(total), index as u32)?; |
| 375 | let mut snapshot = spool::Snapshot::capture_reporting( |
| 376 | &mut input.file, |
| 377 | length, |
| 378 | &mut |step| match step { |
| 379 | spool::Step::Check => check.check(), |
| 380 | spool::Step::Activity => crate::resources::completed(Ok(()), check), |
| 381 | spool::Step::Read { bytes, .. } => { |
| 382 | check.progress(Stage::Read, read + bytes, Some(total), index as u32) |
| 383 | } |
| 384 | }, |
| 385 | )?; |
| 386 | if snapshot.len != length { |
| 387 | return Err(ErrorCode::SourceChanged); |
| 388 | } |
| 389 | check.progress( |
| 390 | Stage::Write, |
| 391 | io(output.stream_position())? - 32, |
| 392 | None, |
| 393 | index as u32, |
| 394 | )?; |
| 395 | streams.push(pack( |
| 396 | &mut snapshot.file, |
| 397 | length, |
| 398 | &mut output, |
| 399 | index as u32, |
| 400 | check, |
| 401 | )?); |
| 402 | read += length; |
| 403 | } |
| 404 | crate::resources::completed(Ok(()), check)?; |
| 405 | } |
| 406 | let at = io(output.stream_position())?; |
| 407 | let header = header(plan, &streams, names, capacity, check)?; |
| 408 | let mut start = [0; 32]; |
| 409 | start[..8].copy_from_slice(b"7z\xbc\xaf\x27\x1c\x00\x04"); |
| 410 | start[12..20].copy_from_slice(&at.checked_sub(32).ok_or(ErrorCode::Internal)?.to_le_bytes()); |
| 411 | start[20..28].copy_from_slice(&(header.0.len() as u64).to_le_bytes()); |
| 412 | start[28..32].copy_from_slice(&crc32(0, &header.0).to_le_bytes()); |
| 413 | let crc = crc32(0, &start[12..]); |
| 414 | start[8..12].copy_from_slice(&crc.to_le_bytes()); |
| 415 | write(&mut output, &header.0, check)?; |
| 416 | drop(header); |
| 417 | let length = io(output.stream_position())?; |
| 418 | check.check()?; |
| 419 | io(output.seek(SeekFrom::Start(0)))?; |
| 420 | write(&mut output, &start, check)?; |
| 421 | check.progress(Stage::Verify, 0, None, plan.items.len() as u32)?; |
| 422 | let catalog = crate::seven_zip::open( |
| 423 | &mut output, |
| 424 | length, |
| 425 | Limits { |
| 426 | input: length, |
| 427 | ..limits |
| 428 | }, |
| 429 | false, |
| 430 | &mut Verify(check), |
| 431 | )?; |
| 432 | if catalog.members.len() != plan.items.len() { |
| 433 | return Err(ErrorCode::Integrity); |
| 434 | } |
| 435 | for (actual, expected) in catalog.members.iter().zip(&plan.items) { |
| 436 | let expected = &expected.member.entry; |
| 437 | if actual.entry.name != expected.name |
| 438 | || actual.entry.kind != expected.kind |
| 439 | || actual.entry.size != expected.size |
| 440 | { |
| 441 | return Err(ErrorCode::Integrity); |
| 442 | } |
| 443 | crate::resources::completed(Ok(()), check)?; |
| 444 | } |
| 445 | drop(catalog); |
| 446 | plan.verify(check)?; |
| 447 | io(output.rewind())?; |
| 448 | Ok((output, length)) |
| 449 | } |
| 450 | |
| 451 | /// 분할 7z 볼륨 이름 (`이름.7z.001` 형식). |
| 452 | pub(crate) fn volume_name(name: &str, index: u64) -> Result<String> { |
| 453 | if !(1..=MAX_SEVEN_ZIP_VOLUMES).contains(&index) { |
| 454 | return Err(ErrorCode::Limit); |
| 455 | } |
| 456 | crate::archive::valid_name(&format!("{name}.{index:03}"), false) |
| 457 | } |
| 458 | /// 완성한 7z 길이를 볼륨 크기로 나눈 (이름, 길이) 목록. 마지막 볼륨만 짧을 수 있음. |
| 459 | /// 분할 읽기가 받는 999개를 넘거나 볼륨이 최소 크기보다 작으면 거부함. |
| 460 | pub(crate) fn volumes(name: &str, length: u64, size: u64) -> Result<Vec<(String, u64)>> { |
| 461 | if size < MIN_SEVEN_ZIP_VOLUME_BYTES || length == 0 { |
| 462 | return Err(ErrorCode::InvalidRequest); |
| 463 | } |
| 464 | let count = length.div_ceil(size); |
| 465 | if count > MAX_SEVEN_ZIP_VOLUMES { |
| 466 | return Err(ErrorCode::Limit); |
| 467 | } |
| 468 | let mut files = Vec::new(); |
| 469 | files |
| 470 | .try_reserve_exact(count as usize) |
| 471 | .map_err(|_| ErrorCode::Limit)?; |
| 472 | for index in 0..count { |
| 473 | files.push(( |
| 474 | volume_name(name, index + 1)?, |
| 475 | size.min(length - index * size), |
| 476 | )); |
| 477 | } |
| 478 | Ok(files) |
| 479 | } |
| 480 | |
| 481 | #[cfg(test)] |
| 482 | #[path = "../../../tests/rust-archive-worker/seven_zip_create_fields.rs"] |
| 483 | mod tests; |