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