| 1 | use crate::{ |
| 2 | create_sources::Input, |
| 3 | filesystem, |
| 4 | protocol::*, |
| 5 | spool::{Snapshot, Step}, |
| 6 | }; |
| 7 | use sha2::{Digest, Sha256}; |
| 8 | use std::{ |
| 9 | ffi::{OsStr, OsString}, |
| 10 | fs::{File, Metadata}, |
| 11 | io::{Read, Seek, Write}, |
| 12 | path::{Path, PathBuf}, |
| 13 | time::{Instant, SystemTime}, |
| 14 | }; |
| 15 | |
| 16 | const MAX_VOLUMES: usize = 999; |
| 17 | type Result<T> = std::result::Result<T, Failure>; |
| 18 | |
| 19 | #[derive(Debug)] |
| 20 | pub(crate) struct Failure { |
| 21 | pub error: ErrorCode, |
| 22 | pub problem: Option<(VolumeProblemReason, NativePath)>, |
| 23 | } |
| 24 | impl From<ErrorCode> for Failure { |
| 25 | fn from(error: ErrorCode) -> Self { |
| 26 | Self { |
| 27 | error, |
| 28 | problem: None, |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | #[cfg(unix)] |
| 34 | fn units(name: &OsStr) -> Vec<u16> { |
| 35 | use std::os::unix::ffi::OsStrExt; |
| 36 | name.as_bytes() |
| 37 | .iter() |
| 38 | .map(|byte| u16::from(*byte)) |
| 39 | .collect() |
| 40 | } |
| 41 | #[cfg(windows)] |
| 42 | fn units(name: &OsStr) -> Vec<u16> { |
| 43 | use std::os::windows::ffi::OsStrExt; |
| 44 | name.encode_wide().collect() |
| 45 | } |
| 46 | #[cfg(unix)] |
| 47 | fn native(name: &[u16]) -> OsString { |
| 48 | use std::os::unix::ffi::OsStringExt; |
| 49 | OsString::from_vec(name.iter().map(|unit| *unit as u8).collect()) |
| 50 | } |
| 51 | #[cfg(windows)] |
| 52 | fn native(name: &[u16]) -> OsString { |
| 53 | use std::os::windows::ffi::OsStringExt; |
| 54 | OsString::from_wide(name) |
| 55 | } |
| 56 | fn equal_name(left: &[u16], right: &[u16]) -> bool { |
| 57 | #[cfg(unix)] |
| 58 | { |
| 59 | left == right |
| 60 | } |
| 61 | #[cfg(windows)] |
| 62 | { |
| 63 | unsafe extern "system" { |
| 64 | fn CompareStringOrdinal( |
| 65 | a: *const u16, |
| 66 | na: i32, |
| 67 | b: *const u16, |
| 68 | nb: i32, |
| 69 | ignore_case: i32, |
| 70 | ) -> i32; |
| 71 | } |
| 72 | if left.len() > 32768 || right.len() > 32768 { |
| 73 | return false; |
| 74 | } |
| 75 | // Windows의 파일명 비교와 같은 대소문자 규칙을 사용함. |
| 76 | unsafe { |
| 77 | CompareStringOrdinal( |
| 78 | left.as_ptr(), |
| 79 | left.len() as i32, |
| 80 | right.as_ptr(), |
| 81 | right.len() as i32, |
| 82 | 1, |
| 83 | ) == 2 |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | fn number(suffix: &[u16]) -> Option<u32> { |
| 88 | if suffix.is_empty() || suffix.iter().any(|unit| !(48..=57).contains(unit)) { |
| 89 | return None; |
| 90 | } |
| 91 | Some(suffix.iter().fold(0u32, |value, digit| { |
| 92 | value |
| 93 | .saturating_mul(10) |
| 94 | .saturating_add(u32::from(*digit - 48)) |
| 95 | })) |
| 96 | } |
| 97 | struct Name { |
| 98 | prefix: Vec<u16>, |
| 99 | selected: u32, |
| 100 | width: usize, |
| 101 | } |
| 102 | impl Name { |
| 103 | fn parse(path: &Path) -> Option<Self> { |
| 104 | let name = units(path.file_name()?); |
| 105 | let dot = name.iter().rposition(|unit| *unit == 46)?; |
| 106 | let prefix = &name[..=dot]; |
| 107 | let suffix = &name[dot + 1..]; |
| 108 | if prefix.len() < 4 || !matches!(&prefix[prefix.len() - 4..], [46, 55, 90 | 122, 46]) { |
| 109 | return None; |
| 110 | } |
| 111 | Some(Self { |
| 112 | prefix: prefix.to_vec(), |
| 113 | selected: number(suffix)?, |
| 114 | width: suffix.len(), |
| 115 | }) |
| 116 | } |
| 117 | fn volume(&self, number: usize) -> NativePath { |
| 118 | let mut name = self.prefix.clone(); |
| 119 | name.extend(format!("{number:03}").bytes().map(u16::from)); |
| 120 | NativePath::from_path(Path::new(&native(&name))) |
| 121 | } |
| 122 | fn problem(&self, reason: VolumeProblemReason, index: usize) -> Failure { |
| 123 | Failure { |
| 124 | error: reason.terminal_error(), |
| 125 | problem: Some((reason, self.volume(index))), |
| 126 | } |
| 127 | } |
| 128 | fn incomplete(&self) -> Failure { |
| 129 | self.problem(VolumeProblemReason::IncompleteSet, 1) |
| 130 | } |
| 131 | } |
| 132 | pub(crate) fn is_split(path: &Path) -> bool { |
| 133 | Name::parse(path).is_some() |
| 134 | } |
| 135 | pub(crate) fn unsupported_split(path: &Path) -> bool { |
| 136 | let Some(leaf) = path.file_name() else { |
| 137 | return false; |
| 138 | }; |
| 139 | let name = units(leaf); |
| 140 | let Some(dot) = name.iter().rposition(|unit| *unit == 46) else { |
| 141 | return false; |
| 142 | }; |
| 143 | let suffix = &name[dot + 1..]; |
| 144 | let numeric = number(suffix).is_some(); |
| 145 | (numeric && dot >= 4 && matches!(&name[dot - 4..dot], [46, 90 | 122, 73 | 105, 80 | 112])) |
| 146 | || (suffix.len() == 3 && matches!(suffix[0], 90 | 122) && number(&suffix[1..]).is_some()) |
| 147 | } |
| 148 | |
| 149 | struct Part { |
| 150 | name: OsString, |
| 151 | object: SourceObject, |
| 152 | length: u64, |
| 153 | modified: SystemTime, |
| 154 | hash: [u8; 32], |
| 155 | } |
| 156 | pub(crate) struct Group { |
| 157 | parent: Input, |
| 158 | path: PathBuf, |
| 159 | object: SourceObject, |
| 160 | name: Name, |
| 161 | parts: Vec<Part>, |
| 162 | total: u64, |
| 163 | metadata_limits: crate::archive::MetadataLimits, |
| 164 | } |
| 165 | pub(crate) struct Captured { |
| 166 | pub snapshot: Snapshot, |
| 167 | pub group: Group, |
| 168 | } |
| 169 | fn metadata(file: &File) -> std::result::Result<Metadata, ErrorCode> { |
| 170 | let metadata = file.metadata().map_err(crate::space::io_error)?; |
| 171 | if !metadata.is_file() { |
| 172 | return Err(ErrorCode::UnsafePath); |
| 173 | } |
| 174 | Ok(metadata) |
| 175 | } |
| 176 | fn combined_length(total: u64, next: u64) -> Result<u64> { |
| 177 | total |
| 178 | .checked_add(next) |
| 179 | .ok_or_else(|| ErrorCode::Limit.into()) |
| 180 | } |
| 181 | impl Group { |
| 182 | fn scan( |
| 183 | &self, |
| 184 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 185 | ) -> Result<Vec<OsString>> { |
| 186 | let mut names: Vec<Option<OsString>> = (0..MAX_VOLUMES).map(|_| None).collect(); |
| 187 | let mut metadata_bytes = 0usize; |
| 188 | step(Step::Check)?; |
| 189 | let entries = self.parent.children(&self.path)?; |
| 190 | step(Step::Activity)?; |
| 191 | for entry in entries { |
| 192 | step(Step::Check)?; |
| 193 | let leaf = entry.map_err(crate::space::io_error)?.file_name(); |
| 194 | let value = units(&leaf); |
| 195 | if value.len() > self.name.prefix.len() |
| 196 | && equal_name(&value[..self.name.prefix.len()], &self.name.prefix) |
| 197 | { |
| 198 | let suffix = &value[self.name.prefix.len()..]; |
| 199 | if let Some(index) = number(suffix) { |
| 200 | if index > MAX_VOLUMES as u32 { |
| 201 | return Err(ErrorCode::Limit.into()); |
| 202 | } |
| 203 | if index == 0 || suffix.len() != 3 { |
| 204 | return Err(self.name.incomplete()); |
| 205 | } |
| 206 | metadata_bytes = value |
| 207 | .len() |
| 208 | .checked_mul(8) |
| 209 | .and_then(|cost| cost.checked_add(256)) |
| 210 | .and_then(|cost| metadata_bytes.checked_add(cost)) |
| 211 | .filter(|cost| *cost <= self.metadata_limits.bytes) |
| 212 | .ok_or(ErrorCode::Limit)?; |
| 213 | if index as usize > self.metadata_limits.nodes { |
| 214 | return Err(ErrorCode::Limit.into()); |
| 215 | } |
| 216 | let slot = &mut names[index as usize - 1]; |
| 217 | if slot.is_some() { |
| 218 | return Err(self.name.incomplete()); |
| 219 | } |
| 220 | *slot = Some(leaf); |
| 221 | } |
| 222 | } |
| 223 | step(Step::Activity)?; |
| 224 | } |
| 225 | let Some(last) = names.iter().rposition(Option::is_some) else { |
| 226 | return Ok(Vec::new()); |
| 227 | }; |
| 228 | names.truncate(last + 1); |
| 229 | names |
| 230 | .into_iter() |
| 231 | .enumerate() |
| 232 | .map(|(index, name)| { |
| 233 | name.ok_or_else(|| { |
| 234 | self.name |
| 235 | .problem(VolumeProblemReason::MissingVolume, index + 1) |
| 236 | }) |
| 237 | }) |
| 238 | .collect() |
| 239 | } |
| 240 | fn parent_unchanged(&self) -> Result<()> { |
| 241 | let named = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?; |
| 242 | if filesystem::object(&named.file)? != self.object |
| 243 | || !named |
| 244 | .file |
| 245 | .metadata() |
| 246 | .map_err(crate::space::io_error)? |
| 247 | .is_dir() |
| 248 | { |
| 249 | return Err(ErrorCode::SourceChanged.into()); |
| 250 | } |
| 251 | Ok(()) |
| 252 | } |
| 253 | fn open_part( |
| 254 | &self, |
| 255 | name: &OsStr, |
| 256 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 257 | ) -> Result<Input> { |
| 258 | match self.parent.open_named(&self.path, name) { |
| 259 | Ok(file) => { |
| 260 | step(Step::Activity)?; |
| 261 | Ok(file) |
| 262 | } |
| 263 | Err(error) => { |
| 264 | // 읽기 실패가 확정된 중간 누락인지 먼저 확인함. |
| 265 | if error == ErrorCode::Io { |
| 266 | let names = self.scan(step)?; |
| 267 | if !names.iter().any(|candidate| candidate == name) { |
| 268 | return Err(ErrorCode::SourceChanged.into()); |
| 269 | } |
| 270 | } |
| 271 | Err(error.into()) |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | fn matches(&self, part: &Part, input: &Input) -> Result<()> { |
| 276 | let data = metadata(&input.file)?; |
| 277 | if filesystem::object(&input.file)? != part.object |
| 278 | || data.len() != part.length |
| 279 | || data.modified().map_err(crate::space::io_error)? != part.modified |
| 280 | { |
| 281 | return Err(ErrorCode::SourceChanged.into()); |
| 282 | } |
| 283 | Ok(()) |
| 284 | } |
| 285 | fn read_part( |
| 286 | &self, |
| 287 | part: &Part, |
| 288 | output: &mut Option<&mut File>, |
| 289 | whole: &mut Sha256, |
| 290 | processed: &mut u64, |
| 291 | reported: &mut Instant, |
| 292 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 293 | ) -> Result<[u8; 32]> { |
| 294 | let mut input = self.open_part(&part.name, step)?; |
| 295 | self.matches(part, &input)?; |
| 296 | let mut hash = Sha256::new(); |
| 297 | let mut read = 0u64; |
| 298 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 299 | loop { |
| 300 | step(Step::Check)?; |
| 301 | let length = input |
| 302 | .file |
| 303 | .read(&mut buffer[..]) |
| 304 | .map_err(crate::space::io_error)?; |
| 305 | step(Step::Activity)?; |
| 306 | if length == 0 { |
| 307 | break; |
| 308 | } |
| 309 | read = read |
| 310 | .checked_add(length as u64) |
| 311 | .filter(|n| *n <= part.length) |
| 312 | .ok_or(ErrorCode::SourceChanged)?; |
| 313 | if let Some(file) = output { |
| 314 | file.write_all(&buffer[..length]) |
| 315 | .map_err(crate::space::io_error)?; |
| 316 | step(Step::Activity)?; |
| 317 | } |
| 318 | hash.update(&buffer[..length]); |
| 319 | whole.update(&buffer[..length]); |
| 320 | *processed = processed |
| 321 | .checked_add(length as u64) |
| 322 | .ok_or(ErrorCode::Limit)?; |
| 323 | if reported.elapsed() >= std::time::Duration::from_millis(200) { |
| 324 | step(Step::Read { |
| 325 | bytes: *processed, |
| 326 | total: self.total, |
| 327 | })?; |
| 328 | *reported = Instant::now(); |
| 329 | } |
| 330 | } |
| 331 | if read != part.length { |
| 332 | return Err(ErrorCode::SourceChanged.into()); |
| 333 | } |
| 334 | self.matches(part, &input)?; |
| 335 | let named = self.open_part(&part.name, step)?; |
| 336 | self.matches(part, &named)?; |
| 337 | Ok(hash.finalize().into()) |
| 338 | } |
| 339 | fn capture( |
| 340 | &mut self, |
| 341 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 342 | ) -> Result<(File, [u8; 32])> { |
| 343 | step(Step::Check)?; |
| 344 | let mut file = crate::spool::temporary()?; |
| 345 | crate::space::ensure(&file, self.total)?; |
| 346 | let mut processed = 0; |
| 347 | let mut whole = Sha256::new(); |
| 348 | let mut reported = Instant::now(); |
| 349 | for index in 0..self.parts.len() { |
| 350 | let hash = self.read_part( |
| 351 | &self.parts[index], |
| 352 | &mut Some(&mut file), |
| 353 | &mut whole, |
| 354 | &mut processed, |
| 355 | &mut reported, |
| 356 | step, |
| 357 | )?; |
| 358 | self.parts[index].hash = hash; |
| 359 | step(Step::Activity)?; |
| 360 | } |
| 361 | step(Step::Read { |
| 362 | bytes: processed, |
| 363 | total: self.total, |
| 364 | })?; |
| 365 | Ok((file, whole.finalize().into())) |
| 366 | } |
| 367 | fn manifest(&self) -> Result<[u8; 32]> { |
| 368 | let mut hash = Sha256::new(); |
| 369 | hash.update(b"zipelo.split7z.v1\0"); |
| 370 | hash.update( |
| 371 | crate::wire::encode_source_object(&self.object).map_err(|_| ErrorCode::Internal)?, |
| 372 | ); |
| 373 | hash.update((self.parts.len() as u16).to_le_bytes()); |
| 374 | for (index, part) in self.parts.iter().enumerate() { |
| 375 | hash.update(((index + 1) as u16).to_le_bytes()); |
| 376 | hash.update( |
| 377 | crate::wire::encode_native_path(&NativePath::from_path(Path::new(&part.name))) |
| 378 | .map_err(|_| ErrorCode::Limit)?, |
| 379 | ); |
| 380 | hash.update( |
| 381 | crate::wire::encode_source_object(&part.object).map_err(|_| ErrorCode::Internal)?, |
| 382 | ); |
| 383 | hash.update(part.length.to_le_bytes()); |
| 384 | hash.update(part.hash); |
| 385 | } |
| 386 | Ok(hash.finalize().into()) |
| 387 | } |
| 388 | pub fn verify( |
| 389 | &self, |
| 390 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 391 | ) -> Result<()> { |
| 392 | step(Step::Check)?; |
| 393 | self.parent_unchanged()?; |
| 394 | let names = self.scan(step).map_err(|failure| { |
| 395 | if matches!( |
| 396 | failure.problem, |
| 397 | Some((VolumeProblemReason::IncompleteSet, _)) |
| 398 | ) { |
| 399 | ErrorCode::SourceChanged.into() |
| 400 | } else { |
| 401 | failure |
| 402 | } |
| 403 | })?; |
| 404 | if names.len() != self.parts.len() |
| 405 | || names |
| 406 | .iter() |
| 407 | .zip(&self.parts) |
| 408 | .any(|(name, part)| *name != part.name) |
| 409 | { |
| 410 | return Err(ErrorCode::SourceChanged.into()); |
| 411 | } |
| 412 | let mut processed = 0; |
| 413 | let mut whole = Sha256::new(); |
| 414 | let mut reported = Instant::now(); |
| 415 | for part in &self.parts { |
| 416 | step(Step::Check)?; |
| 417 | if self.read_part( |
| 418 | part, |
| 419 | &mut None, |
| 420 | &mut whole, |
| 421 | &mut processed, |
| 422 | &mut reported, |
| 423 | step, |
| 424 | )? != part.hash |
| 425 | { |
| 426 | return Err(ErrorCode::SourceChanged.into()); |
| 427 | } |
| 428 | step(Step::Activity)?; |
| 429 | } |
| 430 | step(Step::Read { |
| 431 | bytes: processed, |
| 432 | total: self.total, |
| 433 | })?; |
| 434 | let final_names = self.scan(step).map_err(|failure| { |
| 435 | if matches!( |
| 436 | failure.problem, |
| 437 | Some((VolumeProblemReason::IncompleteSet, _)) |
| 438 | ) { |
| 439 | ErrorCode::SourceChanged.into() |
| 440 | } else { |
| 441 | failure |
| 442 | } |
| 443 | })?; |
| 444 | if final_names != names { |
| 445 | return Err(ErrorCode::SourceChanged.into()); |
| 446 | } |
| 447 | self.parent_unchanged()?; |
| 448 | Ok(()) |
| 449 | } |
| 450 | } |
| 451 | fn discover( |
| 452 | path: &Path, |
| 453 | expected: Option<&ListId>, |
| 454 | limit: u64, |
| 455 | metadata_limits: crate::archive::MetadataLimits, |
| 456 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 457 | ) -> Result<Option<Group>> { |
| 458 | if unsupported_split(path) { |
| 459 | return Err(ErrorCode::UnsupportedFeature.into()); |
| 460 | } |
| 461 | let Some(name) = Name::parse(path) else { |
| 462 | return Ok(None); |
| 463 | }; |
| 464 | if !NativePath::from_path(Path::new( |
| 465 | path.file_name().ok_or(ErrorCode::InvalidRequest)?, |
| 466 | )) |
| 467 | .is_basename() |
| 468 | { |
| 469 | return Err(ErrorCode::UnsafePath.into()); |
| 470 | } |
| 471 | if name.selected > MAX_VOLUMES as u32 { |
| 472 | return Err(ErrorCode::Limit.into()); |
| 473 | } |
| 474 | if name.width != 3 { |
| 475 | return Err(ErrorCode::UnsupportedFeature.into()); |
| 476 | } |
| 477 | if name.selected != 1 { |
| 478 | return Err(name.problem(VolumeProblemReason::FirstVolumeRequired, 1)); |
| 479 | } |
| 480 | step(Step::Check)?; |
| 481 | let parent_path = path |
| 482 | .parent() |
| 483 | .ok_or(ErrorCode::InvalidRequest)? |
| 484 | .to_path_buf(); |
| 485 | let parent = Input::open(&parent_path)?; |
| 486 | if !parent |
| 487 | .file |
| 488 | .metadata() |
| 489 | .map_err(crate::space::io_error)? |
| 490 | .is_dir() |
| 491 | { |
| 492 | return Err(ErrorCode::UnsafePath.into()); |
| 493 | } |
| 494 | let object = filesystem::object(&parent.file)?; |
| 495 | let mut group = Group { |
| 496 | parent, |
| 497 | path: parent_path, |
| 498 | object, |
| 499 | name, |
| 500 | parts: Vec::new(), |
| 501 | total: 0, |
| 502 | metadata_limits, |
| 503 | }; |
| 504 | let names = group.scan(step)?; |
| 505 | if names.is_empty() { |
| 506 | return Err(if expected.is_some() { |
| 507 | ErrorCode::SourceChanged |
| 508 | } else { |
| 509 | ErrorCode::Io |
| 510 | } |
| 511 | .into()); |
| 512 | } |
| 513 | for name in names { |
| 514 | step(Step::Check)?; |
| 515 | let input = group.open_part(&name, step)?; |
| 516 | let data = metadata(&input.file)?; |
| 517 | let object = filesystem::object(&input.file)?; |
| 518 | if group.parts.iter().any(|part| part.object == object) { |
| 519 | return Err(ErrorCode::UnsafePath.into()); |
| 520 | } |
| 521 | group.total = combined_length(group.total, data.len())?; |
| 522 | group.parts.push(Part { |
| 523 | name, |
| 524 | object, |
| 525 | length: data.len(), |
| 526 | modified: data.modified().map_err(crate::space::io_error)?, |
| 527 | hash: [0; 32], |
| 528 | }); |
| 529 | step(Step::Activity)?; |
| 530 | } |
| 531 | if expected.is_some_and(|id| { |
| 532 | id.archive_bytes != group.total |
| 533 | || id.catalog_version != 2 |
| 534 | || id.format != Format::SevenZip |
| 535 | || !matches!(id.source_object, SourceObject::SplitSevenZip { .. }) |
| 536 | }) { |
| 537 | return Err(ErrorCode::SourceChanged.into()); |
| 538 | } |
| 539 | if group.total > limit { |
| 540 | return Err(ErrorCode::Limit.into()); |
| 541 | } |
| 542 | Ok(Some(group)) |
| 543 | } |
| 544 | pub(crate) fn open( |
| 545 | path: &Path, |
| 546 | expected: Option<&ListId>, |
| 547 | limit: u64, |
| 548 | metadata_limits: crate::archive::MetadataLimits, |
| 549 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 550 | ) -> Result<Option<Captured>> { |
| 551 | let Some(mut group) = discover(path, expected, limit, metadata_limits, step)? else { |
| 552 | return Ok(None); |
| 553 | }; |
| 554 | let (mut file, hash) = loop { |
| 555 | match group.capture(step) { |
| 556 | Err(failure) |
| 557 | if failure.error == ErrorCode::DiskFull && crate::spool::next_after_full()? => |
| 558 | { |
| 559 | continue; |
| 560 | } |
| 561 | result => break result?, |
| 562 | } |
| 563 | }; |
| 564 | let object = SourceObject::SplitSevenZip { |
| 565 | manifest_sha256: group.manifest()?, |
| 566 | }; |
| 567 | if expected.is_some_and(|id| id.source_object != object || id.archive_sha256 != hash) { |
| 568 | return Err(ErrorCode::SourceChanged.into()); |
| 569 | } |
| 570 | // 마지막 누락 이름을 추측하지 않고 논리 헤더 끝 위치를 검증함. |
| 571 | file.rewind().map_err(crate::space::io_error)?; |
| 572 | let mut header = [0; 32]; |
| 573 | if group.parts.iter().any(|part| part.length == 0) || group.total < 32 { |
| 574 | return Err(group.name.incomplete()); |
| 575 | } |
| 576 | file.read_exact(&mut header) |
| 577 | .map_err(crate::space::io_error)?; |
| 578 | if &header[..6] != b"7z\xbc\xaf\x27\x1c" |
| 579 | || zlib_rs::crc32::crc32(0, &header[12..]) |
| 580 | != u32::from_le_bytes(header[8..12].try_into().unwrap()) |
| 581 | { |
| 582 | return Err(group.name.incomplete()); |
| 583 | } |
| 584 | let offset = u64::from_le_bytes(header[12..20].try_into().unwrap()); |
| 585 | let length = u64::from_le_bytes(header[20..28].try_into().unwrap()); |
| 586 | if 32u64 |
| 587 | .checked_add(offset) |
| 588 | .and_then(|start| start.checked_add(length)) |
| 589 | != Some(group.total) |
| 590 | { |
| 591 | return Err(group.name.incomplete()); |
| 592 | } |
| 593 | group.verify(step)?; |
| 594 | file.rewind().map_err(crate::space::io_error)?; |
| 595 | Ok(Some(Captured { |
| 596 | snapshot: Snapshot { |
| 597 | file, |
| 598 | len: group.total, |
| 599 | object, |
| 600 | hash, |
| 601 | }, |
| 602 | group, |
| 603 | })) |
| 604 | } |
| 605 | |
| 606 | pub(crate) struct Direct { |
| 607 | group: Group, |
| 608 | changes: Vec<Option<(i64, i64)>>, |
| 609 | position: u64, |
| 610 | pub hash: [u8; 32], |
| 611 | } |
| 612 | impl Direct { |
| 613 | pub fn len(&self) -> u64 { |
| 614 | self.group.total |
| 615 | } |
| 616 | pub fn object(&self) -> Result<SourceObject> { |
| 617 | Ok(SourceObject::SplitSevenZip { |
| 618 | manifest_sha256: self.group.manifest()?, |
| 619 | }) |
| 620 | } |
| 621 | fn matches(&self, index: usize, input: &Input) -> Result<()> { |
| 622 | let part = &self.group.parts[index]; |
| 623 | let data = input.file.metadata().map_err(crate::space::io_error)?; |
| 624 | if !data.is_file() |
| 625 | || filesystem::object(&input.file)? != part.object |
| 626 | || data.len() != part.length |
| 627 | || data.modified().map_err(crate::space::io_error)? != part.modified |
| 628 | || crate::spool::change_stamp(&data) != self.changes[index] |
| 629 | { |
| 630 | return Err(ErrorCode::SourceChanged.into()); |
| 631 | } |
| 632 | Ok(()) |
| 633 | } |
| 634 | fn open_checked( |
| 635 | &self, |
| 636 | index: usize, |
| 637 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 638 | ) -> Result<Input> { |
| 639 | let input = self |
| 640 | .group |
| 641 | .open_part(&self.group.parts[index].name, step) |
| 642 | .map_err(|failure| { |
| 643 | if failure.error == ErrorCode::UnsafePath { |
| 644 | ErrorCode::SourceChanged.into() |
| 645 | } else { |
| 646 | failure |
| 647 | } |
| 648 | })?; |
| 649 | self.matches(index, &input)?; |
| 650 | Ok(input) |
| 651 | } |
| 652 | fn unchanged( |
| 653 | &self, |
| 654 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 655 | ) -> Result<()> { |
| 656 | for index in 0..self.group.parts.len() { |
| 657 | step(Step::Check)?; |
| 658 | self.open_checked(index, step)?; |
| 659 | } |
| 660 | Ok(()) |
| 661 | } |
| 662 | pub fn verify( |
| 663 | &self, |
| 664 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 665 | ) -> Result<()> { |
| 666 | self.unchanged(step)?; |
| 667 | self.group.verify(step)?; |
| 668 | self.unchanged(step) |
| 669 | } |
| 670 | } |
| 671 | impl Read for Direct { |
| 672 | fn read(&mut self, output: &mut [u8]) -> std::io::Result<usize> { |
| 673 | let mut start = 0; |
| 674 | if output.is_empty() { |
| 675 | return Ok(0); |
| 676 | } |
| 677 | let source_error = |failure: Failure| { |
| 678 | std::io::Error::other(format!("분할 원본 읽기 실패: {:?}", failure.error)) |
| 679 | }; |
| 680 | for (index, part) in self.group.parts.iter().enumerate() { |
| 681 | let end = start + part.length; |
| 682 | if self.position < end { |
| 683 | let count = (end - self.position).min(output.len() as u64) as usize; |
| 684 | // 필요한 조각만 열어 핸들 사용량이 조각 수에 비례하지 않게 함. |
| 685 | let mut input = self |
| 686 | .open_checked(index, &mut |_| Ok(())) |
| 687 | .map_err(source_error)?; |
| 688 | input |
| 689 | .file |
| 690 | .seek(std::io::SeekFrom::Start(self.position - start))?; |
| 691 | let read = input.file.read(&mut output[..count]); |
| 692 | self.matches(index, &input).map_err(source_error)?; |
| 693 | let count = read?; |
| 694 | if count == 0 { |
| 695 | return Err(std::io::Error::new( |
| 696 | std::io::ErrorKind::UnexpectedEof, |
| 697 | "분할 원본이 변경됨", |
| 698 | )); |
| 699 | } |
| 700 | self.position += count as u64; |
| 701 | return Ok(count); |
| 702 | } |
| 703 | start = end; |
| 704 | } |
| 705 | Ok(0) |
| 706 | } |
| 707 | } |
| 708 | impl Seek for Direct { |
| 709 | fn seek(&mut self, position: std::io::SeekFrom) -> std::io::Result<u64> { |
| 710 | let next = match position { |
| 711 | std::io::SeekFrom::Start(n) => i128::from(n), |
| 712 | std::io::SeekFrom::Current(n) => i128::from(self.position) + i128::from(n), |
| 713 | std::io::SeekFrom::End(n) => i128::from(self.group.total) + i128::from(n), |
| 714 | }; |
| 715 | self.position = u64::try_from(next).map_err(|_| { |
| 716 | std::io::Error::new(std::io::ErrorKind::InvalidInput, "잘못된 읽기 위치") |
| 717 | })?; |
| 718 | Ok(self.position) |
| 719 | } |
| 720 | } |
| 721 | pub(crate) fn open_direct( |
| 722 | path: &Path, |
| 723 | limit: u64, |
| 724 | metadata_limits: crate::archive::MetadataLimits, |
| 725 | step: &mut impl FnMut(Step) -> std::result::Result<(), ErrorCode>, |
| 726 | ) -> Result<Option<Direct>> { |
| 727 | let Some(mut group) = discover(path, None, limit, metadata_limits, step)? else { |
| 728 | return Ok(None); |
| 729 | }; |
| 730 | let mut changes = Vec::new(); |
| 731 | for part in &group.parts { |
| 732 | let input = group.open_part(&part.name, step)?; |
| 733 | group.matches(part, &input)?; |
| 734 | changes.push(crate::spool::change_stamp(&metadata(&input.file)?)); |
| 735 | } |
| 736 | let mut whole = Sha256::new(); |
| 737 | let mut processed = 0; |
| 738 | let mut reported = Instant::now(); |
| 739 | for index in 0..group.parts.len() { |
| 740 | group.parts[index].hash = group.read_part( |
| 741 | &group.parts[index], |
| 742 | &mut None, |
| 743 | &mut whole, |
| 744 | &mut processed, |
| 745 | &mut reported, |
| 746 | step, |
| 747 | )?; |
| 748 | } |
| 749 | step(Step::Read { |
| 750 | bytes: processed, |
| 751 | total: group.total, |
| 752 | })?; |
| 753 | let mut direct = Direct { |
| 754 | group, |
| 755 | changes, |
| 756 | position: 0, |
| 757 | hash: whole.finalize().into(), |
| 758 | }; |
| 759 | let mut header = [0; 32]; |
| 760 | if direct.group.parts.iter().any(|part| part.length == 0) || direct.len() < 32 { |
| 761 | return Err(direct.group.name.incomplete()); |
| 762 | } |
| 763 | let header_read = direct |
| 764 | .read_exact(&mut header) |
| 765 | .map_err(crate::space::io_error); |
| 766 | direct.verify(step)?; |
| 767 | header_read?; |
| 768 | if &header[..6] != b"7z\xbc\xaf\x27\x1c" |
| 769 | || zlib_rs::crc32::crc32(0, &header[12..]) |
| 770 | != u32::from_le_bytes(header[8..12].try_into().unwrap()) |
| 771 | { |
| 772 | return Err(direct.group.name.incomplete()); |
| 773 | } |
| 774 | let offset = u64::from_le_bytes(header[12..20].try_into().unwrap()); |
| 775 | let length = u64::from_le_bytes(header[20..28].try_into().unwrap()); |
| 776 | if 32u64 |
| 777 | .checked_add(offset) |
| 778 | .and_then(|n| n.checked_add(length)) |
| 779 | != Some(direct.len()) |
| 780 | { |
| 781 | return Err(direct.group.name.incomplete()); |
| 782 | } |
| 783 | direct.rewind().map_err(crate::space::io_error)?; |
| 784 | Ok(Some(direct)) |
| 785 | } |
| 786 | |
| 787 | #[cfg(test)] |
| 788 | #[path = "../../../tests/rust-archive-worker/split_capture.rs"] |
| 789 | mod tests; |