| 1 | use std::{collections::BTreeSet, path::PathBuf}; |
| 2 | |
| 3 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 4 | pub enum Format { |
| 5 | Zip, |
| 6 | Tar, |
| 7 | Gzip, |
| 8 | TarGzip, |
| 9 | SevenZip, |
| 10 | } |
| 11 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 12 | pub enum SourceObject { |
| 13 | Unix { device: u64, inode: u64 }, |
| 14 | Windows { volume: u64, file_id: [u8; 16] }, |
| 15 | SplitSevenZip { manifest_sha256: [u8; 32] }, |
| 16 | } |
| 17 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 18 | pub struct ListId { |
| 19 | pub catalog_version: u16, |
| 20 | pub format: Format, |
| 21 | pub source_object: SourceObject, |
| 22 | pub archive_bytes: u64, |
| 23 | pub archive_sha256: [u8; 32], |
| 24 | } |
| 25 | impl ListId { |
| 26 | pub fn valid(&self) -> bool { |
| 27 | matches!( |
| 28 | (self.catalog_version, self.format, &self.source_object), |
| 29 | ( |
| 30 | 1, |
| 31 | _, |
| 32 | SourceObject::Unix { .. } | SourceObject::Windows { .. } |
| 33 | ) | (2, Format::SevenZip, SourceObject::SplitSevenZip { .. }) |
| 34 | ) |
| 35 | } |
| 36 | pub fn is_split(&self) -> bool { |
| 37 | matches!(self.source_object, SourceObject::SplitSevenZip { .. }) |
| 38 | } |
| 39 | } |
| 40 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 41 | pub struct VolumeProblem { |
| 42 | pub reason: VolumeProblemReason, |
| 43 | pub volume: NativePath, |
| 44 | } |
| 45 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 46 | pub enum Selection { |
| 47 | All, |
| 48 | EntryIds(Vec<u32>), |
| 49 | } |
| 50 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 51 | pub enum Method { |
| 52 | Store, |
| 53 | Deflate, |
| 54 | } |
| 55 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 56 | pub enum Start { |
| 57 | List { |
| 58 | archive: PathBuf, |
| 59 | }, |
| 60 | Extract { |
| 61 | archive: PathBuf, |
| 62 | destination: PathBuf, |
| 63 | selection: Selection, |
| 64 | list_id: ListId, |
| 65 | gzip_output_name: Option<String>, |
| 66 | }, |
| 67 | Preview { |
| 68 | archive: PathBuf, |
| 69 | entry_id: u32, |
| 70 | list_id: ListId, |
| 71 | }, |
| 72 | RecoverZip { |
| 73 | archive: PathBuf, |
| 74 | output_file: PathBuf, |
| 75 | }, |
| 76 | CreateSevenZip { |
| 77 | sources: Vec<(PathBuf, String)>, |
| 78 | output_file: PathBuf, |
| 79 | }, |
| 80 | CreateZip { |
| 81 | sources: Vec<(PathBuf, String)>, |
| 82 | output_file: PathBuf, |
| 83 | method: Method, |
| 84 | aes256: bool, |
| 85 | }, |
| 86 | } |
| 87 | // 암호를 Debug와 로그에서 제외하고 소유 버퍼를 해제 전에 지움. |
| 88 | pub struct Secret(Vec<u8>); |
| 89 | impl Secret { |
| 90 | pub fn new(text: String) -> Result<Self, &'static str> { |
| 91 | let mut bytes = text.into_bytes(); |
| 92 | if bytes.is_empty() || bytes.len() > 1024 { |
| 93 | bytes.fill(0); |
| 94 | return Err("암호는 UTF-8 1~1024바이트로 입력하세요"); |
| 95 | } |
| 96 | Ok(Self(bytes)) |
| 97 | } |
| 98 | pub fn as_bytes(&self) -> &[u8] { |
| 99 | &self.0 |
| 100 | } |
| 101 | } |
| 102 | impl Drop for Secret { |
| 103 | fn drop(&mut self) { |
| 104 | self.0.fill(0); |
| 105 | } |
| 106 | } |
| 107 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 108 | pub enum ConflictChoice { |
| 109 | Overwrite, |
| 110 | Skip, |
| 111 | Rename, |
| 112 | } |
| 113 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 114 | pub struct Conflict { |
| 115 | pub challenge_id: u64, |
| 116 | pub entry_id: u32, |
| 117 | pub relative_name: String, |
| 118 | pub incoming_size: u64, |
| 119 | pub existing_size: u64, |
| 120 | } |
| 121 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 122 | pub struct Resolution { |
| 123 | pub entry_id: u32, |
| 124 | pub relative_name: String, |
| 125 | pub choice: ConflictChoice, |
| 126 | } |
| 127 | pub enum Command { |
| 128 | Start(Start), |
| 129 | StartExpanded(Start), |
| 130 | ResourceReply { |
| 131 | challenge_id: u64, |
| 132 | scope: ResourceScope, |
| 133 | allow: bool, |
| 134 | }, |
| 135 | Password { |
| 136 | challenge_id: u64, |
| 137 | secret: Secret, |
| 138 | }, |
| 139 | ConflictReply { |
| 140 | challenge_id: u64, |
| 141 | choice: ConflictChoice, |
| 142 | apply_to_remaining: bool, |
| 143 | }, |
| 144 | Cancel, |
| 145 | } |
| 146 | pub struct Request { |
| 147 | pub job_id: u64, |
| 148 | pub sequence: u64, |
| 149 | pub command: Command, |
| 150 | } |
| 151 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 152 | pub enum Kind { |
| 153 | File, |
| 154 | Directory, |
| 155 | Link, |
| 156 | Other, |
| 157 | } |
| 158 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 159 | pub struct Entry { |
| 160 | pub id: u32, |
| 161 | pub name: String, |
| 162 | pub kind: Kind, |
| 163 | pub bytes: Option<u64>, |
| 164 | pub packed: Option<u64>, |
| 165 | pub encrypted: bool, |
| 166 | } |
| 167 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 168 | pub enum CancelStatus { |
| 169 | Requested, |
| 170 | AlreadyRequested, |
| 171 | TooLate, |
| 172 | Finished, |
| 173 | } |
| 174 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 175 | pub enum Stage { |
| 176 | Scan, |
| 177 | Read, |
| 178 | Decode, |
| 179 | Write, |
| 180 | Verify, |
| 181 | Commit, |
| 182 | } |
| 183 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 184 | pub enum Outcome { |
| 185 | Completed, |
| 186 | Failed, |
| 187 | Cancelled, |
| 188 | } |
| 189 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 190 | pub enum ErrorCode { |
| 191 | RecoveryIncomplete, |
| 192 | RecoveryImpossible, |
| 193 | MissingVolume, |
| 194 | Integrity, |
| 195 | UnsupportedFormat, |
| 196 | UnsupportedFeature, |
| 197 | WrongPassword, |
| 198 | UnsafePath, |
| 199 | Conflict, |
| 200 | Limit, |
| 201 | Io, |
| 202 | DiskFull, |
| 203 | Protocol, |
| 204 | Internal, |
| 205 | SourceChanged, |
| 206 | InvalidRequest, |
| 207 | } |
| 208 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 209 | pub enum Publication { |
| 210 | None, |
| 211 | Partial, |
| 212 | Complete, |
| 213 | Uncertain, |
| 214 | } |
| 215 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 216 | pub enum Durability { |
| 217 | NotApplicable, |
| 218 | Synced, |
| 219 | Unconfirmed, |
| 220 | Failed, |
| 221 | } |
| 222 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 223 | pub enum Cleanup { |
| 224 | Complete, |
| 225 | Failed, |
| 226 | Unconfirmed, |
| 227 | } |
| 228 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 229 | pub enum Disposition { |
| 230 | Created, |
| 231 | PartialRetained, |
| 232 | Removed, |
| 233 | CommitUncertain, |
| 234 | } |
| 235 | #[derive(Clone, Debug)] |
| 236 | pub struct Terminal { |
| 237 | pub outcome: Outcome, |
| 238 | pub error: Option<ErrorCode>, |
| 239 | pub publication: Publication, |
| 240 | pub created_count: u64, |
| 241 | pub retained_partial_count: u64, |
| 242 | pub durability: Durability, |
| 243 | pub cleanup: Cleanup, |
| 244 | } |
| 245 | pub use worker_protocol::protocol::{ |
| 246 | ActionKind, Limits, NativePath, PreviewFormat, PreviewInfo, RecoveryEnd, RecoveryEntry, |
| 247 | RecoveryMode, RecoveryReason, RecoveryStatus, ResourceScope, ResourceUsage, |
| 248 | VolumeProblemReason, |
| 249 | }; |
| 250 | |
| 251 | pub struct Preview { |
| 252 | pub info: PreviewInfo, |
| 253 | pub data: Vec<u8>, |
| 254 | } |
| 255 | |
| 256 | struct PreviewBuffer { |
| 257 | info: PreviewInfo, |
| 258 | data: Vec<u8>, |
| 259 | ended: bool, |
| 260 | } |
| 261 | |
| 262 | impl PreviewBuffer { |
| 263 | fn chunk(&mut self, entry_id: u32, offset: u64, data: Vec<u8>) -> bool { |
| 264 | if self.ended |
| 265 | || entry_id != self.info.entry_id |
| 266 | || offset != self.data.len() as u64 |
| 267 | || data.is_empty() |
| 268 | || data.len() > 32 * 1024 |
| 269 | || (data.len() as u64) > self.info.total_bytes.saturating_sub(offset) |
| 270 | { |
| 271 | return false; |
| 272 | } |
| 273 | self.data.extend_from_slice(&data); |
| 274 | true |
| 275 | } |
| 276 | fn end(&mut self, entry_id: u32, total_bytes: u64, sha256: [u8; 32]) -> bool { |
| 277 | use sha2::{Digest, Sha256}; |
| 278 | if self.ended |
| 279 | || entry_id != self.info.entry_id |
| 280 | || total_bytes != self.info.total_bytes |
| 281 | || total_bytes != self.data.len() as u64 |
| 282 | || Sha256::digest(&self.data)[..] != sha256 |
| 283 | || (self.info.format == PreviewFormat::Utf8Text |
| 284 | && std::str::from_utf8(&self.data).is_err()) |
| 285 | { |
| 286 | return false; |
| 287 | } |
| 288 | self.ended = true; |
| 289 | true |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | #[derive(Clone, Debug)] |
| 294 | pub struct ResourceChallenge { |
| 295 | pub id: u64, |
| 296 | pub action: ActionKind, |
| 297 | pub scope: ResourceScope, |
| 298 | pub usage: ResourceUsage, |
| 299 | pub soft_limits: Limits, |
| 300 | pub ceiling: Limits, |
| 301 | } |
| 302 | |
| 303 | #[derive(Clone, Debug)] |
| 304 | pub enum Event { |
| 305 | RecoveryEntry(RecoveryEntry), |
| 306 | RecoveryEnd(RecoveryEnd), |
| 307 | VolumeProblem(VolumeProblem), |
| 308 | PreviewBegin(PreviewInfo), |
| 309 | PreviewChunk { |
| 310 | entry_id: u32, |
| 311 | offset: u64, |
| 312 | data: Vec<u8>, |
| 313 | }, |
| 314 | PreviewEnd { |
| 315 | entry_id: u32, |
| 316 | total_bytes: u64, |
| 317 | sha256: [u8; 32], |
| 318 | }, |
| 319 | ResourceRequired(ResourceChallenge), |
| 320 | Accepted { |
| 321 | encryption: bool, |
| 322 | }, |
| 323 | Entry(Entry), |
| 324 | ListEnd { |
| 325 | entry_count: u32, |
| 326 | list_id: ListId, |
| 327 | }, |
| 328 | PasswordRequired { |
| 329 | challenge_id: u64, |
| 330 | attempt: u32, |
| 331 | encrypt: bool, |
| 332 | }, |
| 333 | ConflictRequired(Conflict), |
| 334 | ConflictResolved(Resolution), |
| 335 | Progress { |
| 336 | stage: Stage, |
| 337 | processed: u64, |
| 338 | total: Option<u64>, |
| 339 | completed_entries: u64, |
| 340 | }, |
| 341 | Output { |
| 342 | entry_id: Option<u32>, |
| 343 | relative_name: String, |
| 344 | disposition: Disposition, |
| 345 | }, |
| 346 | CancelAck { |
| 347 | request_sequence: u64, |
| 348 | status: CancelStatus, |
| 349 | }, |
| 350 | Terminal(Terminal), |
| 351 | } |
| 352 | pub enum HostEvent { |
| 353 | Fault(String), |
| 354 | CleanupComplete, |
| 355 | Frame { |
| 356 | job_id: u64, |
| 357 | sequence: u64, |
| 358 | event: Event, |
| 359 | }, |
| 360 | StdoutEof, |
| 361 | StderrEof, |
| 362 | Exited { |
| 363 | success: bool, |
| 364 | }, |
| 365 | } |
| 366 | // 바이트 codec과 프로세스 소유는 작업자 어댑터에서 담당함. |
| 367 | // 전송 실패 후에도 poll로 양쪽 EOF와 자식 회수 결과를 전달함. |
| 368 | pub trait Connection { |
| 369 | fn send(&mut self, request: Request) -> Result<(), String>; |
| 370 | fn poll(&mut self) -> Option<HostEvent>; |
| 371 | } |
| 372 | pub trait Factory { |
| 373 | fn connect(&mut self, job_id: u64) -> Result<Box<dyn Connection>, String>; |
| 374 | } |
| 375 | pub struct Unavailable; |
| 376 | impl Factory for Unavailable { |
| 377 | fn connect(&mut self, _: u64) -> Result<Box<dyn Connection>, String> { |
| 378 | Err("작업자 연결이 아직 준비되지 않았습니다".into()) |
| 379 | } |
| 380 | } |
| 381 | struct Running { |
| 382 | recovery_metadata: usize, |
| 383 | volume_problem: Option<VolumeProblem>, |
| 384 | preview: Option<PreviewBuffer>, |
| 385 | preview_discarded: bool, |
| 386 | id: u64, |
| 387 | outgoing: u64, |
| 388 | incoming: u64, |
| 389 | accepted: bool, |
| 390 | start_failed: bool, |
| 391 | start: Start, |
| 392 | connection: Box<dyn Connection>, |
| 393 | entries: Vec<Entry>, |
| 394 | list_end: Option<(u32, ListId)>, |
| 395 | stdout_eof: bool, |
| 396 | transport_closed: bool, |
| 397 | stderr_eof: bool, |
| 398 | exit: Option<bool>, |
| 399 | cancel_sequence: Option<u64>, |
| 400 | expanded: bool, |
| 401 | granted: ResourceScope, |
| 402 | last_challenge: u64, |
| 403 | estimated: ResourceUsage, |
| 404 | conflict_ids: BTreeSet<u64>, |
| 405 | resolved_ids: BTreeSet<u32>, |
| 406 | file_ids: BTreeSet<u32>, |
| 407 | } |
| 408 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
| 409 | pub enum Close { |
| 410 | #[default] |
| 411 | Open, |
| 412 | Confirm, |
| 413 | Waiting, |
| 414 | Review, |
| 415 | Allowed, |
| 416 | } |
| 417 | #[derive(Default)] |
| 418 | pub struct Model { |
| 419 | pub recovery_entries: Vec<RecoveryEntry>, |
| 420 | pub recovery_end: Option<RecoveryEnd>, |
| 421 | pub volume_problem: Option<VolumeProblem>, |
| 422 | running: Option<Running>, |
| 423 | pub preview: Option<Preview>, |
| 424 | next_id: u64, |
| 425 | pub archive: Option<PathBuf>, |
| 426 | pub entries: Vec<Entry>, |
| 427 | pub list_id: Option<ListId>, |
| 428 | pub selected: BTreeSet<u32>, |
| 429 | pub terminal: Option<Terminal>, |
| 430 | pub challenge: Option<(u64, u32, bool)>, |
| 431 | pub resource: Option<ResourceChallenge>, |
| 432 | retry_start: Option<Start>, |
| 433 | pub conflict: Option<Conflict>, |
| 434 | pub resolutions: Vec<Resolution>, |
| 435 | pub progress: Option<(Stage, u64, Option<u64>, u64)>, |
| 436 | pub outputs: Vec<(String, Disposition)>, |
| 437 | pub cancel: Option<CancelStatus>, |
| 438 | pub error: Option<String>, |
| 439 | pub input_error: Option<String>, |
| 440 | pub encryption: bool, |
| 441 | pub close: Close, |
| 442 | pub confirmed: bool, |
| 443 | } |
| 444 | impl Model { |
| 445 | pub fn busy(&self) -> bool { |
| 446 | self.running.is_some() |
| 447 | } |
| 448 | pub fn cancellation_requested(&self) -> bool { |
| 449 | self.running |
| 450 | .as_ref() |
| 451 | .is_some_and(|run| run.cancel_sequence.is_some()) |
| 452 | } |
| 453 | pub fn job_id(&self) -> Option<u64> { |
| 454 | self.running.as_ref().map(|r| r.id) |
| 455 | } |
| 456 | pub fn can_extract(&self) -> bool { |
| 457 | !self.busy() |
| 458 | && self.list_id.is_some() |
| 459 | && self.archive.is_some() |
| 460 | && self.close == Close::Open |
| 461 | } |
| 462 | pub fn can_preview(&self) -> bool { |
| 463 | self.can_extract() |
| 464 | && self.list_id.as_ref().is_some_and(|id| !id.is_split()) |
| 465 | && self.selected.len() == 1 |
| 466 | && self |
| 467 | .entries |
| 468 | .iter() |
| 469 | .any(|e| self.selected.contains(&e.id) && e.kind == Kind::File) |
| 470 | } |
| 471 | pub fn begin_preview(&mut self, factory: &mut dyn Factory) -> bool { |
| 472 | if !self.can_preview() { |
| 473 | return false; |
| 474 | } |
| 475 | self.begin( |
| 476 | Start::Preview { |
| 477 | archive: self.archive.clone().unwrap(), |
| 478 | entry_id: *self.selected.first().unwrap(), |
| 479 | list_id: self.list_id.clone().unwrap(), |
| 480 | }, |
| 481 | factory, |
| 482 | ) |
| 483 | } |
| 484 | pub fn dismiss_preview(&mut self) { |
| 485 | self.preview = None; |
| 486 | if let Some(run) = self.running.as_mut() |
| 487 | && matches!(run.start, Start::Preview { .. }) |
| 488 | { |
| 489 | run.preview = None; |
| 490 | run.preview_discarded = true; |
| 491 | self.cancel(); |
| 492 | } |
| 493 | } |
| 494 | pub fn begin(&mut self, start: Start, factory: &mut dyn Factory) -> bool { |
| 495 | let expanded = |
| 496 | matches!(start, Start::CreateSevenZip { .. }) || self.needs_expansion(&start); |
| 497 | self.begin_with_limits(start, factory, expanded) |
| 498 | } |
| 499 | pub fn estimated_usage(&self) -> ResourceUsage { |
| 500 | self.running |
| 501 | .as_ref() |
| 502 | .map(|run| run.estimated) |
| 503 | .unwrap_or_default() |
| 504 | } |
| 505 | fn estimate(&self, start: &Start) -> ResourceUsage { |
| 506 | let mut usage = ResourceUsage::default(); |
| 507 | match start { |
| 508 | Start::Extract { selection, .. } => { |
| 509 | let selected_ids: BTreeSet<_> = match selection { |
| 510 | Selection::All => BTreeSet::new(), |
| 511 | Selection::EntryIds(ids) => ids.iter().copied().collect(), |
| 512 | }; |
| 513 | let directories: BTreeSet<_> = self |
| 514 | .entries |
| 515 | .iter() |
| 516 | .filter(|e| selected_ids.contains(&e.id) && e.kind == Kind::Directory) |
| 517 | .map(|e| e.name.trim_end_matches('/')) |
| 518 | .collect(); |
| 519 | let selected = |entry: &&Entry| { |
| 520 | matches!(selection, Selection::All) |
| 521 | || selected_ids.contains(&entry.id) |
| 522 | || entry |
| 523 | .name |
| 524 | .match_indices('/') |
| 525 | .any(|(n, _)| directories.contains(&entry.name[..n])) |
| 526 | }; |
| 527 | let entries: Vec<_> = self.entries.iter().filter(selected).collect(); |
| 528 | usage.estimated_entries = u32::try_from(entries.len()).ok(); |
| 529 | usage.estimated_bytes = entries |
| 530 | .iter() |
| 531 | .try_fold(0u64, |sum, e| sum.checked_add(e.bytes?)); |
| 532 | } |
| 533 | Start::CreateZip { sources, .. } | Start::CreateSevenZip { sources, .. } => { |
| 534 | usage.estimated_bytes = sources.iter().try_fold(0u64, |sum, (path, _)| { |
| 535 | let m = std::fs::symlink_metadata(path).ok()?; |
| 536 | if !m.is_file() { |
| 537 | return None; |
| 538 | } |
| 539 | sum.checked_add(m.len()) |
| 540 | }); |
| 541 | usage.estimated_entries = sources |
| 542 | .iter() |
| 543 | .all(|(path, _)| std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file())) |
| 544 | .then(|| u32::try_from(sources.len()).ok()) |
| 545 | .flatten(); |
| 546 | } |
| 547 | Start::Preview { .. } => { |
| 548 | usage.estimated_entries = u32::try_from(self.entries.len()).ok(); |
| 549 | usage.estimated_bytes = self |
| 550 | .entries |
| 551 | .iter() |
| 552 | .try_fold(0u64, |sum, e| sum.checked_add(e.bytes?)); |
| 553 | } |
| 554 | Start::List { .. } | Start::RecoverZip { .. } => {} |
| 555 | } |
| 556 | usage |
| 557 | } |
| 558 | fn needs_expansion(&self, start: &Start) -> bool { |
| 559 | let usage = self.estimate(start); |
| 560 | usage |
| 561 | .estimated_bytes |
| 562 | .is_some_and(|n| n > Limits::default().output) |
| 563 | || usage |
| 564 | .estimated_entries |
| 565 | .is_some_and(|n| n > Limits::default().entries) |
| 566 | } |
| 567 | pub fn can_retry_expanded(&self) -> bool { |
| 568 | !self.busy() && self.retry_start.is_some() && self.close == Close::Open |
| 569 | } |
| 570 | pub fn retry_expanded(&mut self, factory: &mut dyn Factory) -> bool { |
| 571 | if !self.can_retry_expanded() { |
| 572 | return false; |
| 573 | } |
| 574 | let start = self.retry_start.clone().unwrap(); |
| 575 | self.begin_with_limits(start, factory, true) |
| 576 | } |
| 577 | pub fn resource_reply(&mut self, job_id: u64, challenge_id: u64, allow: bool) -> bool { |
| 578 | if self.job_id() != Some(job_id) || self.cancellation_requested() { |
| 579 | return false; |
| 580 | } |
| 581 | let Some(question) = self.resource.clone().filter(|q| q.id == challenge_id) else { |
| 582 | return false; |
| 583 | }; |
| 584 | if self |
| 585 | .send(Command::ResourceReply { |
| 586 | challenge_id, |
| 587 | scope: question.scope, |
| 588 | allow, |
| 589 | }) |
| 590 | .is_none() |
| 591 | { |
| 592 | return false; |
| 593 | } |
| 594 | if allow { |
| 595 | let granted = &mut self.running.as_mut().unwrap().granted; |
| 596 | granted.output |= question.scope.output; |
| 597 | granted.entries |= question.scope.entries; |
| 598 | granted.ratio |= question.scope.ratio; |
| 599 | } |
| 600 | self.resource = None; |
| 601 | true |
| 602 | } |
| 603 | fn begin_with_limits( |
| 604 | &mut self, |
| 605 | start: Start, |
| 606 | factory: &mut dyn Factory, |
| 607 | expanded: bool, |
| 608 | ) -> bool { |
| 609 | if self.busy() || self.close != Close::Open { |
| 610 | return false; |
| 611 | } |
| 612 | let selectable: BTreeSet<_> = self |
| 613 | .entries |
| 614 | .iter() |
| 615 | .filter(|e| matches!(e.kind, Kind::File | Kind::Directory)) |
| 616 | .map(|e| e.id) |
| 617 | .collect(); |
| 618 | let validation = match &start { |
| 619 | Start::RecoverZip { |
| 620 | archive, |
| 621 | output_file, |
| 622 | } => archive.is_absolute() && output_file.is_absolute() && archive != output_file, |
| 623 | Start::List { archive } => archive.is_absolute(), |
| 624 | Start::Preview { |
| 625 | archive, |
| 626 | entry_id, |
| 627 | list_id, |
| 628 | } => { |
| 629 | archive.is_absolute() |
| 630 | && list_id.valid() |
| 631 | && !list_id.is_split() |
| 632 | && self.archive.as_ref() == Some(archive) |
| 633 | && self.list_id.as_ref() == Some(list_id) |
| 634 | && self |
| 635 | .entries |
| 636 | .iter() |
| 637 | .any(|e| e.id == *entry_id && e.kind == Kind::File) |
| 638 | } |
| 639 | Start::Extract { |
| 640 | archive, |
| 641 | destination, |
| 642 | selection, |
| 643 | gzip_output_name, |
| 644 | list_id, |
| 645 | } => { |
| 646 | archive.is_absolute() |
| 647 | && destination.is_absolute() |
| 648 | && self.archive.as_ref() == Some(archive) |
| 649 | && self.list_id.as_ref() == Some(list_id) |
| 650 | && match list_id.format { |
| 651 | Format::Gzip => gzip_output_name.as_ref().is_some_and(|s| valid_leaf(s)), |
| 652 | _ => gzip_output_name.is_none(), |
| 653 | } |
| 654 | && match selection { |
| 655 | Selection::All => true, |
| 656 | Selection::EntryIds(ids) => { |
| 657 | !ids.is_empty() |
| 658 | && ids.iter().collect::<BTreeSet<_>>().len() == ids.len() |
| 659 | && ids.iter().all(|id| selectable.contains(id)) |
| 660 | } |
| 661 | } |
| 662 | } |
| 663 | Start::CreateZip { |
| 664 | sources, |
| 665 | output_file, |
| 666 | .. |
| 667 | } |
| 668 | | Start::CreateSevenZip { |
| 669 | sources, |
| 670 | output_file, |
| 671 | } => { |
| 672 | !sources.is_empty() |
| 673 | && output_file.is_absolute() |
| 674 | && sources |
| 675 | .iter() |
| 676 | .all(|(p, n)| p.is_absolute() && valid_relative(n)) |
| 677 | } |
| 678 | }; |
| 679 | if !validation { |
| 680 | self.input_error = Some("입력 경로, 출력명과 선택한 목록을 확인하세요".into()); |
| 681 | return false; |
| 682 | } |
| 683 | let Some(id) = self.next_id.checked_add(1) else { |
| 684 | self.error = Some("작업 ID 한도에 도달했습니다".into()); |
| 685 | return false; |
| 686 | }; |
| 687 | self.preview = None; |
| 688 | let estimated = self.estimate(&start); |
| 689 | self.volume_problem = None; |
| 690 | let mut connection = match factory.connect(id) { |
| 691 | Ok(c) => c, |
| 692 | Err(e) => { |
| 693 | self.error = Some(e); |
| 694 | return false; |
| 695 | } |
| 696 | }; |
| 697 | let send_error = connection |
| 698 | .send(Request { |
| 699 | job_id: id, |
| 700 | sequence: 0, |
| 701 | command: if expanded { |
| 702 | Command::StartExpanded(start.clone()) |
| 703 | } else { |
| 704 | Command::Start(start.clone()) |
| 705 | }, |
| 706 | }) |
| 707 | .err(); |
| 708 | let started = send_error.is_none(); |
| 709 | if let Start::List { archive } = &start |
| 710 | && started |
| 711 | { |
| 712 | self.archive = Some(archive.clone()); |
| 713 | self.list_id = None; |
| 714 | self.entries.clear(); |
| 715 | self.selected.clear(); |
| 716 | } |
| 717 | self.next_id = id; |
| 718 | self.recovery_entries.clear(); |
| 719 | self.recovery_end = None; |
| 720 | self.terminal = None; |
| 721 | self.volume_problem = None; |
| 722 | self.retry_start = None; |
| 723 | self.resource = None; |
| 724 | self.challenge = None; |
| 725 | self.conflict = None; |
| 726 | self.resolutions.clear(); |
| 727 | self.progress = None; |
| 728 | self.outputs.clear(); |
| 729 | self.cancel = None; |
| 730 | self.input_error = None; |
| 731 | self.error = send_error; |
| 732 | self.confirmed = false; |
| 733 | self.running = Some(Running { |
| 734 | recovery_metadata: 0, |
| 735 | volume_problem: None, |
| 736 | preview: None, |
| 737 | preview_discarded: false, |
| 738 | id, |
| 739 | outgoing: 1, |
| 740 | incoming: 0, |
| 741 | accepted: false, |
| 742 | start_failed: !started, |
| 743 | start, |
| 744 | connection, |
| 745 | entries: Vec::new(), |
| 746 | list_end: None, |
| 747 | stdout_eof: false, |
| 748 | transport_closed: false, |
| 749 | stderr_eof: false, |
| 750 | exit: None, |
| 751 | cancel_sequence: None, |
| 752 | expanded, |
| 753 | granted: ResourceScope::default(), |
| 754 | last_challenge: 0, |
| 755 | estimated, |
| 756 | conflict_ids: BTreeSet::new(), |
| 757 | resolved_ids: BTreeSet::new(), |
| 758 | file_ids: self |
| 759 | .entries |
| 760 | .iter() |
| 761 | .filter(|e| e.kind == Kind::File) |
| 762 | .map(|e| e.id) |
| 763 | .collect(), |
| 764 | }); |
| 765 | started |
| 766 | } |
| 767 | pub fn extract( |
| 768 | &mut self, |
| 769 | destination: PathBuf, |
| 770 | selected_only: bool, |
| 771 | gzip_output_name: Option<String>, |
| 772 | factory: &mut dyn Factory, |
| 773 | ) -> bool { |
| 774 | if !self.can_extract() { |
| 775 | return false; |
| 776 | } |
| 777 | self.begin( |
| 778 | Start::Extract { |
| 779 | archive: self.archive.clone().unwrap(), |
| 780 | destination, |
| 781 | selection: if selected_only { |
| 782 | Selection::EntryIds(self.selected.iter().copied().collect()) |
| 783 | } else { |
| 784 | Selection::All |
| 785 | }, |
| 786 | list_id: self.list_id.clone().unwrap(), |
| 787 | gzip_output_name, |
| 788 | }, |
| 789 | factory, |
| 790 | ) |
| 791 | } |
| 792 | pub fn password(&mut self, text: String) -> bool { |
| 793 | let Some((challenge_id, _, _)) = self.challenge else { |
| 794 | return false; |
| 795 | }; |
| 796 | let secret = match Secret::new(text) { |
| 797 | Ok(s) => s, |
| 798 | Err(e) => { |
| 799 | self.input_error = Some(e.into()); |
| 800 | return false; |
| 801 | } |
| 802 | }; |
| 803 | if self |
| 804 | .send(Command::Password { |
| 805 | challenge_id, |
| 806 | secret, |
| 807 | }) |
| 808 | .is_some() |
| 809 | { |
| 810 | self.challenge = None; |
| 811 | self.resource = None; |
| 812 | self.conflict = None; |
| 813 | self.input_error = None; |
| 814 | true |
| 815 | } else { |
| 816 | false |
| 817 | } |
| 818 | } |
| 819 | pub fn resolve_conflict(&mut self, choice: ConflictChoice, apply_to_remaining: bool) -> bool { |
| 820 | let Some(conflict) = &self.conflict else { |
| 821 | return false; |
| 822 | }; |
| 823 | if self.cancellation_requested() || self.error.is_some() || self.close != Close::Open { |
| 824 | return false; |
| 825 | } |
| 826 | if self |
| 827 | .send(Command::ConflictReply { |
| 828 | challenge_id: conflict.challenge_id, |
| 829 | choice, |
| 830 | apply_to_remaining, |
| 831 | }) |
| 832 | .is_some() |
| 833 | { |
| 834 | self.conflict = None; |
| 835 | self.input_error = None; |
| 836 | true |
| 837 | } else { |
| 838 | false |
| 839 | } |
| 840 | } |
| 841 | fn send(&mut self, command: Command) -> Option<u64> { |
| 842 | let run = self.running.as_mut()?; |
| 843 | if run.start_failed || self.terminal.is_some() || run.exit.is_some() { |
| 844 | return None; |
| 845 | } |
| 846 | let seq = run.outgoing; |
| 847 | let Some(next) = seq.checked_add(1) else { |
| 848 | self.error = Some("요청 순서 한도 초과".into()); |
| 849 | return None; |
| 850 | }; |
| 851 | match run.connection.send(Request { |
| 852 | job_id: run.id, |
| 853 | sequence: seq, |
| 854 | command, |
| 855 | }) { |
| 856 | Ok(()) => { |
| 857 | run.outgoing = next; |
| 858 | Some(seq) |
| 859 | } |
| 860 | Err(e) => { |
| 861 | self.error = Some(e); |
| 862 | None |
| 863 | } |
| 864 | } |
| 865 | } |
| 866 | pub fn cancel(&mut self) { |
| 867 | self.preview = None; |
| 868 | if let Some(run) = self.running.as_mut() |
| 869 | && matches!(run.start, Start::Preview { .. }) |
| 870 | { |
| 871 | run.preview = None; |
| 872 | run.preview_discarded = true; |
| 873 | } |
| 874 | if self |
| 875 | .running |
| 876 | .as_ref() |
| 877 | .is_some_and(|r| r.cancel_sequence.is_none()) |
| 878 | { |
| 879 | if let Some(seq) = self.send(Command::Cancel) { |
| 880 | self.running.as_mut().unwrap().cancel_sequence = Some(seq); |
| 881 | self.challenge = None; |
| 882 | self.resource = None; |
| 883 | self.conflict = None; |
| 884 | self.input_error = None; |
| 885 | } |
| 886 | } |
| 887 | } |
| 888 | pub fn request_close(&mut self) { |
| 889 | if self.close == Close::Open { |
| 890 | self.close = if self.busy() { |
| 891 | Close::Confirm |
| 892 | } else { |
| 893 | Close::Review |
| 894 | }; |
| 895 | } |
| 896 | } |
| 897 | pub fn confirm_close(&mut self) { |
| 898 | if self.close == Close::Confirm { |
| 899 | self.cancel(); |
| 900 | self.close = if self.busy() { |
| 901 | Close::Waiting |
| 902 | } else { |
| 903 | Close::Review |
| 904 | }; |
| 905 | } |
| 906 | } |
| 907 | pub fn keep_open(&mut self) { |
| 908 | if self.close != Close::Allowed { |
| 909 | self.close = Close::Open; |
| 910 | } |
| 911 | } |
| 912 | pub fn acknowledge_close(&mut self) { |
| 913 | if !self.busy() && self.close == Close::Review { |
| 914 | self.close = Close::Allowed; |
| 915 | } |
| 916 | } |
| 917 | pub fn poll(&mut self) { |
| 918 | let changed = self.running.as_ref().is_some_and(|run| { |
| 919 | matches!(&run.start, Start::Preview { entry_id, .. } |
| 920 | if self.selected.len() != 1 || !self.selected.contains(entry_id)) |
| 921 | }); |
| 922 | if changed { |
| 923 | self.dismiss_preview(); |
| 924 | } |
| 925 | for _ in 0..128 { |
| 926 | let Some(event) = self.running.as_mut().and_then(|r| r.connection.poll()) else { |
| 927 | break; |
| 928 | }; |
| 929 | self.receive(event); |
| 930 | if self.error.is_some() |
| 931 | && self |
| 932 | .running |
| 933 | .as_ref() |
| 934 | .is_some_and(|run| matches!(run.start, Start::Preview { .. })) |
| 935 | { |
| 936 | self.cancel(); |
| 937 | } |
| 938 | } |
| 939 | let complete = self.running.as_ref().is_some_and(|r| { |
| 940 | r.exit.is_some() |
| 941 | && ((r.stdout_eof && r.stderr_eof) || (r.transport_closed && self.error.is_some())) |
| 942 | }); |
| 943 | if complete { |
| 944 | let mut run = self.running.take().unwrap(); |
| 945 | self.confirmed = |
| 946 | self.terminal.is_some() && run.exit == Some(true) && self.error.is_none(); |
| 947 | if !self.confirmed { |
| 948 | self.error.get_or_insert( |
| 949 | "작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요".into(), |
| 950 | ); |
| 951 | } |
| 952 | if self.confirmed |
| 953 | && self |
| 954 | .terminal |
| 955 | .as_ref() |
| 956 | .is_some_and(|t| t.outcome == Outcome::Completed) |
| 957 | { |
| 958 | if matches!(run.start, Start::List { .. }) { |
| 959 | if let Some((count, id)) = run |
| 960 | .list_end |
| 961 | .filter(|(n, _)| *n as usize == run.entries.len()) |
| 962 | { |
| 963 | let _ = count; |
| 964 | self.entries = run.entries; |
| 965 | self.list_id = Some(id); |
| 966 | } else { |
| 967 | self.error = Some("목록 완료 정보가 일치하지 않습니다. 다시 여세요".into()); |
| 968 | self.confirmed = false; |
| 969 | } |
| 970 | } |
| 971 | } |
| 972 | if matches!(run.start, Start::Preview { .. }) { |
| 973 | if self.confirmed |
| 974 | && self |
| 975 | .terminal |
| 976 | .as_ref() |
| 977 | .is_some_and(|t| t.outcome == Outcome::Completed) |
| 978 | && !run.preview_discarded |
| 979 | { |
| 980 | if let Some(buffer) = run.preview.take().filter(|b| b.ended) { |
| 981 | self.preview = Some(Preview { |
| 982 | info: buffer.info, |
| 983 | data: buffer.data, |
| 984 | }); |
| 985 | } else { |
| 986 | self.error = Some("미리보기 완료 정보가 일치하지 않습니다".into()); |
| 987 | self.confirmed = false; |
| 988 | } |
| 989 | } |
| 990 | } |
| 991 | if self.terminal.as_ref().is_some_and(|t| { |
| 992 | matches!( |
| 993 | t.error, |
| 994 | Some(ErrorCode::SourceChanged | ErrorCode::MissingVolume) |
| 995 | ) |
| 996 | }) { |
| 997 | self.list_id = None; |
| 998 | self.selected.clear(); |
| 999 | } |
| 1000 | if self.confirmed && run.cancel_sequence.is_none() { |
| 1001 | self.volume_problem = run.volume_problem.take(); |
| 1002 | } |
| 1003 | self.retry_start = if !matches!(run.start, Start::Preview { .. }) |
| 1004 | && !run.expanded |
| 1005 | && run.cancel_sequence.is_none() |
| 1006 | && self.confirmed |
| 1007 | && self.terminal.as_ref().is_some_and(|t| { |
| 1008 | t.outcome == Outcome::Failed |
| 1009 | && t.error == Some(ErrorCode::Limit) |
| 1010 | && t.publication == Publication::None |
| 1011 | && t.created_count == 0 |
| 1012 | && t.retained_partial_count == 0 |
| 1013 | && t.cleanup == Cleanup::Complete |
| 1014 | }) |
| 1015 | && self.outputs.iter().all(|(_, d)| *d == Disposition::Removed) |
| 1016 | { |
| 1017 | Some(run.start.clone()) |
| 1018 | } else { |
| 1019 | None |
| 1020 | }; |
| 1021 | self.challenge = None; |
| 1022 | self.resource = None; |
| 1023 | self.conflict = None; |
| 1024 | self.input_error = None; |
| 1025 | if matches!(self.close, Close::Waiting | Close::Confirm) { |
| 1026 | self.close = Close::Review; |
| 1027 | } |
| 1028 | } |
| 1029 | } |
| 1030 | fn receive(&mut self, host: HostEvent) { |
| 1031 | let run = self.running.as_mut().unwrap(); |
| 1032 | match host { |
| 1033 | HostEvent::Fault(message) => self.error = Some(message), |
| 1034 | HostEvent::CleanupComplete => run.transport_closed = true, |
| 1035 | HostEvent::StdoutEof => run.stdout_eof = true, |
| 1036 | HostEvent::StderrEof => run.stderr_eof = true, |
| 1037 | HostEvent::Exited { success } => run.exit = Some(success), |
| 1038 | HostEvent::Frame { |
| 1039 | job_id, |
| 1040 | sequence, |
| 1041 | event, |
| 1042 | } => { |
| 1043 | if job_id != run.id |
| 1044 | || sequence != run.incoming |
| 1045 | || self.terminal.is_some() |
| 1046 | || run.stdout_eof |
| 1047 | || sequence >= 1_000_000 |
| 1048 | { |
| 1049 | self.error = Some("작업자 응답 순서나 작업 ID가 일치하지 않습니다".into()); |
| 1050 | return; |
| 1051 | } |
| 1052 | run.incoming += 1; |
| 1053 | if !run.accepted && !matches!(event, Event::Accepted { .. }) { |
| 1054 | self.error = Some("작업 승인 응답이 없습니다".into()); |
| 1055 | return; |
| 1056 | } |
| 1057 | match event { |
| 1058 | Event::RecoveryEntry(entry) => { |
| 1059 | let budget = if run.granted.any() { |
| 1060 | 64 * 1024 * 1024 |
| 1061 | } else { |
| 1062 | 8 * 1024 * 1024 |
| 1063 | }; |
| 1064 | let used = run.recovery_metadata; |
| 1065 | if !matches!(run.start, Start::RecoverZip { .. }) |
| 1066 | || self.recovery_end.is_some() |
| 1067 | || !entry.valid() |
| 1068 | || entry.candidate_id as usize != self.recovery_entries.len() |
| 1069 | || entry.name.as_ref().is_some_and(|n| { |
| 1070 | n.len() > 4096 || !valid_relative(n.trim_end_matches('/')) |
| 1071 | }) |
| 1072 | || self |
| 1073 | .recovery_entries |
| 1074 | .last() |
| 1075 | .is_some_and(|e| e.source_offset >= entry.source_offset) |
| 1076 | || self.recovery_entries.len() |
| 1077 | >= if run.granted.entries { 200_000 } else { 10_000 } |
| 1078 | || used + 128 + entry.name.as_ref().map_or(0, String::len) > budget |
| 1079 | { |
| 1080 | self.error = Some("복구 항목 응답이 유효하지 않습니다".into()); |
| 1081 | } else { |
| 1082 | run.recovery_metadata += |
| 1083 | 128 + entry.name.as_ref().map_or(0, String::len); |
| 1084 | self.recovery_entries.push(entry); |
| 1085 | } |
| 1086 | } |
| 1087 | Event::RecoveryEnd(summary) => { |
| 1088 | let count = |status| { |
| 1089 | self.recovery_entries |
| 1090 | .iter() |
| 1091 | .filter(|e| e.status == status) |
| 1092 | .count() as u32 |
| 1093 | }; |
| 1094 | if !matches!(run.start, Start::RecoverZip { .. }) |
| 1095 | || self.recovery_end.is_some() |
| 1096 | || !summary.valid() |
| 1097 | || summary.source_bytes > 4 * 1024 * 1024 * 1024 |
| 1098 | || self |
| 1099 | .recovery_entries |
| 1100 | .iter() |
| 1101 | .any(|e| e.source_offset >= summary.source_bytes) |
| 1102 | || summary.verified_entries != count(RecoveryStatus::Verified) |
| 1103 | || summary.lost_entries != count(RecoveryStatus::Lost) |
| 1104 | || summary.unverified_entries != count(RecoveryStatus::Unverified) |
| 1105 | { |
| 1106 | self.error = Some("복구 요약이 항목과 일치하지 않습니다".into()); |
| 1107 | } else { |
| 1108 | self.recovery_end = Some(summary); |
| 1109 | } |
| 1110 | } |
| 1111 | Event::VolumeProblem(problem) => { |
| 1112 | if run.cancel_sequence.is_some() { |
| 1113 | return; |
| 1114 | } |
| 1115 | if run.volume_problem.is_some() |
| 1116 | || !matches!(run.start, Start::List { .. } | Start::Extract { .. }) |
| 1117 | || !problem.volume.is_basename() |
| 1118 | { |
| 1119 | self.error = Some("분할 조각 오류 응답이 유효하지 않습니다".into()); |
| 1120 | } else { |
| 1121 | run.volume_problem = Some(problem); |
| 1122 | } |
| 1123 | } |
| 1124 | Event::PreviewBegin(info) => { |
| 1125 | if run.preview_discarded { |
| 1126 | return; |
| 1127 | } |
| 1128 | if !matches!(run.start, Start::Preview { entry_id, .. } if entry_id == info.entry_id) |
| 1129 | || run.preview.is_some() |
| 1130 | || !info.valid() |
| 1131 | || self.error.is_some() |
| 1132 | { |
| 1133 | self.error = Some("미리보기 메타정보가 유효하지 않습니다".into()); |
| 1134 | } else { |
| 1135 | let mut data = Vec::new(); |
| 1136 | if data.try_reserve_exact(info.total_bytes as usize).is_err() { |
| 1137 | self.error = Some("미리보기 메모리를 확보하지 못했습니다".into()); |
| 1138 | } else { |
| 1139 | run.preview = Some(PreviewBuffer { |
| 1140 | info, |
| 1141 | data, |
| 1142 | ended: false, |
| 1143 | }); |
| 1144 | } |
| 1145 | } |
| 1146 | } |
| 1147 | Event::PreviewChunk { |
| 1148 | entry_id, |
| 1149 | offset, |
| 1150 | data, |
| 1151 | } => { |
| 1152 | if run.preview_discarded { |
| 1153 | return; |
| 1154 | } |
| 1155 | if self.error.is_some() |
| 1156 | || !run |
| 1157 | .preview |
| 1158 | .as_mut() |
| 1159 | .is_some_and(|b| b.chunk(entry_id, offset, data)) |
| 1160 | { |
| 1161 | run.preview = None; |
| 1162 | self.error = |
| 1163 | Some("미리보기 데이터 순서나 크기가 일치하지 않습니다".into()); |
| 1164 | } |
| 1165 | } |
| 1166 | Event::PreviewEnd { |
| 1167 | entry_id, |
| 1168 | total_bytes, |
| 1169 | sha256, |
| 1170 | } => { |
| 1171 | if run.preview_discarded { |
| 1172 | return; |
| 1173 | } |
| 1174 | if !run |
| 1175 | .preview |
| 1176 | .as_mut() |
| 1177 | .is_some_and(|b| b.end(entry_id, total_bytes, sha256)) |
| 1178 | { |
| 1179 | run.preview = None; |
| 1180 | self.error = Some("미리보기 내용 검증에 실패했습니다".into()); |
| 1181 | } |
| 1182 | } |
| 1183 | Event::Accepted { encryption } => { |
| 1184 | if matches!( |
| 1185 | run.start, |
| 1186 | Start::CreateSevenZip { .. } | Start::RecoverZip { .. } |
| 1187 | ) && encryption |
| 1188 | { |
| 1189 | self.error = Some("7z 생성의 암호 응답이 유효하지 않습니다".into()); |
| 1190 | } |
| 1191 | if run.accepted { |
| 1192 | self.error = Some("작업 승인 중복".into()); |
| 1193 | } |
| 1194 | run.accepted = true; |
| 1195 | self.encryption = encryption; |
| 1196 | } |
| 1197 | Event::Entry(entry) => { |
| 1198 | if !matches!(run.start, Start::List { .. }) |
| 1199 | || run.list_end.is_some() |
| 1200 | || entry.id as usize != run.entries.len() |
| 1201 | || entry.name.len() > 4096 |
| 1202 | || run.entries.len() |
| 1203 | >= if run.granted.entries { |
| 1204 | 200_000 |
| 1205 | } else { |
| 1206 | 100_000 |
| 1207 | } |
| 1208 | { |
| 1209 | self.error = Some("목록 응답이 유효하지 않습니다".into()); |
| 1210 | } else { |
| 1211 | run.entries.push(entry); |
| 1212 | } |
| 1213 | } |
| 1214 | Event::ListEnd { |
| 1215 | entry_count, |
| 1216 | list_id, |
| 1217 | } => { |
| 1218 | if !matches!(run.start, Start::List { .. }) |
| 1219 | || run.list_end.is_some() |
| 1220 | || !list_id.valid() |
| 1221 | { |
| 1222 | self.error = Some("목록 완료 응답이 유효하지 않습니다".into()); |
| 1223 | } else { |
| 1224 | run.list_end = Some((entry_count, list_id)); |
| 1225 | } |
| 1226 | } |
| 1227 | Event::PasswordRequired { |
| 1228 | challenge_id, |
| 1229 | attempt, |
| 1230 | encrypt, |
| 1231 | } => { |
| 1232 | if run.cancel_sequence.is_some() { |
| 1233 | return; |
| 1234 | } |
| 1235 | if matches!( |
| 1236 | run.start, |
| 1237 | Start::CreateSevenZip { .. } | Start::RecoverZip { .. } |
| 1238 | ) || self.challenge.is_some() |
| 1239 | || self.resource.is_some() |
| 1240 | || challenge_id <= run.last_challenge |
| 1241 | || self.conflict.is_some() |
| 1242 | { |
| 1243 | self.error = Some("암호 요청이 유효하지 않습니다".into()); |
| 1244 | } else { |
| 1245 | run.last_challenge = challenge_id; |
| 1246 | self.challenge = Some((challenge_id, attempt, encrypt)); |
| 1247 | } |
| 1248 | } |
| 1249 | Event::ResourceRequired(question) => { |
| 1250 | if run.cancel_sequence.is_some() { |
| 1251 | return; |
| 1252 | } |
| 1253 | let expected = match run.start { |
| 1254 | Start::List { .. } => ActionKind::List, |
| 1255 | Start::Extract { .. } => ActionKind::Extract, |
| 1256 | Start::CreateZip { .. } => ActionKind::CreateZip, |
| 1257 | Start::CreateSevenZip { .. } => ActionKind::CreateSevenZip, |
| 1258 | Start::Preview { .. } => ActionKind::Preview, |
| 1259 | Start::RecoverZip { .. } => ActionKind::RecoverZip, |
| 1260 | }; |
| 1261 | let hard = Limits { |
| 1262 | input: u64::MAX, |
| 1263 | output: 64 * 1024 * 1024 * 1024, |
| 1264 | entries: 200_000, |
| 1265 | }; |
| 1266 | let ceiling = if run.expanded { |
| 1267 | hard |
| 1268 | } else { |
| 1269 | Limits::default() |
| 1270 | }; |
| 1271 | if self.challenge.is_some() |
| 1272 | || self.resource.is_some() |
| 1273 | || self.conflict.is_some() |
| 1274 | || question.id <= run.last_challenge |
| 1275 | || question.action != expected |
| 1276 | || !question.scope.any() |
| 1277 | || question.soft_limits != Limits::default() |
| 1278 | || question.ceiling != ceiling |
| 1279 | || (question.scope.output && (!run.expanded || run.granted.output)) |
| 1280 | || (question.scope.entries && (!run.expanded || run.granted.entries)) |
| 1281 | || (question.scope.ratio && run.granted.ratio) |
| 1282 | { |
| 1283 | self.error = Some("자원 승인 요청이 유효하지 않습니다".into()); |
| 1284 | } else { |
| 1285 | run.last_challenge = question.id; |
| 1286 | self.resource = Some(question); |
| 1287 | } |
| 1288 | } |
| 1289 | Event::ConflictRequired(conflict) => { |
| 1290 | let valid_entry = self |
| 1291 | .entries |
| 1292 | .iter() |
| 1293 | .any(|entry| entry.id == conflict.entry_id && entry.kind == Kind::File); |
| 1294 | if !matches!(run.start, Start::Extract { .. }) |
| 1295 | || !valid_entry |
| 1296 | || self.resource.is_some() |
| 1297 | || conflict.challenge_id <= run.last_challenge |
| 1298 | || self.challenge.is_some() |
| 1299 | || self.conflict.is_some() |
| 1300 | || run.conflict_ids.len() |
| 1301 | >= if run.granted.entries { |
| 1302 | 200_000 |
| 1303 | } else { |
| 1304 | 100_000 |
| 1305 | } |
| 1306 | || !valid_relative(&conflict.relative_name) |
| 1307 | || conflict.relative_name.len() > 4096 |
| 1308 | || !run.conflict_ids.insert(conflict.challenge_id) |
| 1309 | { |
| 1310 | self.error = Some("파일 충돌 요청이 유효하지 않습니다".into()); |
| 1311 | } else if run.cancel_sequence.is_none() { |
| 1312 | run.last_challenge = conflict.challenge_id; |
| 1313 | self.conflict = Some(conflict); |
| 1314 | } |
| 1315 | } |
| 1316 | Event::ConflictResolved(resolution) => { |
| 1317 | if !matches!(run.start, Start::Extract { .. }) |
| 1318 | || !run.file_ids.contains(&resolution.entry_id) |
| 1319 | || self.resolutions.len() |
| 1320 | >= if run.granted.entries { |
| 1321 | 200_000 |
| 1322 | } else { |
| 1323 | 100_000 |
| 1324 | } |
| 1325 | || !valid_relative(&resolution.relative_name) |
| 1326 | || resolution.relative_name.len() > 4096 |
| 1327 | || !run.resolved_ids.insert(resolution.entry_id) |
| 1328 | { |
| 1329 | self.error = Some("파일 충돌 결과가 유효하지 않습니다".into()); |
| 1330 | } else { |
| 1331 | self.resolutions.push(resolution); |
| 1332 | } |
| 1333 | } |
| 1334 | Event::Progress { |
| 1335 | stage, |
| 1336 | processed, |
| 1337 | total, |
| 1338 | completed_entries, |
| 1339 | } => self.progress = Some((stage, processed, total, completed_entries)), |
| 1340 | Event::Output { |
| 1341 | relative_name, |
| 1342 | disposition, |
| 1343 | entry_id, |
| 1344 | } => { |
| 1345 | if let Start::RecoverZip { output_file, .. } = &run.start { |
| 1346 | let final_output = matches!( |
| 1347 | disposition, |
| 1348 | Disposition::Created | Disposition::CommitUncertain |
| 1349 | ); |
| 1350 | let valid_output = if final_output { |
| 1351 | output_file.file_name().and_then(|n| n.to_str()) |
| 1352 | == Some(relative_name.as_str()) |
| 1353 | && !self.outputs.iter().any(|(_, d)| { |
| 1354 | matches!( |
| 1355 | d, |
| 1356 | Disposition::Created | Disposition::CommitUncertain |
| 1357 | ) |
| 1358 | }) |
| 1359 | } else { |
| 1360 | valid_leaf(&relative_name) |
| 1361 | && (disposition != Disposition::PartialRetained |
| 1362 | || output_file.file_name().and_then(|n| n.to_str()) |
| 1363 | != Some(relative_name.as_str())) |
| 1364 | && !self.outputs.iter().any(|(name, d)| { |
| 1365 | name == &relative_name && *d == disposition |
| 1366 | }) |
| 1367 | }; |
| 1368 | if entry_id.is_some() || self.recovery_end.is_none() || !valid_output { |
| 1369 | self.error = Some("복구본 출력 응답이 유효하지 않습니다".into()); |
| 1370 | return; |
| 1371 | } |
| 1372 | } |
| 1373 | if matches!(run.start, Start::Preview { .. }) { |
| 1374 | self.error = Some("미리보기 중 파일 출력이 보고됐습니다".into()); |
| 1375 | return; |
| 1376 | } |
| 1377 | if self.outputs.len() |
| 1378 | < if run.granted.any() { |
| 1379 | // 암묵적 상위 폴더도 출력되므로 작업자 노드 예산과 맞춤 |
| 1380 | 262_144 |
| 1381 | } else { |
| 1382 | 100_000 |
| 1383 | } |
| 1384 | && relative_name.len() <= 4096 |
| 1385 | { |
| 1386 | self.outputs.push((relative_name, disposition)); |
| 1387 | } else { |
| 1388 | self.error = Some("출력 보고 한도 초과".into()); |
| 1389 | } |
| 1390 | } |
| 1391 | Event::CancelAck { |
| 1392 | request_sequence, |
| 1393 | status, |
| 1394 | } => { |
| 1395 | if run.cancel_sequence == Some(request_sequence) && self.cancel.is_none() { |
| 1396 | self.cancel = Some(status); |
| 1397 | } else { |
| 1398 | self.error = Some("취소 응답이 요청과 일치하지 않습니다".into()); |
| 1399 | } |
| 1400 | } |
| 1401 | Event::Terminal(t) => { |
| 1402 | if matches!(run.start, Start::RecoverZip { .. }) { |
| 1403 | let business = t.outcome == Outcome::Completed |
| 1404 | || matches!( |
| 1405 | t.error, |
| 1406 | Some( |
| 1407 | ErrorCode::RecoveryIncomplete |
| 1408 | | ErrorCode::RecoveryImpossible |
| 1409 | ) |
| 1410 | ); |
| 1411 | if business |
| 1412 | && !self.recovery_end.as_ref().is_some_and(|s| { |
| 1413 | if s.verified_entries == 0 { |
| 1414 | t.outcome == Outcome::Failed |
| 1415 | && t.error == Some(ErrorCode::RecoveryImpossible) |
| 1416 | && t.publication == Publication::None |
| 1417 | && t.created_count == 0 |
| 1418 | && self.outputs.is_empty() |
| 1419 | } else { |
| 1420 | t.publication == Publication::Complete |
| 1421 | && t.created_count == 1 |
| 1422 | && self.outputs.len() == 1 |
| 1423 | && self.outputs[0].1 == Disposition::Created |
| 1424 | && if s.complete() { |
| 1425 | t.outcome == Outcome::Completed && t.error.is_none() |
| 1426 | } else { |
| 1427 | t.outcome == Outcome::Failed |
| 1428 | && t.error |
| 1429 | == Some(ErrorCode::RecoveryIncomplete) |
| 1430 | } |
| 1431 | } |
| 1432 | }) |
| 1433 | { |
| 1434 | self.error = |
| 1435 | Some("복구 결과와 저장 상태가 일치하지 않습니다".into()); |
| 1436 | } |
| 1437 | } |
| 1438 | if run.cancel_sequence.is_none() |
| 1439 | && run.volume_problem.as_ref().is_some_and(|problem| { |
| 1440 | t.outcome != Outcome::Failed |
| 1441 | || t.error |
| 1442 | != match problem.reason { |
| 1443 | VolumeProblemReason::FirstVolumeRequired => { |
| 1444 | Some(ErrorCode::InvalidRequest) |
| 1445 | } |
| 1446 | VolumeProblemReason::MissingVolume => { |
| 1447 | Some(ErrorCode::MissingVolume) |
| 1448 | } |
| 1449 | VolumeProblemReason::IncompleteSet => { |
| 1450 | Some(ErrorCode::Integrity) |
| 1451 | } |
| 1452 | } |
| 1453 | }) |
| 1454 | { |
| 1455 | self.error = |
| 1456 | Some("분할 조각 오류와 종료 상태가 일치하지 않습니다".into()); |
| 1457 | } |
| 1458 | if matches!(run.start, Start::Preview { .. }) |
| 1459 | && (t.publication != Publication::None |
| 1460 | || t.created_count != 0 |
| 1461 | || t.retained_partial_count != 0 |
| 1462 | || t.durability != Durability::NotApplicable) |
| 1463 | { |
| 1464 | self.error = Some("미리보기 종료 상태가 유효하지 않습니다".into()); |
| 1465 | } |
| 1466 | if t.outcome != Outcome::Completed { |
| 1467 | run.preview = None; |
| 1468 | } |
| 1469 | self.challenge = None; |
| 1470 | self.conflict = None; |
| 1471 | self.terminal = Some(t); |
| 1472 | } |
| 1473 | } |
| 1474 | } |
| 1475 | } |
| 1476 | } |
| 1477 | pub fn status(&self) -> String { |
| 1478 | if let Some(error) = self.error.as_ref().or(self.input_error.as_ref()) { |
| 1479 | return error.clone(); |
| 1480 | } |
| 1481 | if self.busy() { |
| 1482 | if self.terminal.is_some() { |
| 1483 | return "작업 결과 수신 / 프로세스 종료 확인 중".into(); |
| 1484 | } |
| 1485 | if self.resource.is_some() { |
| 1486 | return "사용자 허용 대기".into(); |
| 1487 | } |
| 1488 | if self.conflict.is_some() { |
| 1489 | return "같은 이름의 파일을 처리할 방법을 선택하세요".into(); |
| 1490 | } |
| 1491 | if self.challenge.is_some() { |
| 1492 | return "암호를 입력하세요".into(); |
| 1493 | } |
| 1494 | if let Some(c) = self.cancel { |
| 1495 | return match c { |
| 1496 | CancelStatus::Requested | CancelStatus::AlreadyRequested => { |
| 1497 | "취소 요청 접수 / 최종 결과 대기" |
| 1498 | } |
| 1499 | CancelStatus::TooLate => "취소할 수 없는 단계 / 최종 결과 대기", |
| 1500 | CancelStatus::Finished => "처리 종료 응답 / 프로세스 종료 확인 중", |
| 1501 | } |
| 1502 | .into(); |
| 1503 | } |
| 1504 | if self |
| 1505 | .running |
| 1506 | .as_ref() |
| 1507 | .is_some_and(|r| r.cancel_sequence.is_some()) |
| 1508 | { |
| 1509 | return "취소 요청 전송 / 최종 결과 대기".into(); |
| 1510 | } |
| 1511 | return "작업 중".into(); |
| 1512 | } |
| 1513 | match self |
| 1514 | .terminal |
| 1515 | .as_ref() |
| 1516 | .filter(|_| self.confirmed) |
| 1517 | .map(|t| t.outcome) |
| 1518 | { |
| 1519 | Some(Outcome::Completed) => "작업 완료", |
| 1520 | Some(Outcome::Cancelled) => "작업 취소됨", |
| 1521 | Some(Outcome::Failed) => "작업 실패", |
| 1522 | None => "압축파일을 열거나 ZIP 파일을 만드세요", |
| 1523 | } |
| 1524 | .into() |
| 1525 | } |
| 1526 | } |
| 1527 | pub fn valid_leaf(name: &str) -> bool { |
| 1528 | valid_relative(name) && !name.contains('/') && !name.contains('\\') |
| 1529 | } |
| 1530 | pub fn valid_relative(name: &str) -> bool { |
| 1531 | !name.is_empty() |
| 1532 | && !name.contains('\0') |
| 1533 | && !name.contains(':') |
| 1534 | && !name.starts_with('/') |
| 1535 | && !name.starts_with('\\') |
| 1536 | && name |
| 1537 | .split(['/', '\\']) |
| 1538 | .all(|p| !p.is_empty() && p != "." && p != "..") |
| 1539 | } |
| 1540 | |
| 1541 | // 파일 연결로 전달된 원형 경로를 손실 변환 없이 보존함. |
| 1542 | pub fn launch_args( |
| 1543 | args: Vec<std::ffi::OsString>, |
| 1544 | cwd: PathBuf, |
| 1545 | ) -> Result<(bool, Option<PathBuf>), &'static str> { |
| 1546 | let fixture = args.iter().any(|arg| arg == "--ui-fixture"); |
| 1547 | let paths = args |
| 1548 | .into_iter() |
| 1549 | .filter(|arg| arg != "--ui-fixture") |
| 1550 | .collect::<Vec<_>>(); |
| 1551 | if paths.len() > 1 { |
| 1552 | return Err("압축파일 하나를 지정하세요"); |
| 1553 | } |
| 1554 | let path = paths |
| 1555 | .into_iter() |
| 1556 | .next() |
| 1557 | .map(PathBuf::from) |
| 1558 | .map(|p| if p.is_absolute() { p } else { cwd.join(p) }); |
| 1559 | Ok((fixture, path)) |
| 1560 | } |
| 1561 | |
| 1562 | pub fn stage_label(stage: Stage) -> &'static str { |
| 1563 | match stage { |
| 1564 | Stage::Scan => "목록 읽는 중", |
| 1565 | Stage::Read => "파일 읽는 중", |
| 1566 | Stage::Decode => "압축 푸는 중", |
| 1567 | Stage::Write => "파일 쓰는 중", |
| 1568 | Stage::Verify => "검증 중", |
| 1569 | Stage::Commit => "저장 마무리 중", |
| 1570 | } |
| 1571 | } |
| 1572 | pub fn disposition_label(disposition: Disposition) -> &'static str { |
| 1573 | match disposition { |
| 1574 | Disposition::Created => "생성됨", |
| 1575 | Disposition::PartialRetained => "일부 파일 남음", |
| 1576 | Disposition::Removed => "작업 임시 파일 정리됨", |
| 1577 | Disposition::CommitUncertain => "저장 여부 불확실", |
| 1578 | } |
| 1579 | } |
| 1580 | pub fn terminal_lines(t: &Terminal) -> Vec<String> { |
| 1581 | let publication = match t.publication { |
| 1582 | Publication::None => "게시된 파일 없음", |
| 1583 | Publication::Partial => "일부 파일 게시됨", |
| 1584 | Publication::Complete => "파일 게시 완료", |
| 1585 | Publication::Uncertain => "파일 게시 여부 불확실 / 출력 폴더를 확인하세요", |
| 1586 | }; |
| 1587 | let durability = match t.durability { |
| 1588 | Durability::NotApplicable => "동기화 해당 없음", |
| 1589 | Durability::Synced => "디스크 동기화 완료", |
| 1590 | Durability::Unconfirmed => "디스크 동기화 미확인", |
| 1591 | Durability::Failed => "디스크 동기화 실패", |
| 1592 | }; |
| 1593 | let cleanup = match t.cleanup { |
| 1594 | Cleanup::Complete => "작업 임시 파일 정리 완료", |
| 1595 | Cleanup::Failed => "작업 임시 파일 정리 실패", |
| 1596 | Cleanup::Unconfirmed => "작업 임시 파일 정리 미확인", |
| 1597 | }; |
| 1598 | let mut lines = vec![ |
| 1599 | publication.into(), |
| 1600 | format!( |
| 1601 | "생성 {}개 / 남은 임시 파일 {}개", |
| 1602 | t.created_count, t.retained_partial_count |
| 1603 | ), |
| 1604 | format!("{durability} / {cleanup}"), |
| 1605 | ]; |
| 1606 | if let Some(error) = t.error { |
| 1607 | lines.push( |
| 1608 | match error { |
| 1609 | ErrorCode::RecoveryIncomplete => "일부 항목만 복구했습니다", |
| 1610 | ErrorCode::RecoveryImpossible => "복구 가능한 항목이 없습니다", |
| 1611 | ErrorCode::MissingVolume => "분할 압축파일의 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 첫 조각을 다시 여세요", |
| 1612 | ErrorCode::Integrity => "압축파일이 손상됐습니다", |
| 1613 | ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다", |
| 1614 | ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다", |
| 1615 | ErrorCode::WrongPassword => "암호가 올바르지 않습니다", |
| 1616 | ErrorCode::UnsafePath => "안전하지 않은 경로가 있어 중단했습니다", |
| 1617 | ErrorCode::Conflict => "같은 이름의 파일이 있습니다. 다른 출력 폴더를 선택하세요", |
| 1618 | ErrorCode::Limit => "처리 한도를 초과했습니다", |
| 1619 | ErrorCode::Io => { |
| 1620 | "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요" |
| 1621 | } |
| 1622 | ErrorCode::DiskFull => { |
| 1623 | "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요" |
| 1624 | } |
| 1625 | ErrorCode::Protocol => "작업자 응답이 올바르지 않습니다", |
| 1626 | ErrorCode::Internal => "작업자 처리 오류입니다", |
| 1627 | ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요", |
| 1628 | ErrorCode::InvalidRequest => "입력과 선택한 항목을 확인하세요", |
| 1629 | } |
| 1630 | .into(), |
| 1631 | ); |
| 1632 | } |
| 1633 | lines |
| 1634 | } |