| 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 | } |
| 16 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 17 | pub struct ListId { |
| 18 | pub catalog_version: u16, |
| 19 | pub format: Format, |
| 20 | pub source_object: SourceObject, |
| 21 | pub archive_bytes: u64, |
| 22 | pub archive_sha256: [u8; 32], |
| 23 | } |
| 24 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 25 | pub enum Selection { |
| 26 | All, |
| 27 | EntryIds(Vec<u32>), |
| 28 | } |
| 29 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 30 | pub enum Method { |
| 31 | Store, |
| 32 | Deflate, |
| 33 | } |
| 34 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 35 | pub enum Start { |
| 36 | List { |
| 37 | archive: PathBuf, |
| 38 | }, |
| 39 | Extract { |
| 40 | archive: PathBuf, |
| 41 | destination: PathBuf, |
| 42 | selection: Selection, |
| 43 | list_id: ListId, |
| 44 | gzip_output_name: Option<String>, |
| 45 | }, |
| 46 | CreateZip { |
| 47 | sources: Vec<(PathBuf, String)>, |
| 48 | output_file: PathBuf, |
| 49 | method: Method, |
| 50 | aes256: bool, |
| 51 | }, |
| 52 | } |
| 53 | // 암호를 Debug와 로그에서 제외하고 소유 버퍼를 해제 전에 지움. |
| 54 | pub struct Secret(Vec<u8>); |
| 55 | impl Secret { |
| 56 | pub fn new(text: String) -> Result<Self, &'static str> { |
| 57 | let mut bytes = text.into_bytes(); |
| 58 | if bytes.is_empty() || bytes.len() > 1024 { |
| 59 | bytes.fill(0); |
| 60 | return Err("암호는 UTF-8 1~1024바이트로 입력하세요"); |
| 61 | } |
| 62 | Ok(Self(bytes)) |
| 63 | } |
| 64 | pub fn as_bytes(&self) -> &[u8] { |
| 65 | &self.0 |
| 66 | } |
| 67 | } |
| 68 | impl Drop for Secret { |
| 69 | fn drop(&mut self) { |
| 70 | self.0.fill(0); |
| 71 | } |
| 72 | } |
| 73 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 74 | pub enum ConflictChoice { |
| 75 | Overwrite, |
| 76 | Skip, |
| 77 | Rename, |
| 78 | } |
| 79 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 80 | pub struct Conflict { |
| 81 | pub challenge_id: u64, |
| 82 | pub entry_id: u32, |
| 83 | pub relative_name: String, |
| 84 | pub incoming_size: u64, |
| 85 | pub existing_size: u64, |
| 86 | } |
| 87 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 88 | pub struct Resolution { |
| 89 | pub entry_id: u32, |
| 90 | pub relative_name: String, |
| 91 | pub choice: ConflictChoice, |
| 92 | } |
| 93 | pub enum Command { |
| 94 | Start(Start), |
| 95 | Password { |
| 96 | challenge_id: u64, |
| 97 | secret: Secret, |
| 98 | }, |
| 99 | ConflictReply { |
| 100 | challenge_id: u64, |
| 101 | choice: ConflictChoice, |
| 102 | apply_to_remaining: bool, |
| 103 | }, |
| 104 | Cancel, |
| 105 | } |
| 106 | pub struct Request { |
| 107 | pub job_id: u64, |
| 108 | pub sequence: u64, |
| 109 | pub command: Command, |
| 110 | } |
| 111 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 112 | pub enum Kind { |
| 113 | File, |
| 114 | Directory, |
| 115 | Link, |
| 116 | Other, |
| 117 | } |
| 118 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 119 | pub struct Entry { |
| 120 | pub id: u32, |
| 121 | pub name: String, |
| 122 | pub kind: Kind, |
| 123 | pub bytes: Option<u64>, |
| 124 | pub packed: Option<u64>, |
| 125 | pub encrypted: bool, |
| 126 | } |
| 127 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 128 | pub enum CancelStatus { |
| 129 | Requested, |
| 130 | AlreadyRequested, |
| 131 | TooLate, |
| 132 | Finished, |
| 133 | } |
| 134 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 135 | pub enum Stage { |
| 136 | Scan, |
| 137 | Read, |
| 138 | Decode, |
| 139 | Write, |
| 140 | Verify, |
| 141 | Commit, |
| 142 | } |
| 143 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 144 | pub enum Outcome { |
| 145 | Completed, |
| 146 | Failed, |
| 147 | Cancelled, |
| 148 | } |
| 149 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 150 | pub enum ErrorCode { |
| 151 | Integrity, |
| 152 | UnsupportedFormat, |
| 153 | UnsupportedFeature, |
| 154 | WrongPassword, |
| 155 | UnsafePath, |
| 156 | Conflict, |
| 157 | Limit, |
| 158 | Io, |
| 159 | DiskFull, |
| 160 | Protocol, |
| 161 | Internal, |
| 162 | SourceChanged, |
| 163 | InvalidRequest, |
| 164 | } |
| 165 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 166 | pub enum Publication { |
| 167 | None, |
| 168 | Partial, |
| 169 | Complete, |
| 170 | Uncertain, |
| 171 | } |
| 172 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 173 | pub enum Durability { |
| 174 | NotApplicable, |
| 175 | Synced, |
| 176 | Unconfirmed, |
| 177 | Failed, |
| 178 | } |
| 179 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 180 | pub enum Cleanup { |
| 181 | Complete, |
| 182 | Failed, |
| 183 | Unconfirmed, |
| 184 | } |
| 185 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 186 | pub enum Disposition { |
| 187 | Created, |
| 188 | PartialRetained, |
| 189 | Removed, |
| 190 | CommitUncertain, |
| 191 | } |
| 192 | #[derive(Clone, Debug)] |
| 193 | pub struct Terminal { |
| 194 | pub outcome: Outcome, |
| 195 | pub error: Option<ErrorCode>, |
| 196 | pub publication: Publication, |
| 197 | pub created_count: u64, |
| 198 | pub retained_partial_count: u64, |
| 199 | pub durability: Durability, |
| 200 | pub cleanup: Cleanup, |
| 201 | } |
| 202 | #[derive(Clone, Debug)] |
| 203 | pub enum Event { |
| 204 | Accepted { |
| 205 | encryption: bool, |
| 206 | }, |
| 207 | Entry(Entry), |
| 208 | ListEnd { |
| 209 | entry_count: u32, |
| 210 | list_id: ListId, |
| 211 | }, |
| 212 | PasswordRequired { |
| 213 | challenge_id: u64, |
| 214 | attempt: u32, |
| 215 | encrypt: bool, |
| 216 | }, |
| 217 | ConflictRequired(Conflict), |
| 218 | ConflictResolved(Resolution), |
| 219 | Progress { |
| 220 | stage: Stage, |
| 221 | processed: u64, |
| 222 | total: Option<u64>, |
| 223 | completed_entries: u64, |
| 224 | }, |
| 225 | Output { |
| 226 | entry_id: Option<u32>, |
| 227 | relative_name: String, |
| 228 | disposition: Disposition, |
| 229 | }, |
| 230 | CancelAck { |
| 231 | request_sequence: u64, |
| 232 | status: CancelStatus, |
| 233 | }, |
| 234 | Terminal(Terminal), |
| 235 | } |
| 236 | pub enum HostEvent { |
| 237 | Fault(String), |
| 238 | CleanupComplete, |
| 239 | Frame { |
| 240 | job_id: u64, |
| 241 | sequence: u64, |
| 242 | event: Event, |
| 243 | }, |
| 244 | StdoutEof, |
| 245 | StderrEof, |
| 246 | Exited { |
| 247 | success: bool, |
| 248 | }, |
| 249 | } |
| 250 | // 바이트 codec과 프로세스 소유는 작업자 어댑터에서 담당함. |
| 251 | // 전송 실패 후에도 poll로 양쪽 EOF와 자식 회수 결과를 전달함. |
| 252 | pub trait Connection { |
| 253 | fn send(&mut self, request: Request) -> Result<(), String>; |
| 254 | fn poll(&mut self) -> Option<HostEvent>; |
| 255 | } |
| 256 | pub trait Factory { |
| 257 | fn connect(&mut self, job_id: u64) -> Result<Box<dyn Connection>, String>; |
| 258 | } |
| 259 | pub struct Unavailable; |
| 260 | impl Factory for Unavailable { |
| 261 | fn connect(&mut self, _: u64) -> Result<Box<dyn Connection>, String> { |
| 262 | Err("작업자 연결이 아직 준비되지 않았습니다".into()) |
| 263 | } |
| 264 | } |
| 265 | struct Running { |
| 266 | id: u64, |
| 267 | outgoing: u64, |
| 268 | incoming: u64, |
| 269 | accepted: bool, |
| 270 | start_failed: bool, |
| 271 | start: Start, |
| 272 | connection: Box<dyn Connection>, |
| 273 | entries: Vec<Entry>, |
| 274 | list_end: Option<(u32, ListId)>, |
| 275 | stdout_eof: bool, |
| 276 | transport_closed: bool, |
| 277 | stderr_eof: bool, |
| 278 | exit: Option<bool>, |
| 279 | cancel_sequence: Option<u64>, |
| 280 | conflict_ids: BTreeSet<u64>, |
| 281 | resolved_ids: BTreeSet<u32>, |
| 282 | file_ids: BTreeSet<u32>, |
| 283 | } |
| 284 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
| 285 | pub enum Close { |
| 286 | #[default] |
| 287 | Open, |
| 288 | Confirm, |
| 289 | Waiting, |
| 290 | Review, |
| 291 | Allowed, |
| 292 | } |
| 293 | #[derive(Default)] |
| 294 | pub struct Model { |
| 295 | running: Option<Running>, |
| 296 | next_id: u64, |
| 297 | pub archive: Option<PathBuf>, |
| 298 | pub entries: Vec<Entry>, |
| 299 | pub list_id: Option<ListId>, |
| 300 | pub selected: BTreeSet<u32>, |
| 301 | pub terminal: Option<Terminal>, |
| 302 | pub challenge: Option<(u64, u32, bool)>, |
| 303 | pub conflict: Option<Conflict>, |
| 304 | pub resolutions: Vec<Resolution>, |
| 305 | pub progress: Option<(Stage, u64, Option<u64>, u64)>, |
| 306 | pub outputs: Vec<(String, Disposition)>, |
| 307 | pub cancel: Option<CancelStatus>, |
| 308 | pub error: Option<String>, |
| 309 | pub input_error: Option<String>, |
| 310 | pub encryption: bool, |
| 311 | pub close: Close, |
| 312 | pub confirmed: bool, |
| 313 | } |
| 314 | impl Model { |
| 315 | pub fn busy(&self) -> bool { |
| 316 | self.running.is_some() |
| 317 | } |
| 318 | pub fn cancellation_requested(&self) -> bool { |
| 319 | self.running |
| 320 | .as_ref() |
| 321 | .is_some_and(|run| run.cancel_sequence.is_some()) |
| 322 | } |
| 323 | pub fn job_id(&self) -> Option<u64> { |
| 324 | self.running.as_ref().map(|r| r.id) |
| 325 | } |
| 326 | pub fn can_extract(&self) -> bool { |
| 327 | !self.busy() |
| 328 | && self.list_id.is_some() |
| 329 | && self.archive.is_some() |
| 330 | && self.close == Close::Open |
| 331 | } |
| 332 | pub fn begin(&mut self, start: Start, factory: &mut dyn Factory) -> bool { |
| 333 | if self.busy() || self.close != Close::Open { |
| 334 | return false; |
| 335 | } |
| 336 | let validation = match &start { |
| 337 | Start::List { archive } => archive.is_absolute(), |
| 338 | Start::Extract { |
| 339 | archive, |
| 340 | destination, |
| 341 | selection, |
| 342 | gzip_output_name, |
| 343 | list_id, |
| 344 | } => { |
| 345 | archive.is_absolute() |
| 346 | && destination.is_absolute() |
| 347 | && self.archive.as_ref() == Some(archive) |
| 348 | && self.list_id.as_ref() == Some(list_id) |
| 349 | && match list_id.format { |
| 350 | Format::Gzip => gzip_output_name.as_ref().is_some_and(|s| valid_leaf(s)), |
| 351 | _ => gzip_output_name.is_none(), |
| 352 | } |
| 353 | && match selection { |
| 354 | Selection::All => true, |
| 355 | Selection::EntryIds(ids) => { |
| 356 | !ids.is_empty() |
| 357 | && ids.iter().collect::<BTreeSet<_>>().len() == ids.len() |
| 358 | && ids.iter().all(|id| { |
| 359 | self.entries.iter().any(|e| { |
| 360 | e.id == *id |
| 361 | && matches!(e.kind, Kind::File | Kind::Directory) |
| 362 | }) |
| 363 | }) |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | Start::CreateZip { |
| 368 | sources, |
| 369 | output_file, |
| 370 | .. |
| 371 | } => { |
| 372 | !sources.is_empty() |
| 373 | && output_file.is_absolute() |
| 374 | && sources |
| 375 | .iter() |
| 376 | .all(|(p, n)| p.is_absolute() && valid_relative(n)) |
| 377 | } |
| 378 | }; |
| 379 | if !validation { |
| 380 | self.input_error = Some("입력 경로, 출력명과 선택한 목록을 확인하세요".into()); |
| 381 | return false; |
| 382 | } |
| 383 | let Some(id) = self.next_id.checked_add(1) else { |
| 384 | self.error = Some("작업 ID 한도에 도달했습니다".into()); |
| 385 | return false; |
| 386 | }; |
| 387 | let mut connection = match factory.connect(id) { |
| 388 | Ok(c) => c, |
| 389 | Err(e) => { |
| 390 | self.error = Some(e); |
| 391 | return false; |
| 392 | } |
| 393 | }; |
| 394 | let send_error = connection |
| 395 | .send(Request { |
| 396 | job_id: id, |
| 397 | sequence: 0, |
| 398 | command: Command::Start(start.clone()), |
| 399 | }) |
| 400 | .err(); |
| 401 | let started = send_error.is_none(); |
| 402 | if let Start::List { archive } = &start |
| 403 | && started |
| 404 | { |
| 405 | self.archive = Some(archive.clone()); |
| 406 | self.list_id = None; |
| 407 | self.entries.clear(); |
| 408 | self.selected.clear(); |
| 409 | } |
| 410 | self.next_id = id; |
| 411 | self.terminal = None; |
| 412 | self.challenge = None; |
| 413 | self.conflict = None; |
| 414 | self.resolutions.clear(); |
| 415 | self.progress = None; |
| 416 | self.outputs.clear(); |
| 417 | self.cancel = None; |
| 418 | self.input_error = None; |
| 419 | self.error = send_error; |
| 420 | self.confirmed = false; |
| 421 | self.running = Some(Running { |
| 422 | id, |
| 423 | outgoing: 1, |
| 424 | incoming: 0, |
| 425 | accepted: false, |
| 426 | start_failed: !started, |
| 427 | start, |
| 428 | connection, |
| 429 | entries: Vec::new(), |
| 430 | list_end: None, |
| 431 | stdout_eof: false, |
| 432 | transport_closed: false, |
| 433 | stderr_eof: false, |
| 434 | exit: None, |
| 435 | cancel_sequence: None, |
| 436 | conflict_ids: BTreeSet::new(), |
| 437 | resolved_ids: BTreeSet::new(), |
| 438 | file_ids: self |
| 439 | .entries |
| 440 | .iter() |
| 441 | .filter(|e| e.kind == Kind::File) |
| 442 | .map(|e| e.id) |
| 443 | .collect(), |
| 444 | }); |
| 445 | started |
| 446 | } |
| 447 | pub fn extract( |
| 448 | &mut self, |
| 449 | destination: PathBuf, |
| 450 | selected_only: bool, |
| 451 | gzip_output_name: Option<String>, |
| 452 | factory: &mut dyn Factory, |
| 453 | ) -> bool { |
| 454 | if !self.can_extract() { |
| 455 | return false; |
| 456 | } |
| 457 | self.begin( |
| 458 | Start::Extract { |
| 459 | archive: self.archive.clone().unwrap(), |
| 460 | destination, |
| 461 | selection: if selected_only { |
| 462 | Selection::EntryIds(self.selected.iter().copied().collect()) |
| 463 | } else { |
| 464 | Selection::All |
| 465 | }, |
| 466 | list_id: self.list_id.clone().unwrap(), |
| 467 | gzip_output_name, |
| 468 | }, |
| 469 | factory, |
| 470 | ) |
| 471 | } |
| 472 | pub fn password(&mut self, text: String) -> bool { |
| 473 | let Some((challenge_id, _, _)) = self.challenge else { |
| 474 | return false; |
| 475 | }; |
| 476 | let secret = match Secret::new(text) { |
| 477 | Ok(s) => s, |
| 478 | Err(e) => { |
| 479 | self.input_error = Some(e.into()); |
| 480 | return false; |
| 481 | } |
| 482 | }; |
| 483 | if self |
| 484 | .send(Command::Password { |
| 485 | challenge_id, |
| 486 | secret, |
| 487 | }) |
| 488 | .is_some() |
| 489 | { |
| 490 | self.challenge = None; |
| 491 | self.conflict = None; |
| 492 | self.input_error = None; |
| 493 | true |
| 494 | } else { |
| 495 | false |
| 496 | } |
| 497 | } |
| 498 | pub fn resolve_conflict(&mut self, choice: ConflictChoice, apply_to_remaining: bool) -> bool { |
| 499 | let Some(conflict) = &self.conflict else { |
| 500 | return false; |
| 501 | }; |
| 502 | if self.cancellation_requested() || self.error.is_some() || self.close != Close::Open { |
| 503 | return false; |
| 504 | } |
| 505 | if self |
| 506 | .send(Command::ConflictReply { |
| 507 | challenge_id: conflict.challenge_id, |
| 508 | choice, |
| 509 | apply_to_remaining, |
| 510 | }) |
| 511 | .is_some() |
| 512 | { |
| 513 | self.conflict = None; |
| 514 | self.input_error = None; |
| 515 | true |
| 516 | } else { |
| 517 | false |
| 518 | } |
| 519 | } |
| 520 | fn send(&mut self, command: Command) -> Option<u64> { |
| 521 | let run = self.running.as_mut()?; |
| 522 | if run.start_failed || self.terminal.is_some() || run.exit.is_some() { |
| 523 | return None; |
| 524 | } |
| 525 | let seq = run.outgoing; |
| 526 | let Some(next) = seq.checked_add(1) else { |
| 527 | self.error = Some("요청 순서 한도 초과".into()); |
| 528 | return None; |
| 529 | }; |
| 530 | match run.connection.send(Request { |
| 531 | job_id: run.id, |
| 532 | sequence: seq, |
| 533 | command, |
| 534 | }) { |
| 535 | Ok(()) => { |
| 536 | run.outgoing = next; |
| 537 | Some(seq) |
| 538 | } |
| 539 | Err(e) => { |
| 540 | self.error = Some(e); |
| 541 | None |
| 542 | } |
| 543 | } |
| 544 | } |
| 545 | pub fn cancel(&mut self) { |
| 546 | if self |
| 547 | .running |
| 548 | .as_ref() |
| 549 | .is_some_and(|r| r.cancel_sequence.is_none()) |
| 550 | { |
| 551 | if let Some(seq) = self.send(Command::Cancel) { |
| 552 | self.running.as_mut().unwrap().cancel_sequence = Some(seq); |
| 553 | self.challenge = None; |
| 554 | self.conflict = None; |
| 555 | self.input_error = None; |
| 556 | } |
| 557 | } |
| 558 | } |
| 559 | pub fn request_close(&mut self) { |
| 560 | if self.close == Close::Open { |
| 561 | self.close = if self.busy() { |
| 562 | Close::Confirm |
| 563 | } else { |
| 564 | Close::Review |
| 565 | }; |
| 566 | } |
| 567 | } |
| 568 | pub fn confirm_close(&mut self) { |
| 569 | if self.close == Close::Confirm { |
| 570 | self.cancel(); |
| 571 | self.close = if self.busy() { |
| 572 | Close::Waiting |
| 573 | } else { |
| 574 | Close::Review |
| 575 | }; |
| 576 | } |
| 577 | } |
| 578 | pub fn keep_open(&mut self) { |
| 579 | if self.close != Close::Allowed { |
| 580 | self.close = Close::Open; |
| 581 | } |
| 582 | } |
| 583 | pub fn acknowledge_close(&mut self) { |
| 584 | if !self.busy() && self.close == Close::Review { |
| 585 | self.close = Close::Allowed; |
| 586 | } |
| 587 | } |
| 588 | pub fn poll(&mut self) { |
| 589 | for _ in 0..128 { |
| 590 | let Some(event) = self.running.as_mut().and_then(|r| r.connection.poll()) else { |
| 591 | break; |
| 592 | }; |
| 593 | self.receive(event); |
| 594 | } |
| 595 | let complete = self.running.as_ref().is_some_and(|r| { |
| 596 | r.exit.is_some() |
| 597 | && ((r.stdout_eof && r.stderr_eof) || (r.transport_closed && self.error.is_some())) |
| 598 | }); |
| 599 | if complete { |
| 600 | let run = self.running.take().unwrap(); |
| 601 | self.confirmed = |
| 602 | self.terminal.is_some() && run.exit == Some(true) && self.error.is_none(); |
| 603 | if !self.confirmed { |
| 604 | self.error.get_or_insert( |
| 605 | "작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요".into(), |
| 606 | ); |
| 607 | } |
| 608 | if self.confirmed |
| 609 | && self |
| 610 | .terminal |
| 611 | .as_ref() |
| 612 | .is_some_and(|t| t.outcome == Outcome::Completed) |
| 613 | { |
| 614 | if matches!(run.start, Start::List { .. }) { |
| 615 | if let Some((count, id)) = run |
| 616 | .list_end |
| 617 | .filter(|(n, _)| *n as usize == run.entries.len()) |
| 618 | { |
| 619 | let _ = count; |
| 620 | self.entries = run.entries; |
| 621 | self.list_id = Some(id); |
| 622 | } else { |
| 623 | self.error = Some("목록 완료 정보가 일치하지 않습니다. 다시 여세요".into()); |
| 624 | self.confirmed = false; |
| 625 | } |
| 626 | } |
| 627 | } |
| 628 | if self |
| 629 | .terminal |
| 630 | .as_ref() |
| 631 | .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged)) |
| 632 | { |
| 633 | self.list_id = None; |
| 634 | self.selected.clear(); |
| 635 | } |
| 636 | self.challenge = None; |
| 637 | self.conflict = None; |
| 638 | self.input_error = None; |
| 639 | if matches!(self.close, Close::Waiting | Close::Confirm) { |
| 640 | self.close = Close::Review; |
| 641 | } |
| 642 | } |
| 643 | } |
| 644 | fn receive(&mut self, host: HostEvent) { |
| 645 | let run = self.running.as_mut().unwrap(); |
| 646 | match host { |
| 647 | HostEvent::Fault(message) => self.error = Some(message), |
| 648 | HostEvent::CleanupComplete => run.transport_closed = true, |
| 649 | HostEvent::StdoutEof => run.stdout_eof = true, |
| 650 | HostEvent::StderrEof => run.stderr_eof = true, |
| 651 | HostEvent::Exited { success } => run.exit = Some(success), |
| 652 | HostEvent::Frame { |
| 653 | job_id, |
| 654 | sequence, |
| 655 | event, |
| 656 | } => { |
| 657 | if job_id != run.id |
| 658 | || sequence != run.incoming |
| 659 | || self.terminal.is_some() |
| 660 | || run.stdout_eof |
| 661 | || sequence >= 1_000_000 |
| 662 | { |
| 663 | self.error = Some("작업자 응답 순서나 작업 ID가 일치하지 않습니다".into()); |
| 664 | return; |
| 665 | } |
| 666 | run.incoming += 1; |
| 667 | if !run.accepted && !matches!(event, Event::Accepted { .. }) { |
| 668 | self.error = Some("작업 승인 응답이 없습니다".into()); |
| 669 | return; |
| 670 | } |
| 671 | match event { |
| 672 | Event::Accepted { encryption } => { |
| 673 | if run.accepted { |
| 674 | self.error = Some("작업 승인 중복".into()); |
| 675 | } |
| 676 | run.accepted = true; |
| 677 | self.encryption = encryption; |
| 678 | } |
| 679 | Event::Entry(entry) => { |
| 680 | if !matches!(run.start, Start::List { .. }) |
| 681 | || run.list_end.is_some() |
| 682 | || entry.id as usize != run.entries.len() |
| 683 | || entry.name.len() > 4096 |
| 684 | || run.entries.len() >= 100_000 |
| 685 | { |
| 686 | self.error = Some("목록 응답이 유효하지 않습니다".into()); |
| 687 | } else { |
| 688 | run.entries.push(entry); |
| 689 | } |
| 690 | } |
| 691 | Event::ListEnd { |
| 692 | entry_count, |
| 693 | list_id, |
| 694 | } => { |
| 695 | if !matches!(run.start, Start::List { .. }) |
| 696 | || run.list_end.is_some() |
| 697 | || list_id.catalog_version != 1 |
| 698 | { |
| 699 | self.error = Some("목록 완료 응답이 유효하지 않습니다".into()); |
| 700 | } else { |
| 701 | run.list_end = Some((entry_count, list_id)); |
| 702 | } |
| 703 | } |
| 704 | Event::PasswordRequired { |
| 705 | challenge_id, |
| 706 | attempt, |
| 707 | encrypt, |
| 708 | } => { |
| 709 | if self.challenge.is_some() || self.conflict.is_some() || challenge_id == 0 |
| 710 | { |
| 711 | self.error = Some("암호 요청이 유효하지 않습니다".into()); |
| 712 | } else { |
| 713 | self.challenge = Some((challenge_id, attempt, encrypt)); |
| 714 | } |
| 715 | } |
| 716 | Event::ConflictRequired(conflict) => { |
| 717 | let valid_entry = self |
| 718 | .entries |
| 719 | .iter() |
| 720 | .any(|entry| entry.id == conflict.entry_id && entry.kind == Kind::File); |
| 721 | if !matches!(run.start, Start::Extract { .. }) |
| 722 | || !valid_entry |
| 723 | || conflict.challenge_id == 0 |
| 724 | || self.challenge.is_some() |
| 725 | || self.conflict.is_some() |
| 726 | || run.conflict_ids.len() >= 100_000 |
| 727 | || !valid_relative(&conflict.relative_name) |
| 728 | || conflict.relative_name.len() > 4096 |
| 729 | || !run.conflict_ids.insert(conflict.challenge_id) |
| 730 | { |
| 731 | self.error = Some("파일 충돌 요청이 유효하지 않습니다".into()); |
| 732 | } else if run.cancel_sequence.is_none() { |
| 733 | self.conflict = Some(conflict); |
| 734 | } |
| 735 | } |
| 736 | Event::ConflictResolved(resolution) => { |
| 737 | if !matches!(run.start, Start::Extract { .. }) |
| 738 | || !run.file_ids.contains(&resolution.entry_id) |
| 739 | || self.resolutions.len() >= 100_000 |
| 740 | || !valid_relative(&resolution.relative_name) |
| 741 | || resolution.relative_name.len() > 4096 |
| 742 | || !run.resolved_ids.insert(resolution.entry_id) |
| 743 | { |
| 744 | self.error = Some("파일 충돌 결과가 유효하지 않습니다".into()); |
| 745 | } else { |
| 746 | self.resolutions.push(resolution); |
| 747 | } |
| 748 | } |
| 749 | Event::Progress { |
| 750 | stage, |
| 751 | processed, |
| 752 | total, |
| 753 | completed_entries, |
| 754 | } => self.progress = Some((stage, processed, total, completed_entries)), |
| 755 | Event::Output { |
| 756 | relative_name, |
| 757 | disposition, |
| 758 | .. |
| 759 | } => { |
| 760 | if self.outputs.len() < 100_000 && relative_name.len() <= 4096 { |
| 761 | self.outputs.push((relative_name, disposition)); |
| 762 | } else { |
| 763 | self.error = Some("출력 보고 한도 초과".into()); |
| 764 | } |
| 765 | } |
| 766 | Event::CancelAck { |
| 767 | request_sequence, |
| 768 | status, |
| 769 | } => { |
| 770 | if run.cancel_sequence == Some(request_sequence) && self.cancel.is_none() { |
| 771 | self.cancel = Some(status); |
| 772 | } else { |
| 773 | self.error = Some("취소 응답이 요청과 일치하지 않습니다".into()); |
| 774 | } |
| 775 | } |
| 776 | Event::Terminal(t) => { |
| 777 | self.challenge = None; |
| 778 | self.conflict = None; |
| 779 | self.terminal = Some(t); |
| 780 | } |
| 781 | } |
| 782 | } |
| 783 | } |
| 784 | } |
| 785 | pub fn status(&self) -> String { |
| 786 | if let Some(error) = self.error.as_ref().or(self.input_error.as_ref()) { |
| 787 | return error.clone(); |
| 788 | } |
| 789 | if self.busy() { |
| 790 | if self.terminal.is_some() { |
| 791 | return "작업 결과 수신 / 프로세스 종료 확인 중".into(); |
| 792 | } |
| 793 | if self.conflict.is_some() { |
| 794 | return "같은 이름의 파일을 처리할 방법을 선택하세요".into(); |
| 795 | } |
| 796 | if self.challenge.is_some() { |
| 797 | return "암호를 입력하세요".into(); |
| 798 | } |
| 799 | if let Some(c) = self.cancel { |
| 800 | return match c { |
| 801 | CancelStatus::Requested | CancelStatus::AlreadyRequested => { |
| 802 | "취소 요청 접수 / 최종 결과 대기" |
| 803 | } |
| 804 | CancelStatus::TooLate => "취소할 수 없는 단계 / 최종 결과 대기", |
| 805 | CancelStatus::Finished => "처리 종료 응답 / 프로세스 종료 확인 중", |
| 806 | } |
| 807 | .into(); |
| 808 | } |
| 809 | if self |
| 810 | .running |
| 811 | .as_ref() |
| 812 | .is_some_and(|r| r.cancel_sequence.is_some()) |
| 813 | { |
| 814 | return "취소 요청 전송 / 최종 결과 대기".into(); |
| 815 | } |
| 816 | return "작업 중".into(); |
| 817 | } |
| 818 | match self |
| 819 | .terminal |
| 820 | .as_ref() |
| 821 | .filter(|_| self.confirmed) |
| 822 | .map(|t| t.outcome) |
| 823 | { |
| 824 | Some(Outcome::Completed) => "작업 완료", |
| 825 | Some(Outcome::Cancelled) => "작업 취소됨", |
| 826 | Some(Outcome::Failed) => "작업 실패", |
| 827 | None => "압축파일을 열거나 ZIP 파일을 만드세요", |
| 828 | } |
| 829 | .into() |
| 830 | } |
| 831 | } |
| 832 | pub fn valid_leaf(name: &str) -> bool { |
| 833 | valid_relative(name) && !name.contains('/') && !name.contains('\\') |
| 834 | } |
| 835 | pub fn valid_relative(name: &str) -> bool { |
| 836 | !name.is_empty() |
| 837 | && !name.contains('\0') |
| 838 | && !name.contains(':') |
| 839 | && !name.starts_with('/') |
| 840 | && !name.starts_with('\\') |
| 841 | && name |
| 842 | .split(['/', '\\']) |
| 843 | .all(|p| !p.is_empty() && p != "." && p != "..") |
| 844 | } |
| 845 | |
| 846 | // 파일 연결로 전달된 원형 경로를 손실 변환 없이 보존함. |
| 847 | pub fn launch_args( |
| 848 | args: Vec<std::ffi::OsString>, |
| 849 | cwd: PathBuf, |
| 850 | ) -> Result<(bool, Option<PathBuf>), &'static str> { |
| 851 | let fixture = args.iter().any(|arg| arg == "--ui-fixture"); |
| 852 | let paths = args |
| 853 | .into_iter() |
| 854 | .filter(|arg| arg != "--ui-fixture") |
| 855 | .collect::<Vec<_>>(); |
| 856 | if paths.len() > 1 { |
| 857 | return Err("압축파일 하나를 지정하세요"); |
| 858 | } |
| 859 | let path = paths |
| 860 | .into_iter() |
| 861 | .next() |
| 862 | .map(PathBuf::from) |
| 863 | .map(|p| if p.is_absolute() { p } else { cwd.join(p) }); |
| 864 | Ok((fixture, path)) |
| 865 | } |
| 866 | |
| 867 | pub fn stage_label(stage: Stage) -> &'static str { |
| 868 | match stage { |
| 869 | Stage::Scan => "목록 읽는 중", |
| 870 | Stage::Read => "파일 읽는 중", |
| 871 | Stage::Decode => "압축 푸는 중", |
| 872 | Stage::Write => "파일 쓰는 중", |
| 873 | Stage::Verify => "검증 중", |
| 874 | Stage::Commit => "저장 마무리 중", |
| 875 | } |
| 876 | } |
| 877 | pub fn disposition_label(disposition: Disposition) -> &'static str { |
| 878 | match disposition { |
| 879 | Disposition::Created => "생성됨", |
| 880 | Disposition::PartialRetained => "일부 파일 남음", |
| 881 | Disposition::Removed => "작업 임시 파일 정리됨", |
| 882 | Disposition::CommitUncertain => "저장 여부 불확실", |
| 883 | } |
| 884 | } |
| 885 | pub fn terminal_lines(t: &Terminal) -> Vec<String> { |
| 886 | let publication = match t.publication { |
| 887 | Publication::None => "게시된 파일 없음", |
| 888 | Publication::Partial => "일부 파일 게시됨", |
| 889 | Publication::Complete => "파일 게시 완료", |
| 890 | Publication::Uncertain => "파일 게시 여부 불확실 / 출력 폴더를 확인하세요", |
| 891 | }; |
| 892 | let durability = match t.durability { |
| 893 | Durability::NotApplicable => "동기화 해당 없음", |
| 894 | Durability::Synced => "디스크 동기화 완료", |
| 895 | Durability::Unconfirmed => "디스크 동기화 미확인", |
| 896 | Durability::Failed => "디스크 동기화 실패", |
| 897 | }; |
| 898 | let cleanup = match t.cleanup { |
| 899 | Cleanup::Complete => "작업 임시 파일 정리 완료", |
| 900 | Cleanup::Failed => "작업 임시 파일 정리 실패", |
| 901 | Cleanup::Unconfirmed => "작업 임시 파일 정리 미확인", |
| 902 | }; |
| 903 | let mut lines = vec![ |
| 904 | publication.into(), |
| 905 | format!( |
| 906 | "생성 {}개 / 남은 임시 파일 {}개", |
| 907 | t.created_count, t.retained_partial_count |
| 908 | ), |
| 909 | format!("{durability} / {cleanup}"), |
| 910 | ]; |
| 911 | if let Some(error) = t.error { |
| 912 | lines.push( |
| 913 | match error { |
| 914 | ErrorCode::Integrity => "압축파일이 손상됐습니다", |
| 915 | ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다", |
| 916 | ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다", |
| 917 | ErrorCode::WrongPassword => "암호가 올바르지 않습니다", |
| 918 | ErrorCode::UnsafePath => "안전하지 않은 경로가 있어 중단했습니다", |
| 919 | ErrorCode::Conflict => "같은 이름의 파일이 있습니다. 다른 출력 폴더를 선택하세요", |
| 920 | ErrorCode::Limit => "처리 한도를 초과했습니다", |
| 921 | ErrorCode::Io => { |
| 922 | "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요" |
| 923 | } |
| 924 | ErrorCode::DiskFull => { |
| 925 | "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요" |
| 926 | } |
| 927 | ErrorCode::Protocol => "작업자 응답이 올바르지 않습니다", |
| 928 | ErrorCode::Internal => "작업자 처리 오류입니다", |
| 929 | ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요", |
| 930 | ErrorCode::InvalidRequest => "입력과 선택한 항목을 확인하세요", |
| 931 | } |
| 932 | .into(), |
| 933 | ); |
| 934 | } |
| 935 | lines |
| 936 | } |