| 1 | use crate::{ |
| 2 | archive, |
| 3 | filesystem::{self, Dir}, |
| 4 | protocol::*, |
| 5 | resources::{Budget, Monitor, Watchdog, completed}, |
| 6 | wire::{Reader, Writer}, |
| 7 | }; |
| 8 | use std::{ |
| 9 | collections::BTreeSet, |
| 10 | io::{Read, Seek, SeekFrom, Write}, |
| 11 | sync::{Arc, Condvar, Mutex}, |
| 12 | time::{Duration, Instant}, |
| 13 | }; |
| 14 | |
| 15 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 16 | #[derive(PartialEq, Eq)] |
| 17 | enum Challenge { |
| 18 | Password(u64), |
| 19 | Conflict(u64), |
| 20 | Resource(u64, ResourceScope), |
| 21 | } |
| 22 | struct State<W> { |
| 23 | writer: Writer<W>, |
| 24 | cancelled: bool, |
| 25 | phase: u8, |
| 26 | fault: Option<ErrorCode>, |
| 27 | challenge: Option<Challenge>, |
| 28 | conflict_reply: Option<(ConflictChoice, bool)>, |
| 29 | password: Option<Secret>, |
| 30 | resource_reply: Option<bool>, |
| 31 | input_closed: bool, |
| 32 | } |
| 33 | struct Job<W> { |
| 34 | state: Arc<Mutex<State<W>>>, |
| 35 | wake: Arc<Condvar>, |
| 36 | next_challenge: u64, |
| 37 | interactive: bool, |
| 38 | action: ActionKind, |
| 39 | budget: Option<Budget>, |
| 40 | watchdog: Watchdog, |
| 41 | remaining_choice: Option<ConflictChoice>, |
| 42 | source_group: Option<crate::split_seven_zip::Group>, |
| 43 | direct_source: Option<crate::spool::DirectSource>, |
| 44 | direct_split: Option<crate::split_seven_zip::Direct>, |
| 45 | source_verified_for_publication: bool, |
| 46 | creation_plan: Option<crate::create::Plan>, |
| 47 | recovery: Option<crate::zip_recovery::Recovery>, |
| 48 | started: Instant, |
| 49 | terminal: Terminal, |
| 50 | parent: crate::parent::Parent, |
| 51 | } |
| 52 | impl<W: Write> Job<W> { |
| 53 | fn request_resource( |
| 54 | &mut self, |
| 55 | scope: ResourceScope, |
| 56 | mut usage: ResourceUsage, |
| 57 | storage: Option<&std::fs::File>, |
| 58 | ) -> Result<()> { |
| 59 | let budget = self.budget.as_ref().ok_or(ErrorCode::Internal)?; |
| 60 | let (soft_limits, ceiling) = (budget.soft, budget.ceiling); |
| 61 | if let Some(file) = storage { |
| 62 | usage.available_bytes = |
| 63 | Some(crate::space::available(file)?.min(u64::MAX as u128) as u64); |
| 64 | } |
| 65 | self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?; |
| 66 | let id = self.next_challenge; |
| 67 | let state_ref = Arc::clone(&self.state); |
| 68 | let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?; |
| 69 | if state.challenge.is_some() { |
| 70 | return Err(ErrorCode::Internal); |
| 71 | } |
| 72 | state.challenge = Some(Challenge::Resource(id, scope)); |
| 73 | state |
| 74 | .writer |
| 75 | .send(&Message::ResourceRequired { |
| 76 | challenge_id: id, |
| 77 | action: self.action, |
| 78 | scope, |
| 79 | usage, |
| 80 | soft_limits, |
| 81 | ceiling, |
| 82 | }) |
| 83 | .map_err(|_| ErrorCode::Io)?; |
| 84 | let waiting = Instant::now(); |
| 85 | loop { |
| 86 | self.parent.check()?; |
| 87 | if let Some(error) = state.fault { |
| 88 | return Err(error); |
| 89 | } |
| 90 | if state.cancelled { |
| 91 | return Err(ErrorCode::None); |
| 92 | } |
| 93 | if let Some(allow) = state.resource_reply.take() { |
| 94 | if !allow { |
| 95 | return Err(ErrorCode::None); |
| 96 | } |
| 97 | self.budget |
| 98 | .as_mut() |
| 99 | .ok_or(ErrorCode::Internal)? |
| 100 | .grant(scope); |
| 101 | self.watchdog.resume(self.started.elapsed(), true); |
| 102 | return Ok(()); |
| 103 | } |
| 104 | if state.input_closed { |
| 105 | return Err(ErrorCode::Protocol); |
| 106 | } |
| 107 | if waiting.elapsed() >= Duration::from_secs(300) { |
| 108 | return Err(ErrorCode::Limit); |
| 109 | } |
| 110 | state = self |
| 111 | .wake |
| 112 | .wait_timeout(state, Duration::from_millis(50)) |
| 113 | .map_err(|_| ErrorCode::Internal)? |
| 114 | .0; |
| 115 | } |
| 116 | } |
| 117 | fn password(&mut self, purpose: PasswordPurpose, attempt: u32) -> Result<Secret> { |
| 118 | self.check()?; |
| 119 | self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?; |
| 120 | let id = self.next_challenge; |
| 121 | let state_ref = Arc::clone(&self.state); |
| 122 | let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?; |
| 123 | state.challenge = Some(Challenge::Password(id)); |
| 124 | state |
| 125 | .writer |
| 126 | .send(&Message::PasswordRequired { |
| 127 | challenge_id: id, |
| 128 | attempt, |
| 129 | purpose, |
| 130 | }) |
| 131 | .map_err(|_| ErrorCode::Io)?; |
| 132 | let waiting = Instant::now(); |
| 133 | loop { |
| 134 | self.parent.check()?; |
| 135 | if let Some(error) = state.fault { |
| 136 | return Err(error); |
| 137 | } |
| 138 | if state.cancelled { |
| 139 | return Err(ErrorCode::None); |
| 140 | } |
| 141 | if let Some(secret) = state.password.take() { |
| 142 | self.watchdog.resume(self.started.elapsed(), false); |
| 143 | return Ok(secret); |
| 144 | } |
| 145 | if state.input_closed { |
| 146 | return Err(ErrorCode::Protocol); |
| 147 | } |
| 148 | if if self.budget.is_some() { |
| 149 | waiting.elapsed() >= Duration::from_secs(300) |
| 150 | } else { |
| 151 | self.started.elapsed() > Duration::from_secs(300) |
| 152 | } { |
| 153 | return Err(ErrorCode::Limit); |
| 154 | } |
| 155 | state = self |
| 156 | .wake |
| 157 | .wait_timeout(state, Duration::from_millis(50)) |
| 158 | .map_err(|_| ErrorCode::Internal)? |
| 159 | .0; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | fn conflict(&mut self, entry: &Entry, existing_size: u64) -> Result<ConflictChoice> { |
| 164 | self.check()?; |
| 165 | if let Some(choice) = self.remaining_choice { |
| 166 | return Ok(choice); |
| 167 | } |
| 168 | self.next_challenge = self.next_challenge.checked_add(1).ok_or(ErrorCode::Limit)?; |
| 169 | let id = self.next_challenge; |
| 170 | let state_ref = Arc::clone(&self.state); |
| 171 | let mut state = state_ref.lock().map_err(|_| ErrorCode::Internal)?; |
| 172 | state.challenge = Some(Challenge::Conflict(id)); |
| 173 | state |
| 174 | .writer |
| 175 | .send(&Message::ConflictRequired { |
| 176 | challenge_id: id, |
| 177 | entry_id: entry.entry_id, |
| 178 | relative_name: entry.name.clone(), |
| 179 | incoming_size: entry.size, |
| 180 | existing_size, |
| 181 | }) |
| 182 | .map_err(|_| ErrorCode::Io)?; |
| 183 | let waiting = Instant::now(); |
| 184 | loop { |
| 185 | self.parent.check()?; |
| 186 | if let Some(error) = state.fault { |
| 187 | return Err(error); |
| 188 | } |
| 189 | if state.cancelled { |
| 190 | return Err(ErrorCode::None); |
| 191 | } |
| 192 | if let Some((choice, apply)) = state.conflict_reply.take() { |
| 193 | if apply { |
| 194 | self.remaining_choice = Some(choice); |
| 195 | } |
| 196 | self.watchdog.resume(self.started.elapsed(), false); |
| 197 | return Ok(choice); |
| 198 | } |
| 199 | if state.input_closed { |
| 200 | return Err(ErrorCode::Protocol); |
| 201 | } |
| 202 | if if self.budget.is_some() { |
| 203 | waiting.elapsed() >= Duration::from_secs(300) |
| 204 | } else { |
| 205 | self.started.elapsed() > Duration::from_secs(300) |
| 206 | } { |
| 207 | return Err(ErrorCode::Limit); |
| 208 | } |
| 209 | state = self |
| 210 | .wake |
| 211 | .wait_timeout(state, Duration::from_millis(50)) |
| 212 | .map_err(|_| ErrorCode::Internal)? |
| 213 | .0; |
| 214 | } |
| 215 | } |
| 216 | fn rename(&mut self, root: &Dir, name: &str, reserved: &BTreeSet<String>) -> Result<String> { |
| 217 | let (prefix, leaf) = name.rsplit_once('/').unwrap_or(("", name)); |
| 218 | let (stem, extension) = match leaf.rsplit_once('.') { |
| 219 | Some((stem, ext)) if !stem.is_empty() => (stem, format!(".{ext}")), |
| 220 | _ => (leaf, String::new()), |
| 221 | }; |
| 222 | for index in 1..=10000 { |
| 223 | self.check()?; |
| 224 | fn clip(text: &str, bytes: usize) -> &str { |
| 225 | let mut end = text.len().min(bytes); |
| 226 | while !text.is_char_boundary(end) { |
| 227 | end -= 1; |
| 228 | } |
| 229 | &text[..end] |
| 230 | } |
| 231 | let suffix = format!(" ({index})"); |
| 232 | let extension = clip(&extension, 255 - suffix.len() - 4).trim_end_matches(['.', ' ']); |
| 233 | let stem = clip(stem, 255 - suffix.len() - extension.len()); |
| 234 | let stem = if stem.is_empty() { "file" } else { stem }; |
| 235 | let leaf = format!("{stem}{suffix}{extension}"); |
| 236 | let candidate = if prefix.is_empty() { |
| 237 | leaf |
| 238 | } else { |
| 239 | format!("{prefix}/{leaf}") |
| 240 | }; |
| 241 | archive::valid_name(&candidate, false)?; |
| 242 | let unused = !reserved.contains(&candidate.to_lowercase()) |
| 243 | && filesystem::unused_with(root, &candidate, self)?; |
| 244 | completed(Ok(()), self)?; |
| 245 | if unused { |
| 246 | return Ok(candidate); |
| 247 | } |
| 248 | } |
| 249 | Err(ErrorCode::Conflict) |
| 250 | } |
| 251 | fn event(&mut self, event: Message) -> Result<()> { |
| 252 | let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 253 | state.writer.send(&event).map_err(|_| { |
| 254 | state.fault = Some(ErrorCode::Io); |
| 255 | ErrorCode::Io |
| 256 | }) |
| 257 | } |
| 258 | fn split_result<T>( |
| 259 | &mut self, |
| 260 | result: std::result::Result<T, crate::split_seven_zip::Failure>, |
| 261 | ) -> Result<T> { |
| 262 | match result { |
| 263 | Ok(value) => Ok(value), |
| 264 | Err(failure) => { |
| 265 | self.check()?; |
| 266 | if let Some((reason, volume)) = failure.problem { |
| 267 | self.event(Message::VolumeProblem { reason, volume })?; |
| 268 | } |
| 269 | Err(failure.error) |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | fn verify_split(&mut self) -> Result<()> { |
| 274 | let Some(group) = self.source_group.take() else { |
| 275 | return Ok(()); |
| 276 | }; |
| 277 | let result = (|| { |
| 278 | self.progress(Stage::Verify, 0, None, 0)?; |
| 279 | group.verify(&mut |step| match step { |
| 280 | crate::spool::Step::Check => self.check(), |
| 281 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 282 | crate::spool::Step::Read { bytes, total } => { |
| 283 | self.progress(Stage::Verify, bytes, Some(total), 0) |
| 284 | } |
| 285 | }) |
| 286 | })(); |
| 287 | self.source_group = Some(group); |
| 288 | self.split_result(result) |
| 289 | } |
| 290 | fn verify_before_publication( |
| 291 | &mut self, |
| 292 | temporary: Option<&filesystem::PublicationTemp>, |
| 293 | ) -> Result<()> { |
| 294 | if !self.source_verified_for_publication { |
| 295 | if let Some(plan) = self.creation_plan.take() { |
| 296 | let result = match temporary { |
| 297 | Some(temporary) => plan.verify_for_publication(temporary, self), |
| 298 | None => plan.verify(self), |
| 299 | }; |
| 300 | self.creation_plan = Some(plan); |
| 301 | result?; |
| 302 | } |
| 303 | if let Some(mut recovery) = self.recovery.take() { |
| 304 | let result = recovery.verify_source(self); |
| 305 | self.recovery = Some(recovery); |
| 306 | result?; |
| 307 | } |
| 308 | self.verify_split()?; |
| 309 | self.source_verified_for_publication = true; |
| 310 | } |
| 311 | Ok(()) |
| 312 | } |
| 313 | fn publication_step(&mut self, step: filesystem::PublishStep, last: bool) -> Result<()> { |
| 314 | match step { |
| 315 | filesystem::PublishStep::Check => self.check(), |
| 316 | filesystem::PublishStep::Activity => completed(Ok(()), self), |
| 317 | filesystem::PublishStep::Commit(temporary) => { |
| 318 | self.verify_before_publication(temporary.as_ref())?; |
| 319 | if let Some(plan) = &self.creation_plan { |
| 320 | self.progress(Stage::Commit, 0, None, plan.items.len() as u32)?; |
| 321 | } |
| 322 | if last { self.cutoff() } else { self.check() } |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | fn check(&mut self) -> Result<()> { |
| 327 | self.parent.check()?; |
| 328 | let state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 329 | if let Some(error) = state.fault { |
| 330 | return Err(error); |
| 331 | } |
| 332 | if state.cancelled && state.phase == 0 { |
| 333 | return Err(ErrorCode::None); |
| 334 | } |
| 335 | self.watchdog.check(self.started.elapsed()) |
| 336 | } |
| 337 | fn cutoff(&mut self) -> Result<()> { |
| 338 | self.check()?; |
| 339 | let mut state = self.state.lock().map_err(|_| ErrorCode::Internal)?; |
| 340 | if state.phase == 0 && state.cancelled { |
| 341 | return Err(ErrorCode::None); |
| 342 | } |
| 343 | state.phase = 1; |
| 344 | Ok(()) |
| 345 | } |
| 346 | fn progress( |
| 347 | &mut self, |
| 348 | stage: Stage, |
| 349 | bytes: u64, |
| 350 | total: Option<u64>, |
| 351 | entries: u32, |
| 352 | ) -> Result<()> { |
| 353 | self.event(Message::Progress { |
| 354 | stage, |
| 355 | processed_bytes: bytes, |
| 356 | total_bytes: total, |
| 357 | completed_entries: entries, |
| 358 | }) |
| 359 | } |
| 360 | fn output_reader( |
| 361 | &mut self, |
| 362 | root: &Dir, |
| 363 | name: &str, |
| 364 | data: &mut impl Read, |
| 365 | length: u64, |
| 366 | id: Option<u32>, |
| 367 | last: bool, |
| 368 | replace: Option<&filesystem::Existing>, |
| 369 | ) -> Result<()> { |
| 370 | self.check()?; |
| 371 | self.progress( |
| 372 | Stage::Write, |
| 373 | 0, |
| 374 | Some(length), |
| 375 | self.terminal.created_count as u32, |
| 376 | )?; |
| 377 | let p = filesystem::publish_reader_steps(root, name, data, length, replace, &mut |step| { |
| 378 | self.publication_step(step, last) |
| 379 | }); |
| 380 | self.terminal.retained_partial_count += p.retained; |
| 381 | if p.cleanup != Cleanup::Complete { |
| 382 | self.terminal.cleanup = p.cleanup; |
| 383 | } |
| 384 | if p.created { |
| 385 | self.terminal.created_count += 1; |
| 386 | self.terminal.publication = Publication::Partial; |
| 387 | self.terminal.durability = match (self.terminal.durability, p.durability) { |
| 388 | (Durability::Failed, _) | (_, Durability::Failed) => Durability::Failed, |
| 389 | (Durability::Unconfirmed, _) | (_, Durability::Unconfirmed) => { |
| 390 | Durability::Unconfirmed |
| 391 | } |
| 392 | _ => p.durability, |
| 393 | }; |
| 394 | self.event(Message::Output { |
| 395 | entry_id: id, |
| 396 | relative_name: name.to_owned(), |
| 397 | disposition: Disposition::Created, |
| 398 | })?; |
| 399 | } |
| 400 | if p.uncertain { |
| 401 | self.terminal.publication = Publication::Uncertain; |
| 402 | self.terminal.durability = Durability::Unconfirmed; |
| 403 | self.event(Message::Output { |
| 404 | entry_id: id, |
| 405 | relative_name: name.to_owned(), |
| 406 | disposition: Disposition::CommitUncertain, |
| 407 | })?; |
| 408 | } |
| 409 | if p.retained != 0 { |
| 410 | self.event(Message::Output { |
| 411 | entry_id: id, |
| 412 | relative_name: p.retained_name.clone().ok_or(ErrorCode::Internal)?, |
| 413 | disposition: Disposition::PartialRetained, |
| 414 | })?; |
| 415 | } |
| 416 | if let Some(error) = p.error { |
| 417 | return Err(error); |
| 418 | } |
| 419 | if p.created { |
| 420 | completed(Ok(()), self)?; |
| 421 | } |
| 422 | Ok(()) |
| 423 | } |
| 424 | /// 분할 7z 볼륨을 한 묶음으로 게시함. 실패하면 게시한 볼륨을 되돌림. |
| 425 | fn output_set( |
| 426 | &mut self, |
| 427 | root: &Dir, |
| 428 | files: &[(String, u64)], |
| 429 | data: &mut impl Read, |
| 430 | ) -> Result<()> { |
| 431 | self.check()?; |
| 432 | let total = files |
| 433 | .iter() |
| 434 | .try_fold(0u64, |sum, (_, length)| sum.checked_add(*length)) |
| 435 | .ok_or(ErrorCode::Limit)?; |
| 436 | self.progress( |
| 437 | Stage::Write, |
| 438 | 0, |
| 439 | Some(total), |
| 440 | self.terminal.created_count as u32, |
| 441 | )?; |
| 442 | let p = filesystem::publish_set_steps(root, files, data, &mut |step| { |
| 443 | self.publication_step(step, true) |
| 444 | }); |
| 445 | self.terminal.retained_partial_count += p.retained.len() as u64; |
| 446 | if p.cleanup != Cleanup::Complete { |
| 447 | self.terminal.cleanup = p.cleanup; |
| 448 | } |
| 449 | if !p.created.is_empty() { |
| 450 | self.terminal.publication = Publication::Partial; |
| 451 | self.terminal.durability = match (self.terminal.durability, p.durability) { |
| 452 | (Durability::Failed, _) | (_, Durability::Failed) => Durability::Failed, |
| 453 | (Durability::Unconfirmed, _) | (_, Durability::Unconfirmed) => { |
| 454 | Durability::Unconfirmed |
| 455 | } |
| 456 | _ => p.durability, |
| 457 | }; |
| 458 | } |
| 459 | for name in &p.created { |
| 460 | self.terminal.created_count += 1; |
| 461 | self.event(Message::Output { |
| 462 | entry_id: None, |
| 463 | relative_name: name.clone(), |
| 464 | disposition: Disposition::Created, |
| 465 | })?; |
| 466 | } |
| 467 | if p.uncertain { |
| 468 | self.terminal.publication = Publication::Uncertain; |
| 469 | self.terminal.durability = Durability::Unconfirmed; |
| 470 | for (name, _) in files.iter().filter(|(name, _)| !p.created.contains(name)) { |
| 471 | self.event(Message::Output { |
| 472 | entry_id: None, |
| 473 | relative_name: name.clone(), |
| 474 | disposition: Disposition::CommitUncertain, |
| 475 | })?; |
| 476 | } |
| 477 | } |
| 478 | for name in &p.retained { |
| 479 | self.event(Message::Output { |
| 480 | entry_id: None, |
| 481 | relative_name: name.clone(), |
| 482 | disposition: Disposition::PartialRetained, |
| 483 | })?; |
| 484 | } |
| 485 | if let Some(error) = p.error { |
| 486 | return Err(error); |
| 487 | } |
| 488 | completed(Ok(()), self) |
| 489 | } |
| 490 | fn direct_snapshot( |
| 491 | &mut self, |
| 492 | path: &std::path::Path, |
| 493 | limit: u64, |
| 494 | ) -> Result<crate::spool::Snapshot> { |
| 495 | let (snapshot, guard) = |
| 496 | crate::spool::Snapshot::open_direct(path, limit, &mut |step| match step { |
| 497 | crate::spool::Step::Check => self.check(), |
| 498 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 499 | crate::spool::Step::Read { bytes, total } => { |
| 500 | self.progress(Stage::Read, bytes, Some(total), 0) |
| 501 | } |
| 502 | })?; |
| 503 | self.direct_source = Some(guard); |
| 504 | Ok(snapshot) |
| 505 | } |
| 506 | fn verify_direct(&mut self) -> Result<()> { |
| 507 | if let Some(mut source) = self.direct_source.take() { |
| 508 | let result = source.verify(&mut |step| match step { |
| 509 | crate::spool::Step::Check => self.check(), |
| 510 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 511 | crate::spool::Step::Read { bytes, total } => { |
| 512 | self.progress(Stage::Verify, bytes, Some(total), 0) |
| 513 | } |
| 514 | }); |
| 515 | self.direct_source = Some(source); |
| 516 | result?; |
| 517 | } |
| 518 | if let Some(source) = self.direct_split.take() { |
| 519 | let result = source.verify(&mut |step| match step { |
| 520 | crate::spool::Step::Check => self.check(), |
| 521 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 522 | crate::spool::Step::Read { bytes, total } => { |
| 523 | self.progress(Stage::Verify, bytes, Some(total), 0) |
| 524 | } |
| 525 | }); |
| 526 | self.direct_split = Some(source); |
| 527 | self.split_result(result)?; |
| 528 | } |
| 529 | Ok(()) |
| 530 | } |
| 531 | fn list_direct_split(&mut self, path: &std::path::Path, limits: Limits) -> Result<()> { |
| 532 | let metadata_limits = self.metadata_limits(); |
| 533 | let opened = |
| 534 | crate::split_seven_zip::open_direct(path, limits.input, metadata_limits, &mut |step| { |
| 535 | match step { |
| 536 | crate::spool::Step::Check => self.check(), |
| 537 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 538 | crate::spool::Step::Read { bytes, total } => { |
| 539 | self.progress(Stage::Read, bytes, Some(total), 0) |
| 540 | } |
| 541 | } |
| 542 | }); |
| 543 | let mut source = self.split_result(opened)?.ok_or(ErrorCode::Internal)?; |
| 544 | let length = source.len(); |
| 545 | let object = self.split_result(source.object())?; |
| 546 | let hash = source.hash; |
| 547 | let result = crate::spool::retry_full(|| { |
| 548 | crate::seven_zip::open(&mut source, length, limits, false, self) |
| 549 | }); |
| 550 | self.direct_split = Some(source); |
| 551 | let catalog = result?; |
| 552 | for member in &catalog.members { |
| 553 | self.check()?; |
| 554 | completed(self.event(Message::Entry(member.entry.clone())), self)?; |
| 555 | } |
| 556 | self.verify_direct()?; |
| 557 | completed( |
| 558 | self.event(Message::ListEnd { |
| 559 | entry_count: catalog.members.len() as u32, |
| 560 | list_id: ListId { |
| 561 | catalog_version: 2, |
| 562 | format: Format::SevenZip, |
| 563 | source_object: object, |
| 564 | archive_bytes: length, |
| 565 | archive_sha256: hash, |
| 566 | }, |
| 567 | }), |
| 568 | self, |
| 569 | ) |
| 570 | } |
| 571 | fn preview( |
| 572 | &mut self, |
| 573 | archive: NativePath, |
| 574 | entry_id: u32, |
| 575 | expected: ListId, |
| 576 | limits: Limits, |
| 577 | ) -> Result<()> { |
| 578 | use sha2::{Digest, Sha256}; |
| 579 | use std::io::{Read, Seek, SeekFrom}; |
| 580 | let path = archive.to_path()?; |
| 581 | if crate::split_seven_zip::is_split(&path) |
| 582 | || crate::split_seven_zip::unsupported_split(&path) |
| 583 | || matches!(expected.source_object, SourceObject::SplitSevenZip { .. }) |
| 584 | { |
| 585 | return Err(ErrorCode::UnsupportedFeature); |
| 586 | } |
| 587 | self.progress(Stage::Read, 0, None, 0)?; |
| 588 | let mut snapshot = self.direct_snapshot(&path, limits.input)?; |
| 589 | if expected.catalog_version != 1 |
| 590 | || expected.source_object != snapshot.object |
| 591 | || expected.archive_bytes != snapshot.len |
| 592 | || expected.archive_sha256 != snapshot.hash |
| 593 | { |
| 594 | return Err(ErrorCode::SourceChanged); |
| 595 | } |
| 596 | let mut catalog = crate::streaming::Catalog::open( |
| 597 | &mut snapshot.file, |
| 598 | snapshot.len, |
| 599 | limits, |
| 600 | false, |
| 601 | None, |
| 602 | self, |
| 603 | )?; |
| 604 | if expected.format != catalog.format { |
| 605 | return Err(ErrorCode::SourceChanged); |
| 606 | } |
| 607 | let entry = catalog |
| 608 | .members |
| 609 | .get(entry_id as usize) |
| 610 | .ok_or(ErrorCode::InvalidRequest)? |
| 611 | .entry |
| 612 | .clone(); |
| 613 | if entry.entry_id != entry_id || entry.kind != EntryKind::File { |
| 614 | return Err(ErrorCode::InvalidRequest); |
| 615 | } |
| 616 | let name = if catalog.format == Format::Gzip { |
| 617 | let name = path |
| 618 | .file_name() |
| 619 | .and_then(|s| s.to_str()) |
| 620 | .ok_or(ErrorCode::UnsupportedFeature)?; |
| 621 | if !name.to_ascii_lowercase().ends_with(".gz") { |
| 622 | return Err(ErrorCode::UnsupportedFeature); |
| 623 | } |
| 624 | &name[..name.len() - 3] |
| 625 | } else { |
| 626 | &entry.name |
| 627 | }; |
| 628 | let kind = crate::preview::Kind::from_name(name)?; |
| 629 | if entry.size > kind.limit() { |
| 630 | return Err(ErrorCode::Limit); |
| 631 | } |
| 632 | self.progress(Stage::Decode, 0, Some(entry.size), 0)?; |
| 633 | if matches!(catalog.format, Format::Zip | Format::SevenZip) { |
| 634 | for attempt in 1..=3 { |
| 635 | let secret = if entry.encrypted { |
| 636 | Some(self.password(PasswordPurpose::Decrypt, attempt)?) |
| 637 | } else { |
| 638 | None |
| 639 | }; |
| 640 | match crate::streaming::Catalog::preview( |
| 641 | &mut snapshot.file, |
| 642 | snapshot.len, |
| 643 | limits, |
| 644 | secret.as_ref().map(|s| s.0.as_slice()), |
| 645 | entry_id, |
| 646 | self, |
| 647 | ) { |
| 648 | Ok(decoded) => { |
| 649 | catalog = decoded; |
| 650 | break; |
| 651 | } |
| 652 | Err(ErrorCode::WrongPassword) if entry.encrypted && attempt < 3 => continue, |
| 653 | Err(error) => return Err(error), |
| 654 | } |
| 655 | } |
| 656 | } |
| 657 | let mut bytes = Vec::new(); |
| 658 | bytes |
| 659 | .try_reserve_exact(entry.size as usize) |
| 660 | .map_err(|_| ErrorCode::Limit)?; |
| 661 | catalog |
| 662 | .data |
| 663 | .seek(SeekFrom::Start(catalog.offsets[entry_id as usize])) |
| 664 | .map_err(crate::space::io_error)?; |
| 665 | let mut remaining = entry.size; |
| 666 | let mut chunk = [0; 32768]; |
| 667 | while remaining != 0 { |
| 668 | self.check()?; |
| 669 | let length = remaining.min(chunk.len() as u64) as usize; |
| 670 | catalog |
| 671 | .data |
| 672 | .read_exact(&mut chunk[..length]) |
| 673 | .map_err(|_| ErrorCode::Integrity)?; |
| 674 | bytes.extend_from_slice(&chunk[..length]); |
| 675 | remaining -= length as u64; |
| 676 | completed(Ok(()), self)?; |
| 677 | } |
| 678 | let (info, bytes) = crate::preview::decode(kind, entry_id, bytes, self)?; |
| 679 | self.check()?; |
| 680 | self.verify_direct()?; |
| 681 | let hash: [u8; 32] = Sha256::digest(&bytes).into(); |
| 682 | completed(self.event(Message::PreviewBegin(info)), self)?; |
| 683 | for (index, chunk) in bytes.chunks(MAX_PREVIEW_CHUNK_BYTES).enumerate() { |
| 684 | self.check()?; |
| 685 | completed( |
| 686 | self.event(Message::PreviewChunk { |
| 687 | entry_id, |
| 688 | offset: (index * MAX_PREVIEW_CHUNK_BYTES) as u64, |
| 689 | data: chunk.to_vec(), |
| 690 | }), |
| 691 | self, |
| 692 | )?; |
| 693 | } |
| 694 | self.check()?; |
| 695 | completed( |
| 696 | self.event(Message::PreviewEnd { |
| 697 | entry_id, |
| 698 | total_bytes: info.total_bytes, |
| 699 | sha256: hash, |
| 700 | }), |
| 701 | self, |
| 702 | )?; |
| 703 | Ok(()) |
| 704 | } |
| 705 | fn run(&mut self, start: Start) -> Result<()> { |
| 706 | if !start.limits.valid() { |
| 707 | return Err(ErrorCode::InvalidRequest); |
| 708 | } |
| 709 | let limits = self.budget.as_ref().map_or(start.limits, |b| b.ceiling); |
| 710 | self.event(Message::Accepted { |
| 711 | action: start.action.kind(), |
| 712 | encryption: !matches!( |
| 713 | start.action, |
| 714 | Action::CreateSevenZip { .. } | Action::RecoverZip { .. } |
| 715 | ), |
| 716 | })?; |
| 717 | self.check()?; |
| 718 | if let Action::CreateSevenZip { |
| 719 | sources, |
| 720 | solid, |
| 721 | encryption, |
| 722 | .. |
| 723 | } = &start.action |
| 724 | { |
| 725 | if *solid || *encryption != Encryption::None { |
| 726 | return Err(ErrorCode::UnsupportedFeature); |
| 727 | } |
| 728 | if sources.is_empty() { |
| 729 | return Err(ErrorCode::InvalidRequest); |
| 730 | } |
| 731 | } |
| 732 | // 해제의 원본 사본과 단계 임시 파일은 출력 폴더에 둠. 폴더를 열 수 없으면 기존 위치를 |
| 733 | // 쓰고, 오류는 아래의 원래 출력 폴더 확인 지점에서 같은 순서로 보고함. |
| 734 | let _spool_location = match &start.action { |
| 735 | Action::Extract { destination, .. } => destination |
| 736 | .to_path() |
| 737 | .ok() |
| 738 | .and_then(|path| Dir::root(&path).ok()) |
| 739 | .map(|root| crate::spool::place_in(&root)) |
| 740 | .transpose()?, |
| 741 | Action::List { archive } | Action::Preview { archive, .. } => { |
| 742 | Some(crate::spool::fallback_for(&archive.to_path()?)) |
| 743 | } |
| 744 | _ => None, |
| 745 | }; |
| 746 | if let Some(budget) = &self.budget { |
| 747 | let scope = ResourceScope { |
| 748 | output: budget.ceiling.output > budget.soft.output, |
| 749 | entries: budget.ceiling.entries > budget.soft.entries, |
| 750 | ratio: false, |
| 751 | }; |
| 752 | if scope.any() { |
| 753 | let temporary = crate::spool::temporary()?; |
| 754 | self.request_resource(scope, ResourceUsage::default(), Some(&temporary))?; |
| 755 | } |
| 756 | } |
| 757 | match start.action { |
| 758 | Action::RecoverZip { |
| 759 | archive: source, |
| 760 | output_file, |
| 761 | } => { |
| 762 | let source = source.to_path()?; |
| 763 | let output = output_file.to_path()?; |
| 764 | let leaf = output |
| 765 | .file_name() |
| 766 | .and_then(|n| n.to_str()) |
| 767 | .ok_or(ErrorCode::InvalidRequest)?; |
| 768 | let name = archive::valid_name(leaf, false)?; |
| 769 | let root = completed( |
| 770 | Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?), |
| 771 | self, |
| 772 | )?; |
| 773 | filesystem::preflight_mode_with( |
| 774 | &root, |
| 775 | &[(name.clone(), EntryKind::File)], |
| 776 | false, |
| 777 | self, |
| 778 | )?; |
| 779 | self.progress(Stage::Scan, 0, None, 0)?; |
| 780 | let mut recovery = crate::zip_recovery::Recovery::open(&source, limits, self)?; |
| 781 | for finding in &recovery.findings { |
| 782 | self.event(Message::RecoveryEntry(finding.clone()))?; |
| 783 | } |
| 784 | self.event(Message::RecoveryEnd(recovery.summary.clone()))?; |
| 785 | if recovery.summary.verified_entries == 0 { |
| 786 | return Err(ErrorCode::RecoveryImpossible); |
| 787 | } |
| 788 | let incomplete = !recovery.summary.complete(); |
| 789 | let (mut data, length) = recovery.build(limits, self)?; |
| 790 | filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?; |
| 791 | self.recovery = Some(recovery); |
| 792 | self.output_reader(&root, &name, &mut data, length, None, true, None)?; |
| 793 | self.terminal.publication = Publication::Complete; |
| 794 | if incomplete { |
| 795 | return Err(ErrorCode::RecoveryIncomplete); |
| 796 | } |
| 797 | } |
| 798 | Action::List { |
| 799 | archive: ref source, |
| 800 | } |
| 801 | | Action::Extract { |
| 802 | archive: ref source, |
| 803 | .. |
| 804 | } => { |
| 805 | let extract = matches!(start.action, Action::Extract { .. }); |
| 806 | let path = source.to_path()?; |
| 807 | self.progress( |
| 808 | if crate::split_seven_zip::is_split(&path) { |
| 809 | Stage::Scan |
| 810 | } else { |
| 811 | Stage::Read |
| 812 | }, |
| 813 | 0, |
| 814 | None, |
| 815 | 0, |
| 816 | )?; |
| 817 | let expected = match &start.action { |
| 818 | Action::Extract { list_id, .. } => list_id.as_ref(), |
| 819 | _ => None, |
| 820 | }; |
| 821 | if !extract && crate::split_seven_zip::is_split(&path) { |
| 822 | return self.list_direct_split(&path, limits); |
| 823 | } |
| 824 | let metadata_limits = self.metadata_limits(); |
| 825 | let captured = crate::split_seven_zip::open( |
| 826 | &path, |
| 827 | expected, |
| 828 | limits.input, |
| 829 | metadata_limits, |
| 830 | &mut |step| match step { |
| 831 | crate::spool::Step::Check => self.check(), |
| 832 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 833 | crate::spool::Step::Read { bytes, total } => { |
| 834 | self.progress(Stage::Read, bytes, Some(total), 0) |
| 835 | } |
| 836 | }, |
| 837 | ); |
| 838 | let mut snapshot = if let Some(captured) = self.split_result(captured)? { |
| 839 | self.source_group = Some(captured.group); |
| 840 | captured.snapshot |
| 841 | } else if !extract { |
| 842 | self.direct_snapshot(&path, limits.input)? |
| 843 | } else { |
| 844 | crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| { |
| 845 | match step { |
| 846 | crate::spool::Step::Check => self.check(), |
| 847 | crate::spool::Step::Activity => completed(Ok(()), self), |
| 848 | crate::spool::Step::Read { bytes, total } => { |
| 849 | self.progress(Stage::Read, bytes, Some(total), 0) |
| 850 | } |
| 851 | } |
| 852 | })? |
| 853 | }; |
| 854 | if let Action::Extract { |
| 855 | list_id: Some(expected), |
| 856 | .. |
| 857 | } = &start.action |
| 858 | { |
| 859 | if expected.catalog_version != if self.source_group.is_some() { 2 } else { 1 } |
| 860 | || expected.source_object != snapshot.object |
| 861 | || expected.archive_bytes != snapshot.len |
| 862 | || expected.archive_sha256 != snapshot.hash |
| 863 | { |
| 864 | return Err(ErrorCode::SourceChanged); |
| 865 | } |
| 866 | } |
| 867 | self.progress(Stage::Decode, snapshot.len, Some(snapshot.len), 0)?; |
| 868 | let mut catalog = crate::streaming::Catalog::open( |
| 869 | &mut snapshot.file, |
| 870 | snapshot.len, |
| 871 | limits, |
| 872 | false, |
| 873 | None, |
| 874 | self, |
| 875 | )?; |
| 876 | let list_id = ListId { |
| 877 | catalog_version: if self.source_group.is_some() { 2 } else { 1 }, |
| 878 | format: catalog.format, |
| 879 | source_object: snapshot.object, |
| 880 | archive_bytes: snapshot.len, |
| 881 | archive_sha256: snapshot.hash, |
| 882 | }; |
| 883 | if !extract { |
| 884 | for member in &catalog.members { |
| 885 | self.check()?; |
| 886 | completed(self.event(Message::Entry(member.entry.clone())), self)?; |
| 887 | } |
| 888 | self.verify_split()?; |
| 889 | self.verify_direct()?; |
| 890 | completed( |
| 891 | self.event(Message::ListEnd { |
| 892 | entry_count: catalog.members.len() as u32, |
| 893 | list_id, |
| 894 | }), |
| 895 | self, |
| 896 | )?; |
| 897 | } else if let Action::Extract { |
| 898 | destination, |
| 899 | selection, |
| 900 | list_id: expected, |
| 901 | gzip_output_name, |
| 902 | .. |
| 903 | } = start.action |
| 904 | { |
| 905 | if expected |
| 906 | .as_ref() |
| 907 | .is_some_and(|expected| *expected != list_id) |
| 908 | { |
| 909 | return Err(ErrorCode::SourceChanged); |
| 910 | } |
| 911 | let selected = match selection { |
| 912 | Selection::All => None, |
| 913 | Selection::EntryIds(ids) => { |
| 914 | if expected.is_none() || ids.is_empty() { |
| 915 | return Err(ErrorCode::InvalidRequest); |
| 916 | } |
| 917 | let mut set = BTreeSet::new(); |
| 918 | for id in ids { |
| 919 | if id as usize >= catalog.members.len() || !set.insert(id) { |
| 920 | return Err(ErrorCode::InvalidRequest); |
| 921 | } |
| 922 | completed(Ok(()), self)?; |
| 923 | } |
| 924 | Some(set) |
| 925 | } |
| 926 | }; |
| 927 | for member in &catalog.members { |
| 928 | if !matches!(member.entry.kind, EntryKind::File | EntryKind::Directory) { |
| 929 | return Err(ErrorCode::UnsafePath); |
| 930 | } |
| 931 | completed(Ok(()), self)?; |
| 932 | } |
| 933 | if catalog.format == Format::Gzip { |
| 934 | let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?; |
| 935 | let checked = archive::valid_name(&name, false) |
| 936 | .map_err(|_| ErrorCode::InvalidRequest)?; |
| 937 | if checked.contains('/') { |
| 938 | return Err(ErrorCode::InvalidRequest); |
| 939 | } |
| 940 | catalog.members[0].entry.name = checked; |
| 941 | } else if gzip_output_name.is_some() { |
| 942 | return Err(ErrorCode::InvalidRequest); |
| 943 | } |
| 944 | let root = completed(Dir::root(&destination.to_path()?), self)?; |
| 945 | let mut output_sizes = Vec::new(); |
| 946 | let mut staged_total = 0u64; |
| 947 | let mut encrypted = false; |
| 948 | for member in &catalog.members { |
| 949 | if member.entry.kind == EntryKind::File |
| 950 | && selected |
| 951 | .as_ref() |
| 952 | .is_none_or(|s| s.contains(&member.entry.entry_id)) |
| 953 | { |
| 954 | output_sizes.push((member.entry.name.clone(), member.entry.size)); |
| 955 | } |
| 956 | staged_total = staged_total |
| 957 | .checked_add(member.entry.size) |
| 958 | .ok_or(ErrorCode::Limit)?; |
| 959 | encrypted |= member.entry.encrypted; |
| 960 | completed(Ok(()), self)?; |
| 961 | } |
| 962 | let staged = matches!(catalog.format, Format::Zip | Format::SevenZip) |
| 963 | .then_some((&catalog.data, staged_total)); |
| 964 | // 선택 전에는 검증에 필요한 스테이징 공간만 계산함. |
| 965 | let initial_outputs = if self.interactive { |
| 966 | &[][..] |
| 967 | } else { |
| 968 | &output_sizes[..] |
| 969 | }; |
| 970 | filesystem::preflight_space_with(&root, initial_outputs, staged, self)?; |
| 971 | if matches!(catalog.format, Format::Zip | Format::SevenZip) { |
| 972 | for attempt in 1..=3 { |
| 973 | let secret = if encrypted { |
| 974 | Some(self.password(PasswordPurpose::Decrypt, attempt)?) |
| 975 | } else { |
| 976 | None |
| 977 | }; |
| 978 | match crate::streaming::Catalog::open( |
| 979 | &mut snapshot.file, |
| 980 | snapshot.len, |
| 981 | limits, |
| 982 | true, |
| 983 | secret.as_ref().map(|s| s.0.as_slice()), |
| 984 | self, |
| 985 | ) { |
| 986 | Ok(decoded) => { |
| 987 | catalog = decoded; |
| 988 | break; |
| 989 | } |
| 990 | Err(ErrorCode::WrongPassword) if attempt < 3 => continue, |
| 991 | Err(error) => return Err(error), |
| 992 | } |
| 993 | } |
| 994 | } |
| 995 | let offsets = catalog.offsets; |
| 996 | let mut data = catalog.data; |
| 997 | let mut members = Vec::new(); |
| 998 | for member in catalog.members { |
| 999 | if selected |
| 1000 | .as_ref() |
| 1001 | .is_none_or(|s| s.contains(&member.entry.entry_id)) |
| 1002 | { |
| 1003 | members.push(member); |
| 1004 | } |
| 1005 | completed(Ok(()), self)?; |
| 1006 | } |
| 1007 | let dirs = archive::output_directories(&members, self)?; |
| 1008 | let files = members |
| 1009 | .iter() |
| 1010 | .filter(|m| m.entry.kind == EntryKind::File) |
| 1011 | .map(|member| completed(Ok(member), self)) |
| 1012 | .collect::<Result<Vec<_>>>()?; |
| 1013 | let mut names = dirs |
| 1014 | .iter() |
| 1015 | .map(|name| completed(Ok((name.clone(), EntryKind::Directory)), self)) |
| 1016 | .collect::<Result<Vec<_>>>()?; |
| 1017 | names.extend( |
| 1018 | files |
| 1019 | .iter() |
| 1020 | .map(|member| { |
| 1021 | completed(Ok((member.entry.name.clone(), EntryKind::File)), self) |
| 1022 | }) |
| 1023 | .collect::<Result<Vec<_>>>()?, |
| 1024 | ); |
| 1025 | filesystem::preflight_mode_with(&root, &names, self.interactive, self)?; |
| 1026 | if !self.interactive { |
| 1027 | filesystem::preflight_space_with(&root, &output_sizes, None, self)?; |
| 1028 | } |
| 1029 | let mut reserved = names |
| 1030 | .iter() |
| 1031 | .map(|(name, _)| completed(Ok(name.to_lowercase()), self)) |
| 1032 | .collect::<Result<BTreeSet<_>>>()?; |
| 1033 | for name in dirs { |
| 1034 | self.check()?; |
| 1035 | let (created, durability, sync_error) = |
| 1036 | filesystem::directory_steps(&root, &name, &mut |step| { |
| 1037 | self.publication_step(step, false) |
| 1038 | })?; |
| 1039 | if created { |
| 1040 | self.terminal.created_count += 1; |
| 1041 | self.terminal.publication = Publication::Partial; |
| 1042 | self.terminal.durability = durability; |
| 1043 | self.event(Message::Output { |
| 1044 | entry_id: None, |
| 1045 | relative_name: name, |
| 1046 | disposition: Disposition::Created, |
| 1047 | })?; |
| 1048 | if let Some(error) = sync_error { |
| 1049 | return Err(error); |
| 1050 | } |
| 1051 | completed(Ok(()), self)?; |
| 1052 | } |
| 1053 | } |
| 1054 | for (index, m) in files.iter().enumerate() { |
| 1055 | completed( |
| 1056 | data.seek(SeekFrom::Start(offsets[m.entry.entry_id as usize])) |
| 1057 | .map_err(|_| ErrorCode::Io), |
| 1058 | self, |
| 1059 | )?; |
| 1060 | self.check()?; |
| 1061 | let existing = if self.interactive { |
| 1062 | filesystem::existing_with(&root, &m.entry.name, self)? |
| 1063 | } else { |
| 1064 | None |
| 1065 | }; |
| 1066 | let mut name = m.entry.name.clone(); |
| 1067 | let mut replace = None; |
| 1068 | if let Some(ref existing) = existing { |
| 1069 | let choice = self.conflict(&m.entry, existing.size)?; |
| 1070 | self.check()?; |
| 1071 | if choice == ConflictChoice::Rename { |
| 1072 | name = self.rename(&root, &name, &reserved)?; |
| 1073 | reserved.insert(name.to_lowercase()); |
| 1074 | } else if choice == ConflictChoice::Overwrite { |
| 1075 | replace = Some(existing); |
| 1076 | } |
| 1077 | completed( |
| 1078 | self.event(Message::ConflictResolved { |
| 1079 | entry_id: m.entry.entry_id, |
| 1080 | relative_name: name.clone(), |
| 1081 | choice, |
| 1082 | }), |
| 1083 | self, |
| 1084 | )?; |
| 1085 | if choice == ConflictChoice::Skip { |
| 1086 | continue; |
| 1087 | } |
| 1088 | } |
| 1089 | if self.interactive { |
| 1090 | // 건너뛴 파일을 제외하고 이번에 게시할 파일의 공간을 확인함. |
| 1091 | filesystem::preflight_space_with( |
| 1092 | &root, |
| 1093 | &[(name.clone(), m.entry.size)], |
| 1094 | None, |
| 1095 | self, |
| 1096 | )?; |
| 1097 | } |
| 1098 | self.output_reader( |
| 1099 | &root, |
| 1100 | &name, |
| 1101 | &mut (&mut data).take(m.entry.size), |
| 1102 | m.entry.size, |
| 1103 | Some(m.entry.entry_id), |
| 1104 | index + 1 == files.len(), |
| 1105 | replace, |
| 1106 | )?; |
| 1107 | } |
| 1108 | // 건너뛰기 등 실제 게시가 없을 때도 완료 전에 원본을 확인함. |
| 1109 | self.verify_before_publication(None)?; |
| 1110 | if !self.interactive || self.terminal.created_count != 0 { |
| 1111 | self.terminal.publication = Publication::Complete; |
| 1112 | } |
| 1113 | } |
| 1114 | } |
| 1115 | Action::Preview { |
| 1116 | archive, |
| 1117 | entry_id, |
| 1118 | list_id, |
| 1119 | } => { |
| 1120 | self.preview(archive, entry_id, list_id, limits)?; |
| 1121 | } |
| 1122 | Action::CreateZip { |
| 1123 | sources, |
| 1124 | output_file, |
| 1125 | method, |
| 1126 | encryption, |
| 1127 | } => { |
| 1128 | let output = output_file.to_path()?; |
| 1129 | let leaf = output |
| 1130 | .file_name() |
| 1131 | .and_then(|n| n.to_str()) |
| 1132 | .ok_or(ErrorCode::InvalidRequest)?; |
| 1133 | let name = archive::valid_name(leaf, false)?; |
| 1134 | let root = completed( |
| 1135 | Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?), |
| 1136 | self, |
| 1137 | )?; |
| 1138 | filesystem::preflight_mode_with( |
| 1139 | &root, |
| 1140 | &[(name.clone(), EntryKind::File)], |
| 1141 | false, |
| 1142 | self, |
| 1143 | )?; |
| 1144 | let members = crate::create::plan(&sources, limits, self)?; |
| 1145 | let secret = if encryption == Encryption::Aes256 { |
| 1146 | let secret = self.password(PasswordPurpose::Encrypt, 1)?; |
| 1147 | if secret.0.is_empty() { |
| 1148 | return Err(ErrorCode::InvalidRequest); |
| 1149 | } |
| 1150 | Some(secret) |
| 1151 | } else { |
| 1152 | None |
| 1153 | }; |
| 1154 | let (mut data, length) = crate::create::zip( |
| 1155 | &members, |
| 1156 | method, |
| 1157 | limits, |
| 1158 | secret.as_ref().map(|s| s.0.as_slice()), |
| 1159 | self, |
| 1160 | )?; |
| 1161 | filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?; |
| 1162 | self.output_reader(&root, &name, &mut data, length, None, true, None)?; |
| 1163 | self.terminal.publication = Publication::Complete; |
| 1164 | } |
| 1165 | Action::CreateSevenZip { |
| 1166 | sources, |
| 1167 | output_file, |
| 1168 | volume_size, |
| 1169 | .. |
| 1170 | } => { |
| 1171 | let output = output_file.to_path()?; |
| 1172 | let leaf = output |
| 1173 | .file_name() |
| 1174 | .and_then(|n| n.to_str()) |
| 1175 | .ok_or(ErrorCode::InvalidRequest)?; |
| 1176 | let name = archive::valid_name(leaf, false)?; |
| 1177 | let parent = output.parent().ok_or(ErrorCode::InvalidRequest)?; |
| 1178 | let root = completed(Dir::root(parent), self)?; |
| 1179 | if let Some(size) = volume_size { |
| 1180 | // 분할 읽기가 찾는 `이름.7z.001` 형식만 만들고 너무 작은 볼륨은 거부함. |
| 1181 | if size < MIN_SEVEN_ZIP_VOLUME_BYTES |
| 1182 | || !name.to_ascii_lowercase().ends_with(".7z") |
| 1183 | { |
| 1184 | return Err(ErrorCode::InvalidRequest); |
| 1185 | } |
| 1186 | filesystem::preflight_mode_with( |
| 1187 | &root, |
| 1188 | &[( |
| 1189 | crate::seven_zip_create::volume_name(&name, 1)?, |
| 1190 | EntryKind::File, |
| 1191 | )], |
| 1192 | false, |
| 1193 | self, |
| 1194 | )?; |
| 1195 | self.split_names_free(parent, &name)?; |
| 1196 | } else { |
| 1197 | filesystem::preflight_mode_with( |
| 1198 | &root, |
| 1199 | &[(name.clone(), EntryKind::File)], |
| 1200 | false, |
| 1201 | self, |
| 1202 | )?; |
| 1203 | } |
| 1204 | self.progress(Stage::Scan, 0, None, 0)?; |
| 1205 | let mut plan = crate::create::plan(&sources, limits, self)?; |
| 1206 | let (mut data, length) = crate::seven_zip_create::archive(&mut plan, limits, self)?; |
| 1207 | if let Some(size) = volume_size { |
| 1208 | let files = crate::seven_zip_create::volumes(&name, length, size)?; |
| 1209 | let kinds = files |
| 1210 | .iter() |
| 1211 | .map(|(file, _)| (file.clone(), EntryKind::File)) |
| 1212 | .collect::<Vec<_>>(); |
| 1213 | // 모든 볼륨 이름이 비어 있는지 다시 확인함. 압축하는 사이 생긴 이름도 거부함. |
| 1214 | filesystem::preflight_mode_with(&root, &kinds, false, self)?; |
| 1215 | self.split_names_free(parent, &name)?; |
| 1216 | filesystem::preflight_space_with(&root, &files, None, self)?; |
| 1217 | self.creation_plan = Some(plan); |
| 1218 | self.output_set(&root, &files, &mut data)?; |
| 1219 | } else { |
| 1220 | filesystem::preflight_space_with(&root, &[(name.clone(), length)], None, self)?; |
| 1221 | self.creation_plan = Some(plan); |
| 1222 | self.output_reader(&root, &name, &mut data, length, None, true, None)?; |
| 1223 | } |
| 1224 | self.terminal.publication = Publication::Complete; |
| 1225 | } |
| 1226 | } |
| 1227 | self.cutoff()?; |
| 1228 | Ok(()) |
| 1229 | } |
| 1230 | } |
| 1231 | impl<W: Write> Job<W> { |
| 1232 | /// 분할 읽기는 같은 폴더의 `이름.7z.<숫자>`를 모두 한 묶음으로 보므로, |
| 1233 | /// 자릿수와 관계없이 그런 이름이 하나라도 있으면 새 볼륨을 만들지 않음. |
| 1234 | fn split_names_free(&mut self, parent: &std::path::Path, name: &str) -> Result<()> { |
| 1235 | let fold = |value: &str| { |
| 1236 | if cfg!(windows) { |
| 1237 | value.to_lowercase() |
| 1238 | } else { |
| 1239 | value.to_owned() |
| 1240 | } |
| 1241 | }; |
| 1242 | let prefix = fold(&format!("{name}.")); |
| 1243 | let entries = completed( |
| 1244 | std::fs::read_dir(parent).map_err(crate::space::io_error), |
| 1245 | self, |
| 1246 | )?; |
| 1247 | for entry in entries { |
| 1248 | self.check()?; |
| 1249 | let leaf = entry.map_err(crate::space::io_error)?.file_name(); |
| 1250 | let leaf = fold(&leaf.to_string_lossy()); |
| 1251 | if let Some(suffix) = leaf.strip_prefix(&prefix) { |
| 1252 | if !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit()) { |
| 1253 | return Err(ErrorCode::Conflict); |
| 1254 | } |
| 1255 | } |
| 1256 | completed(Ok(()), self)?; |
| 1257 | } |
| 1258 | Ok(()) |
| 1259 | } |
| 1260 | } |
| 1261 | impl<W: Write> Monitor for Job<W> { |
| 1262 | fn progress( |
| 1263 | &mut self, |
| 1264 | stage: Stage, |
| 1265 | bytes: u64, |
| 1266 | total: Option<u64>, |
| 1267 | entries: u32, |
| 1268 | ) -> Result<()> { |
| 1269 | Job::progress(self, stage, bytes, total, entries) |
| 1270 | } |
| 1271 | fn metadata_limits(&self) -> archive::MetadataLimits { |
| 1272 | self.budget |
| 1273 | .as_ref() |
| 1274 | .map_or_else(archive::MetadataLimits::default, |b| b.metadata_limits()) |
| 1275 | } |
| 1276 | fn check(&mut self) -> Result<()> { |
| 1277 | Job::check(self) |
| 1278 | } |
| 1279 | fn activity(&mut self) -> Result<()> { |
| 1280 | self.check()?; |
| 1281 | self.watchdog.activity(self.started.elapsed()) |
| 1282 | } |
| 1283 | fn observe(&mut self, usage: ResourceUsage, storage: Option<&std::fs::File>) -> Result<()> { |
| 1284 | self.check()?; |
| 1285 | let Some(budget) = &self.budget else { |
| 1286 | return Ok(()); |
| 1287 | }; |
| 1288 | let scope = budget.required(usage)?; |
| 1289 | if !scope.any() { |
| 1290 | return Ok(()); |
| 1291 | } |
| 1292 | self.request_resource(scope, usage, storage) |
| 1293 | } |
| 1294 | } |
| 1295 | |
| 1296 | pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( |
| 1297 | input: R, |
| 1298 | output: W, |
| 1299 | ) -> std::io::Result<()> { |
| 1300 | let parent = crate::parent::Parent::capture() |
| 1301 | .map_err(|_| std::io::Error::other("worker parent unavailable"))?; |
| 1302 | let mut reader = Reader::new(input); |
| 1303 | let (job, _, message) = reader |
| 1304 | .read()? |
| 1305 | .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::UnexpectedEof))?; |
| 1306 | let (start, interactive, budget) = match message { |
| 1307 | Message::Start(start) => (start, false, None), |
| 1308 | Message::StartInteractive(start) => (start, true, None), |
| 1309 | Message::StartGuarded(guarded) if guarded.valid() => { |
| 1310 | let budget = Budget { |
| 1311 | soft: guarded.start.limits, |
| 1312 | ceiling: guarded.ceiling, |
| 1313 | granted: ResourceScope::default(), |
| 1314 | }; |
| 1315 | (guarded.start, guarded.interactive, Some(budget)) |
| 1316 | } |
| 1317 | _ => { |
| 1318 | return Err(std::io::Error::new( |
| 1319 | std::io::ErrorKind::InvalidData, |
| 1320 | "Start required", |
| 1321 | )); |
| 1322 | } |
| 1323 | }; |
| 1324 | let state = Arc::new(Mutex::new(State { |
| 1325 | writer: Writer::new(output, job), |
| 1326 | cancelled: false, |
| 1327 | phase: 0, |
| 1328 | fault: None, |
| 1329 | challenge: None, |
| 1330 | conflict_reply: None, |
| 1331 | password: None, |
| 1332 | resource_reply: None, |
| 1333 | input_closed: false, |
| 1334 | })); |
| 1335 | let wake = Arc::new(Condvar::new()); |
| 1336 | let control_wake = Arc::clone(&wake); |
| 1337 | let control = Arc::clone(&state); |
| 1338 | std::thread::spawn(move || { |
| 1339 | loop { |
| 1340 | let command = reader.read(); |
| 1341 | let Ok(Some((_, sequence, message))) = command else { |
| 1342 | if let Ok(mut state) = control.lock() { |
| 1343 | state.input_closed = true; |
| 1344 | if command.is_err() && state.phase < 2 { |
| 1345 | state.fault = Some(ErrorCode::Protocol); |
| 1346 | } |
| 1347 | control_wake.notify_all(); |
| 1348 | } |
| 1349 | break; |
| 1350 | }; |
| 1351 | let Ok(mut state) = control.lock() else { |
| 1352 | break; |
| 1353 | }; |
| 1354 | if state.phase == 3 { |
| 1355 | break; |
| 1356 | } |
| 1357 | match message { |
| 1358 | Message::Password { |
| 1359 | challenge_id, |
| 1360 | secret, |
| 1361 | } => { |
| 1362 | if state.phase != 0 |
| 1363 | || state.challenge != Some(Challenge::Password(challenge_id)) |
| 1364 | || state.password.is_some() |
| 1365 | { |
| 1366 | state.fault = Some(ErrorCode::Protocol); |
| 1367 | } else { |
| 1368 | state.challenge = None; |
| 1369 | if !state.cancelled { |
| 1370 | state.password = Some(secret); |
| 1371 | } |
| 1372 | } |
| 1373 | control_wake.notify_all(); |
| 1374 | } |
| 1375 | Message::ConflictReply { |
| 1376 | challenge_id, |
| 1377 | choice, |
| 1378 | apply_to_remaining, |
| 1379 | } => { |
| 1380 | if state.phase != 0 |
| 1381 | || state.challenge != Some(Challenge::Conflict(challenge_id)) |
| 1382 | || state.conflict_reply.is_some() |
| 1383 | { |
| 1384 | state.fault = Some(ErrorCode::Protocol); |
| 1385 | } else { |
| 1386 | state.challenge = None; |
| 1387 | if !state.cancelled { |
| 1388 | state.conflict_reply = Some((choice, apply_to_remaining)); |
| 1389 | } |
| 1390 | } |
| 1391 | control_wake.notify_all(); |
| 1392 | } |
| 1393 | Message::ResourceReply { |
| 1394 | challenge_id, |
| 1395 | scope, |
| 1396 | allow, |
| 1397 | } => { |
| 1398 | if state.phase != 0 |
| 1399 | || state.challenge != Some(Challenge::Resource(challenge_id, scope)) |
| 1400 | || state.resource_reply.is_some() |
| 1401 | { |
| 1402 | state.fault = Some(ErrorCode::Protocol); |
| 1403 | } else { |
| 1404 | state.challenge = None; |
| 1405 | if !state.cancelled { |
| 1406 | state.resource_reply = Some(allow); |
| 1407 | } |
| 1408 | } |
| 1409 | control_wake.notify_all(); |
| 1410 | } |
| 1411 | Message::Cancel => { |
| 1412 | let status = match state.phase { |
| 1413 | 2 => CancelStatus::Finished, |
| 1414 | 1 => CancelStatus::TooLate, |
| 1415 | _ if state.cancelled => CancelStatus::AlreadyRequested, |
| 1416 | _ => { |
| 1417 | state.cancelled = true; |
| 1418 | CancelStatus::Requested |
| 1419 | } |
| 1420 | }; |
| 1421 | control_wake.notify_all(); |
| 1422 | if state |
| 1423 | .writer |
| 1424 | .send(&Message::CancelAck { |
| 1425 | request_sequence: sequence, |
| 1426 | status, |
| 1427 | }) |
| 1428 | .is_err() |
| 1429 | { |
| 1430 | state.fault = Some(ErrorCode::Io); |
| 1431 | break; |
| 1432 | } |
| 1433 | } |
| 1434 | _ => { |
| 1435 | state.fault = Some(ErrorCode::Protocol); |
| 1436 | break; |
| 1437 | } |
| 1438 | } |
| 1439 | } |
| 1440 | }); |
| 1441 | let mut context = Job { |
| 1442 | state: Arc::clone(&state), |
| 1443 | wake, |
| 1444 | next_challenge: 0, |
| 1445 | interactive, |
| 1446 | action: start.action.kind(), |
| 1447 | budget, |
| 1448 | watchdog: Watchdog::new(), |
| 1449 | remaining_choice: None, |
| 1450 | source_group: None, |
| 1451 | direct_source: None, |
| 1452 | direct_split: None, |
| 1453 | source_verified_for_publication: false, |
| 1454 | creation_plan: None, |
| 1455 | recovery: None, |
| 1456 | parent, |
| 1457 | started: Instant::now(), |
| 1458 | terminal: Terminal { |
| 1459 | outcome: Outcome::Completed, |
| 1460 | error: ErrorCode::None, |
| 1461 | publication: Publication::None, |
| 1462 | created_count: 0, |
| 1463 | retained_partial_count: 0, |
| 1464 | durability: Durability::NotApplicable, |
| 1465 | cleanup: Cleanup::Complete, |
| 1466 | detail: String::new(), |
| 1467 | }, |
| 1468 | }; |
| 1469 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 1470 | let result = context.run(start); |
| 1471 | if result.is_err() |
| 1472 | && !matches!( |
| 1473 | result, |
| 1474 | Err(ErrorCode::None | ErrorCode::Limit | ErrorCode::Protocol | ErrorCode::Internal) |
| 1475 | ) |
| 1476 | { |
| 1477 | context.verify_direct()?; |
| 1478 | } |
| 1479 | result |
| 1480 | })); |
| 1481 | let error = match result { |
| 1482 | Ok(r) => r.err(), |
| 1483 | Err(_) => { |
| 1484 | context.terminal.publication = Publication::Uncertain; |
| 1485 | context.terminal.cleanup = Cleanup::Unconfirmed; |
| 1486 | Some(ErrorCode::Internal) |
| 1487 | } |
| 1488 | }; |
| 1489 | // 출력 폴더의 임시 파일 이름을 지우지 못했으면 남은 파일이 있다고 알림. |
| 1490 | if crate::spool::take_leftover() { |
| 1491 | context.terminal.cleanup = Cleanup::Failed; |
| 1492 | } |
| 1493 | let mut state = state |
| 1494 | .lock() |
| 1495 | .map_err(|_| std::io::Error::other("worker state poisoned"))?; |
| 1496 | state.phase = 2; |
| 1497 | state.challenge = None; |
| 1498 | state.password = None; |
| 1499 | state.conflict_reply = None; |
| 1500 | state.resource_reply = None; |
| 1501 | if let Some(error) = state.fault.or(error) { |
| 1502 | context.terminal.error = error; |
| 1503 | context.terminal.outcome = if error == ErrorCode::None { |
| 1504 | Outcome::Cancelled |
| 1505 | } else { |
| 1506 | Outcome::Failed |
| 1507 | }; |
| 1508 | context.terminal.detail = match error { |
| 1509 | ErrorCode::None => "취소됨", |
| 1510 | ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원", |
| 1511 | ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함", |
| 1512 | ErrorCode::DiskFull => { |
| 1513 | "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요" |
| 1514 | } |
| 1515 | ErrorCode::Io => { |
| 1516 | "파일을 읽거나 쓰지 못했습니다. 디스크 여유 공간과 접근 권한을 확인하세요" |
| 1517 | } |
| 1518 | _ => "작업 실패. 오류 코드와 게시 상태를 확인해야 함", |
| 1519 | } |
| 1520 | .to_owned(); |
| 1521 | } |
| 1522 | state.writer.send(&Message::Terminal(context.terminal))?; |
| 1523 | state.phase = 3; |
| 1524 | Ok(()) |
| 1525 | } |