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