team-ljyzipelo

공개
1,712줄64 KB
1use std::{collections::BTreeSet, path::PathBuf};
2
3#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4pub enum Format {
5 Zip,
6 Tar,
7 Gzip,
8 TarGzip,
9 SevenZip,
10}
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub 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)]
18pub 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}
25impl 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)]
41pub struct VolumeProblem {
42 pub reason: VolumeProblemReason,
43 pub volume: NativePath,
44}
45#[derive(Clone, Debug, Eq, PartialEq)]
46pub enum Selection {
47 All,
48 EntryIds(Vec<u32>),
49}
50#[derive(Clone, Copy, Debug, Eq, PartialEq)]
51pub enum Method {
52 Store,
53 Deflate,
54}
55#[derive(Clone, Debug, Eq, PartialEq)]
56pub 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와 로그에서 제외하고 소유 버퍼를 해제 전에 지움.
88pub struct Secret(Vec<u8>);
89impl 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}
102impl Drop for Secret {
103 fn drop(&mut self) {
104 self.0.fill(0);
105 }
106}
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
108pub enum ConflictChoice {
109 Overwrite,
110 Skip,
111 Rename,
112}
113#[derive(Clone, Debug, Eq, PartialEq)]
114pub 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)]
122pub struct Resolution {
123 pub entry_id: u32,
124 pub relative_name: String,
125 pub choice: ConflictChoice,
126}
127pub 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}
146pub struct Request {
147 pub job_id: u64,
148 pub sequence: u64,
149 pub command: Command,
150}
151#[derive(Clone, Copy, Debug, Eq, PartialEq)]
152pub enum Kind {
153 File,
154 Directory,
155 Link,
156 Other,
157}
158#[derive(Clone, Debug, Eq, PartialEq)]
159pub 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)]
168pub enum CancelStatus {
169 Requested,
170 AlreadyRequested,
171 TooLate,
172 Finished,
173}
174#[derive(Clone, Copy, Debug, Eq, PartialEq)]
175pub enum Stage {
176 Scan,
177 Read,
178 Decode,
179 Write,
180 Verify,
181 Commit,
182}
183#[derive(Clone, Copy, Debug, Eq, PartialEq)]
184pub enum Outcome {
185 Completed,
186 Failed,
187 Cancelled,
188}
189#[derive(Clone, Copy, Debug, Eq, PartialEq)]
190pub 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)]
209pub enum Publication {
210 None,
211 Partial,
212 Complete,
213 Uncertain,
214}
215#[derive(Clone, Copy, Debug, Eq, PartialEq)]
216pub enum Durability {
217 NotApplicable,
218 Synced,
219 Unconfirmed,
220 Failed,
221}
222#[derive(Clone, Copy, Debug, Eq, PartialEq)]
223pub enum Cleanup {
224 Complete,
225 Failed,
226 Unconfirmed,
227}
228#[derive(Clone, Copy, Debug, Eq, PartialEq)]
229pub enum Disposition {
230 Created,
231 PartialRetained,
232 Removed,
233 CommitUncertain,
234}
235#[derive(Clone, Debug)]
236pub 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}
245pub use worker_protocol::protocol::{
246 ActionKind, Limits, NativePath, PreviewFormat, PreviewInfo, RecoveryEnd, RecoveryEntry,
247 RecoveryMode, RecoveryReason, RecoveryStatus, ResourceScope, ResourceUsage,
248 VolumeProblemReason,
249};
250
251pub struct Preview {
252 pub info: PreviewInfo,
253 pub data: Vec<u8>,
254}
255
256struct PreviewBuffer {
257 info: PreviewInfo,
258 data: Vec<u8>,
259 ended: bool,
260}
261
262impl 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)]
294pub 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)]
304pub 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}
352pub 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와 자식 회수 결과를 전달함.
368pub trait Connection {
369 fn send(&mut self, request: Request) -> Result<(), String>;
370 fn poll(&mut self) -> Option<HostEvent>;
371}
372pub trait Factory {
373 fn connect(&mut self, job_id: u64) -> Result<Box<dyn Connection>, String>;
374}
375pub struct Unavailable;
376impl Factory for Unavailable {
377 fn connect(&mut self, _: u64) -> Result<Box<dyn Connection>, String> {
378 Err("작업자 연결이 아직 준비되지 않았습니다".into())
379 }
380}
381struct 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)]
409pub enum Close {
410 #[default]
411 Open,
412 Confirm,
413 Waiting,
414 Review,
415 Allowed,
416}
417#[derive(Default)]
418pub 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}
444impl 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 crate::log_debug!("작업을 시작하지 않음: 다른 작업 중이거나 닫는 중");
611 return false;
612 }
613 crate::log_debug!(
614 "작업 시작 요청 (확대 한도: {expanded}): {}",
615 crate::applog::brief(&start, 600)
616 );
617 let selectable: BTreeSet<_> = self
618 .entries
619 .iter()
620 .filter(|e| matches!(e.kind, Kind::File | Kind::Directory))
621 .map(|e| e.id)
622 .collect();
623 let validation = match &start {
624 Start::RecoverZip {
625 archive,
626 output_file,
627 } => archive.is_absolute() && output_file.is_absolute() && archive != output_file,
628 Start::List { archive } => archive.is_absolute(),
629 Start::Preview {
630 archive,
631 entry_id,
632 list_id,
633 } => {
634 archive.is_absolute()
635 && list_id.valid()
636 && !list_id.is_split()
637 && self.archive.as_ref() == Some(archive)
638 && self.list_id.as_ref() == Some(list_id)
639 && self
640 .entries
641 .iter()
642 .any(|e| e.id == *entry_id && e.kind == Kind::File)
643 }
644 Start::Extract {
645 archive,
646 destination,
647 selection,
648 gzip_output_name,
649 list_id,
650 } => {
651 archive.is_absolute()
652 && destination.is_absolute()
653 && self.archive.as_ref() == Some(archive)
654 && self.list_id.as_ref() == Some(list_id)
655 && match list_id.format {
656 Format::Gzip => gzip_output_name.as_ref().is_some_and(|s| valid_leaf(s)),
657 _ => gzip_output_name.is_none(),
658 }
659 && match selection {
660 Selection::All => true,
661 Selection::EntryIds(ids) => {
662 !ids.is_empty()
663 && ids.iter().collect::<BTreeSet<_>>().len() == ids.len()
664 && ids.iter().all(|id| selectable.contains(id))
665 }
666 }
667 }
668 Start::CreateZip {
669 sources,
670 output_file,
671 ..
672 }
673 | Start::CreateSevenZip {
674 sources,
675 output_file,
676 } => {
677 !sources.is_empty()
678 && output_file.is_absolute()
679 && sources
680 .iter()
681 .all(|(p, n)| p.is_absolute() && valid_relative(n))
682 }
683 };
684 if !validation {
685 self.input_error = Some("입력 경로, 출력명과 선택한 목록을 확인하세요".into());
686 return false;
687 }
688 let Some(id) = self.next_id.checked_add(1) else {
689 self.error = Some("작업 ID 한도에 도달했습니다".into());
690 return false;
691 };
692 self.preview = None;
693 let estimated = self.estimate(&start);
694 self.volume_problem = None;
695 let mut connection = match factory.connect(id) {
696 Ok(c) => c,
697 Err(e) => {
698 self.error = Some(e);
699 return false;
700 }
701 };
702 let send_error = connection
703 .send(Request {
704 job_id: id,
705 sequence: 0,
706 command: if expanded {
707 Command::StartExpanded(start.clone())
708 } else {
709 Command::Start(start.clone())
710 },
711 })
712 .err();
713 let started = send_error.is_none();
714 if let Start::List { archive } = &start
715 && started
716 {
717 self.archive = Some(archive.clone());
718 self.list_id = None;
719 self.entries.clear();
720 self.selected.clear();
721 }
722 self.next_id = id;
723 self.recovery_entries.clear();
724 self.recovery_end = None;
725 self.terminal = None;
726 self.volume_problem = None;
727 self.retry_start = None;
728 self.resource = None;
729 self.challenge = None;
730 self.conflict = None;
731 self.resolutions.clear();
732 self.progress = None;
733 self.outputs.clear();
734 self.cancel = None;
735 self.input_error = None;
736 self.error = send_error;
737 self.confirmed = false;
738 self.running = Some(Running {
739 recovery_metadata: 0,
740 volume_problem: None,
741 preview: None,
742 preview_discarded: false,
743 id,
744 outgoing: 1,
745 incoming: 0,
746 accepted: false,
747 start_failed: !started,
748 start,
749 connection,
750 entries: Vec::new(),
751 list_end: None,
752 stdout_eof: false,
753 transport_closed: false,
754 stderr_eof: false,
755 exit: None,
756 cancel_sequence: None,
757 expanded,
758 granted: ResourceScope::default(),
759 last_challenge: 0,
760 estimated,
761 conflict_ids: BTreeSet::new(),
762 resolved_ids: BTreeSet::new(),
763 file_ids: self
764 .entries
765 .iter()
766 .filter(|e| e.kind == Kind::File)
767 .map(|e| e.id)
768 .collect(),
769 });
770 started
771 }
772 pub fn extract(
773 &mut self,
774 destination: PathBuf,
775 selected_only: bool,
776 gzip_output_name: Option<String>,
777 factory: &mut dyn Factory,
778 ) -> bool {
779 if !self.can_extract() {
780 return false;
781 }
782 self.begin(
783 Start::Extract {
784 archive: self.archive.clone().unwrap(),
785 destination,
786 selection: if selected_only {
787 Selection::EntryIds(self.selected.iter().copied().collect())
788 } else {
789 Selection::All
790 },
791 list_id: self.list_id.clone().unwrap(),
792 gzip_output_name,
793 },
794 factory,
795 )
796 }
797 pub fn password(&mut self, text: String) -> bool {
798 let Some((challenge_id, _, _)) = self.challenge else {
799 return false;
800 };
801 let secret = match Secret::new(text) {
802 Ok(s) => s,
803 Err(e) => {
804 self.input_error = Some(e.into());
805 return false;
806 }
807 };
808 crate::log_debug!("암호 전달 (요청 {challenge_id}, 내용은 기록하지 않음)");
809 if self
810 .send(Command::Password {
811 challenge_id,
812 secret,
813 })
814 .is_some()
815 {
816 self.challenge = None;
817 self.resource = None;
818 self.conflict = None;
819 self.input_error = None;
820 true
821 } else {
822 false
823 }
824 }
825 pub fn resolve_conflict(&mut self, choice: ConflictChoice, apply_to_remaining: bool) -> bool {
826 let Some(conflict) = &self.conflict else {
827 return false;
828 };
829 if self.cancellation_requested() || self.error.is_some() || self.close != Close::Open {
830 return false;
831 }
832 if self
833 .send(Command::ConflictReply {
834 challenge_id: conflict.challenge_id,
835 choice,
836 apply_to_remaining,
837 })
838 .is_some()
839 {
840 self.conflict = None;
841 self.input_error = None;
842 true
843 } else {
844 false
845 }
846 }
847 fn send(&mut self, command: Command) -> Option<u64> {
848 let run = self.running.as_mut()?;
849 if run.start_failed || self.terminal.is_some() || run.exit.is_some() {
850 return None;
851 }
852 let seq = run.outgoing;
853 if crate::applog::enabled(crate::applog::Level::Trace) {
854 // 암호는 내용 없이 요청 번호만 남김.
855 let text = match &command {
856 Command::Start(start) => format!("Start {}", crate::applog::brief(start, 400)),
857 Command::StartExpanded(start) => {
858 format!("StartExpanded {}", crate::applog::brief(start, 400))
859 }
860 Command::ResourceReply {
861 challenge_id,
862 allow,
863 ..
864 } => format!("ResourceReply challenge={challenge_id} allow={allow}"),
865 Command::Password { challenge_id, .. } => {
866 format!("Password challenge={challenge_id}")
867 }
868 Command::ConflictReply {
869 challenge_id,
870 choice,
871 apply_to_remaining,
872 } => format!(
873 "ConflictReply challenge={challenge_id} choice={choice:?} apply={apply_to_remaining}"
874 ),
875 Command::Cancel => "Cancel".into(),
876 };
877 crate::log_trace!("작업 {} #{seq} 송신: {text}", run.id);
878 }
879 let Some(next) = seq.checked_add(1) else {
880 self.error = Some("요청 순서 한도 초과".into());
881 return None;
882 };
883 match run.connection.send(Request {
884 job_id: run.id,
885 sequence: seq,
886 command,
887 }) {
888 Ok(()) => {
889 run.outgoing = next;
890 Some(seq)
891 }
892 Err(e) => {
893 self.error = Some(e);
894 None
895 }
896 }
897 }
898 pub fn cancel(&mut self) {
899 crate::log_debug!("작업 취소 요청");
900 self.preview = None;
901 if let Some(run) = self.running.as_mut()
902 && matches!(run.start, Start::Preview { .. })
903 {
904 run.preview = None;
905 run.preview_discarded = true;
906 }
907 if self
908 .running
909 .as_ref()
910 .is_some_and(|r| r.cancel_sequence.is_none())
911 {
912 if let Some(seq) = self.send(Command::Cancel) {
913 self.running.as_mut().unwrap().cancel_sequence = Some(seq);
914 self.challenge = None;
915 self.resource = None;
916 self.conflict = None;
917 self.input_error = None;
918 }
919 }
920 }
921 pub fn request_close(&mut self) {
922 if self.close == Close::Open {
923 self.close = if self.busy() {
924 Close::Confirm
925 } else {
926 Close::Review
927 };
928 }
929 }
930 pub fn confirm_close(&mut self) {
931 if self.close == Close::Confirm {
932 self.cancel();
933 self.close = if self.busy() {
934 Close::Waiting
935 } else {
936 Close::Review
937 };
938 }
939 }
940 pub fn keep_open(&mut self) {
941 if self.close != Close::Allowed {
942 self.close = Close::Open;
943 }
944 }
945 pub fn acknowledge_close(&mut self) {
946 if !self.busy() && self.close == Close::Review {
947 self.close = Close::Allowed;
948 }
949 }
950 pub fn poll(&mut self) {
951 let changed = self.running.as_ref().is_some_and(|run| {
952 matches!(&run.start, Start::Preview { entry_id, .. }
953 if self.selected.len() != 1 || !self.selected.contains(entry_id))
954 });
955 if changed {
956 self.dismiss_preview();
957 }
958 for _ in 0..128 {
959 let Some(event) = self.running.as_mut().and_then(|r| r.connection.poll()) else {
960 break;
961 };
962 self.receive(event);
963 if self.error.is_some()
964 && self
965 .running
966 .as_ref()
967 .is_some_and(|run| matches!(run.start, Start::Preview { .. }))
968 {
969 self.cancel();
970 }
971 }
972 let complete = self.running.as_ref().is_some_and(|r| {
973 r.exit.is_some()
974 && ((r.stdout_eof && r.stderr_eof) || (r.transport_closed && self.error.is_some()))
975 });
976 if complete {
977 let mut run = self.running.take().unwrap();
978 self.confirmed =
979 self.terminal.is_some() && run.exit == Some(true) && self.error.is_none();
980 match (&self.terminal, &self.error) {
981 (_, Some(error)) => crate::log_error!("작업 {} 실패: {error}", run.id),
982 (Some(terminal), None) if terminal.error.is_some() => crate::log_warn!(
983 "작업 {} 끝남: {}",
984 run.id,
985 crate::applog::brief(terminal, 400)
986 ),
987 (Some(terminal), None) => crate::log_info!(
988 "작업 {} 끝남: {}",
989 run.id,
990 crate::applog::brief(terminal, 400)
991 ),
992 (None, None) => crate::log_warn!("작업 {} 종료 결과 없음", run.id),
993 }
994 if !self.confirmed {
995 self.error.get_or_insert(
996 "작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요".into(),
997 );
998 }
999 if self.confirmed
1000 && self
1001 .terminal
1002 .as_ref()
1003 .is_some_and(|t| t.outcome == Outcome::Completed)
1004 {
1005 if matches!(run.start, Start::List { .. }) {
1006 if let Some((count, id)) = run
1007 .list_end
1008 .filter(|(n, _)| *n as usize == run.entries.len())
1009 {
1010 let _ = count;
1011 self.entries = run.entries;
1012 self.list_id = Some(id);
1013 } else {
1014 self.error = Some("목록 완료 정보가 일치하지 않습니다. 다시 여세요".into());
1015 self.confirmed = false;
1016 }
1017 }
1018 }
1019 if matches!(run.start, Start::Preview { .. }) {
1020 if self.confirmed
1021 && self
1022 .terminal
1023 .as_ref()
1024 .is_some_and(|t| t.outcome == Outcome::Completed)
1025 && !run.preview_discarded
1026 {
1027 if let Some(buffer) = run.preview.take().filter(|b| b.ended) {
1028 self.preview = Some(Preview {
1029 info: buffer.info,
1030 data: buffer.data,
1031 });
1032 } else {
1033 self.error = Some("미리보기 완료 정보가 일치하지 않습니다".into());
1034 self.confirmed = false;
1035 }
1036 }
1037 }
1038 if self.terminal.as_ref().is_some_and(|t| {
1039 matches!(
1040 t.error,
1041 Some(ErrorCode::SourceChanged | ErrorCode::MissingVolume)
1042 )
1043 }) {
1044 self.list_id = None;
1045 self.selected.clear();
1046 }
1047 if self.confirmed && run.cancel_sequence.is_none() {
1048 self.volume_problem = run.volume_problem.take();
1049 }
1050 self.retry_start = if !matches!(run.start, Start::Preview { .. })
1051 && !run.expanded
1052 && run.cancel_sequence.is_none()
1053 && self.confirmed
1054 && self.terminal.as_ref().is_some_and(|t| {
1055 t.outcome == Outcome::Failed
1056 && t.error == Some(ErrorCode::Limit)
1057 && t.publication == Publication::None
1058 && t.created_count == 0
1059 && t.retained_partial_count == 0
1060 && t.cleanup == Cleanup::Complete
1061 })
1062 && self.outputs.iter().all(|(_, d)| *d == Disposition::Removed)
1063 {
1064 Some(run.start.clone())
1065 } else {
1066 None
1067 };
1068 self.challenge = None;
1069 self.resource = None;
1070 self.conflict = None;
1071 self.input_error = None;
1072 if matches!(self.close, Close::Waiting | Close::Confirm) {
1073 self.close = Close::Review;
1074 }
1075 }
1076 }
1077 fn receive(&mut self, host: HostEvent) {
1078 let run = self.running.as_mut().unwrap();
1079 match host {
1080 HostEvent::Fault(message) => {
1081 crate::log_error!("작업자 통신 오류: {message}");
1082 self.error = Some(message)
1083 }
1084 HostEvent::CleanupComplete => {
1085 crate::log_trace!("작업 {} 통신 정리 완료", run.id);
1086 run.transport_closed = true
1087 }
1088 HostEvent::StdoutEof => {
1089 crate::log_trace!("작업 {} 표준 출력 끝", run.id);
1090 run.stdout_eof = true
1091 }
1092 HostEvent::StderrEof => {
1093 crate::log_trace!("작업 {} 표준 오류 끝", run.id);
1094 run.stderr_eof = true
1095 }
1096 HostEvent::Exited { success } => {
1097 if success {
1098 crate::log_debug!("작업 {} 작업자 종료 (성공)", run.id);
1099 } else {
1100 crate::log_warn!("작업 {} 작업자 종료 (실패)", run.id);
1101 }
1102 run.exit = Some(success)
1103 }
1104 HostEvent::Frame {
1105 job_id,
1106 sequence,
1107 event,
1108 } => {
1109 if crate::applog::enabled(crate::applog::Level::Trace) {
1110 match &event {
1111 Event::PreviewChunk { offset, data, .. } => crate::log_trace!(
1112 "작업 {job_id} #{sequence} 미리보기 조각 offset={offset} len={}",
1113 data.len()
1114 ),
1115 event => crate::log_trace!(
1116 "작업 {job_id} #{sequence} 수신: {}",
1117 crate::applog::brief(event, 400)
1118 ),
1119 }
1120 }
1121 if job_id != run.id
1122 || sequence != run.incoming
1123 || self.terminal.is_some()
1124 || run.stdout_eof
1125 || sequence >= 1_000_000
1126 {
1127 self.error = Some("작업자 응답 순서나 작업 ID가 일치하지 않습니다".into());
1128 return;
1129 }
1130 run.incoming += 1;
1131 if !run.accepted && !matches!(event, Event::Accepted { .. }) {
1132 self.error = Some("작업 승인 응답이 없습니다".into());
1133 return;
1134 }
1135 match event {
1136 Event::RecoveryEntry(entry) => {
1137 let budget = if run.granted.any() {
1138 64 * 1024 * 1024
1139 } else {
1140 8 * 1024 * 1024
1141 };
1142 let used = run.recovery_metadata;
1143 if !matches!(run.start, Start::RecoverZip { .. })
1144 || self.recovery_end.is_some()
1145 || !entry.valid()
1146 || entry.candidate_id as usize != self.recovery_entries.len()
1147 || entry.name.as_ref().is_some_and(|n| {
1148 n.len() > 4096 || !valid_relative(n.trim_end_matches('/'))
1149 })
1150 || self
1151 .recovery_entries
1152 .last()
1153 .is_some_and(|e| e.source_offset >= entry.source_offset)
1154 || self.recovery_entries.len()
1155 >= if run.granted.entries { 200_000 } else { 10_000 }
1156 || used + 128 + entry.name.as_ref().map_or(0, String::len) > budget
1157 {
1158 self.error = Some("복구 항목 응답이 유효하지 않습니다".into());
1159 } else {
1160 run.recovery_metadata +=
1161 128 + entry.name.as_ref().map_or(0, String::len);
1162 self.recovery_entries.push(entry);
1163 }
1164 }
1165 Event::RecoveryEnd(summary) => {
1166 let count = |status| {
1167 self.recovery_entries
1168 .iter()
1169 .filter(|e| e.status == status)
1170 .count() as u32
1171 };
1172 if !matches!(run.start, Start::RecoverZip { .. })
1173 || self.recovery_end.is_some()
1174 || !summary.valid()
1175 || summary.source_bytes > 4 * 1024 * 1024 * 1024
1176 || self
1177 .recovery_entries
1178 .iter()
1179 .any(|e| e.source_offset >= summary.source_bytes)
1180 || summary.verified_entries != count(RecoveryStatus::Verified)
1181 || summary.lost_entries != count(RecoveryStatus::Lost)
1182 || summary.unverified_entries != count(RecoveryStatus::Unverified)
1183 {
1184 self.error = Some("복구 요약이 항목과 일치하지 않습니다".into());
1185 } else {
1186 self.recovery_end = Some(summary);
1187 }
1188 }
1189 Event::VolumeProblem(problem) => {
1190 if run.cancel_sequence.is_some() {
1191 return;
1192 }
1193 if run.volume_problem.is_some()
1194 || !matches!(run.start, Start::List { .. } | Start::Extract { .. })
1195 || !problem.volume.is_basename()
1196 {
1197 self.error = Some("분할 조각 오류 응답이 유효하지 않습니다".into());
1198 } else {
1199 run.volume_problem = Some(problem);
1200 }
1201 }
1202 Event::PreviewBegin(info) => {
1203 if run.preview_discarded {
1204 return;
1205 }
1206 if !matches!(run.start, Start::Preview { entry_id, .. } if entry_id == info.entry_id)
1207 || run.preview.is_some()
1208 || !info.valid()
1209 || self.error.is_some()
1210 {
1211 self.error = Some("미리보기 메타정보가 유효하지 않습니다".into());
1212 } else {
1213 let mut data = Vec::new();
1214 if data.try_reserve_exact(info.total_bytes as usize).is_err() {
1215 self.error = Some("미리보기 메모리를 확보하지 못했습니다".into());
1216 } else {
1217 run.preview = Some(PreviewBuffer {
1218 info,
1219 data,
1220 ended: false,
1221 });
1222 }
1223 }
1224 }
1225 Event::PreviewChunk {
1226 entry_id,
1227 offset,
1228 data,
1229 } => {
1230 if run.preview_discarded {
1231 return;
1232 }
1233 if self.error.is_some()
1234 || !run
1235 .preview
1236 .as_mut()
1237 .is_some_and(|b| b.chunk(entry_id, offset, data))
1238 {
1239 run.preview = None;
1240 self.error =
1241 Some("미리보기 데이터 순서나 크기가 일치하지 않습니다".into());
1242 }
1243 }
1244 Event::PreviewEnd {
1245 entry_id,
1246 total_bytes,
1247 sha256,
1248 } => {
1249 if run.preview_discarded {
1250 return;
1251 }
1252 if !run
1253 .preview
1254 .as_mut()
1255 .is_some_and(|b| b.end(entry_id, total_bytes, sha256))
1256 {
1257 run.preview = None;
1258 self.error = Some("미리보기 내용 검증에 실패했습니다".into());
1259 }
1260 }
1261 Event::Accepted { encryption } => {
1262 if matches!(
1263 run.start,
1264 Start::CreateSevenZip { .. } | Start::RecoverZip { .. }
1265 ) && encryption
1266 {
1267 self.error = Some("7z 생성의 암호 응답이 유효하지 않습니다".into());
1268 }
1269 if run.accepted {
1270 self.error = Some("작업 승인 중복".into());
1271 }
1272 run.accepted = true;
1273 self.encryption = encryption;
1274 }
1275 Event::Entry(entry) => {
1276 if !matches!(run.start, Start::List { .. })
1277 || run.list_end.is_some()
1278 || entry.id as usize != run.entries.len()
1279 || entry.name.len() > 4096
1280 || run.entries.len()
1281 >= if run.granted.entries {
1282 200_000
1283 } else {
1284 100_000
1285 }
1286 {
1287 self.error = Some("목록 응답이 유효하지 않습니다".into());
1288 } else {
1289 run.entries.push(entry);
1290 }
1291 }
1292 Event::ListEnd {
1293 entry_count,
1294 list_id,
1295 } => {
1296 if !matches!(run.start, Start::List { .. })
1297 || run.list_end.is_some()
1298 || !list_id.valid()
1299 {
1300 self.error = Some("목록 완료 응답이 유효하지 않습니다".into());
1301 } else {
1302 run.list_end = Some((entry_count, list_id));
1303 }
1304 }
1305 Event::PasswordRequired {
1306 challenge_id,
1307 attempt,
1308 encrypt,
1309 } => {
1310 if run.cancel_sequence.is_some() {
1311 return;
1312 }
1313 if matches!(
1314 run.start,
1315 Start::CreateSevenZip { .. } | Start::RecoverZip { .. }
1316 ) || self.challenge.is_some()
1317 || self.resource.is_some()
1318 || challenge_id <= run.last_challenge
1319 || self.conflict.is_some()
1320 {
1321 self.error = Some("암호 요청이 유효하지 않습니다".into());
1322 } else {
1323 run.last_challenge = challenge_id;
1324 self.challenge = Some((challenge_id, attempt, encrypt));
1325 }
1326 }
1327 Event::ResourceRequired(question) => {
1328 if run.cancel_sequence.is_some() {
1329 return;
1330 }
1331 let expected = match run.start {
1332 Start::List { .. } => ActionKind::List,
1333 Start::Extract { .. } => ActionKind::Extract,
1334 Start::CreateZip { .. } => ActionKind::CreateZip,
1335 Start::CreateSevenZip { .. } => ActionKind::CreateSevenZip,
1336 Start::Preview { .. } => ActionKind::Preview,
1337 Start::RecoverZip { .. } => ActionKind::RecoverZip,
1338 };
1339 let hard = Limits {
1340 input: u64::MAX,
1341 output: 64 * 1024 * 1024 * 1024,
1342 entries: 200_000,
1343 };
1344 let ceiling = if run.expanded {
1345 hard
1346 } else {
1347 Limits::default()
1348 };
1349 if self.challenge.is_some()
1350 || self.resource.is_some()
1351 || self.conflict.is_some()
1352 || question.id <= run.last_challenge
1353 || question.action != expected
1354 || !question.scope.any()
1355 || question.soft_limits != Limits::default()
1356 || question.ceiling != ceiling
1357 || (question.scope.output && (!run.expanded || run.granted.output))
1358 || (question.scope.entries && (!run.expanded || run.granted.entries))
1359 || (question.scope.ratio && run.granted.ratio)
1360 {
1361 self.error = Some("자원 승인 요청이 유효하지 않습니다".into());
1362 } else {
1363 run.last_challenge = question.id;
1364 self.resource = Some(question);
1365 }
1366 }
1367 Event::ConflictRequired(conflict) => {
1368 let valid_entry = self
1369 .entries
1370 .iter()
1371 .any(|entry| entry.id == conflict.entry_id && entry.kind == Kind::File);
1372 if !matches!(run.start, Start::Extract { .. })
1373 || !valid_entry
1374 || self.resource.is_some()
1375 || conflict.challenge_id <= run.last_challenge
1376 || self.challenge.is_some()
1377 || self.conflict.is_some()
1378 || run.conflict_ids.len()
1379 >= if run.granted.entries {
1380 200_000
1381 } else {
1382 100_000
1383 }
1384 || !valid_relative(&conflict.relative_name)
1385 || conflict.relative_name.len() > 4096
1386 || !run.conflict_ids.insert(conflict.challenge_id)
1387 {
1388 self.error = Some("파일 충돌 요청이 유효하지 않습니다".into());
1389 } else if run.cancel_sequence.is_none() {
1390 run.last_challenge = conflict.challenge_id;
1391 self.conflict = Some(conflict);
1392 }
1393 }
1394 Event::ConflictResolved(resolution) => {
1395 if !matches!(run.start, Start::Extract { .. })
1396 || !run.file_ids.contains(&resolution.entry_id)
1397 || self.resolutions.len()
1398 >= if run.granted.entries {
1399 200_000
1400 } else {
1401 100_000
1402 }
1403 || !valid_relative(&resolution.relative_name)
1404 || resolution.relative_name.len() > 4096
1405 || !run.resolved_ids.insert(resolution.entry_id)
1406 {
1407 self.error = Some("파일 충돌 결과가 유효하지 않습니다".into());
1408 } else {
1409 self.resolutions.push(resolution);
1410 }
1411 }
1412 Event::Progress {
1413 stage,
1414 processed,
1415 total,
1416 completed_entries,
1417 } => self.progress = Some((stage, processed, total, completed_entries)),
1418 Event::Output {
1419 relative_name,
1420 disposition,
1421 entry_id,
1422 } => {
1423 if let Start::RecoverZip { output_file, .. } = &run.start {
1424 let final_output = matches!(
1425 disposition,
1426 Disposition::Created | Disposition::CommitUncertain
1427 );
1428 let valid_output = if final_output {
1429 output_file.file_name().and_then(|n| n.to_str())
1430 == Some(relative_name.as_str())
1431 && !self.outputs.iter().any(|(_, d)| {
1432 matches!(
1433 d,
1434 Disposition::Created | Disposition::CommitUncertain
1435 )
1436 })
1437 } else {
1438 valid_leaf(&relative_name)
1439 && (disposition != Disposition::PartialRetained
1440 || output_file.file_name().and_then(|n| n.to_str())
1441 != Some(relative_name.as_str()))
1442 && !self.outputs.iter().any(|(name, d)| {
1443 name == &relative_name && *d == disposition
1444 })
1445 };
1446 if entry_id.is_some() || self.recovery_end.is_none() || !valid_output {
1447 self.error = Some("복구본 출력 응답이 유효하지 않습니다".into());
1448 return;
1449 }
1450 }
1451 if matches!(run.start, Start::Preview { .. }) {
1452 self.error = Some("미리보기 중 파일 출력이 보고됐습니다".into());
1453 return;
1454 }
1455 if self.outputs.len()
1456 < if run.granted.any() {
1457 // 암묵적 상위 폴더도 출력되므로 작업자 노드 예산과 맞춤
1458 262_144
1459 } else {
1460 100_000
1461 }
1462 && relative_name.len() <= 4096
1463 {
1464 self.outputs.push((relative_name, disposition));
1465 } else {
1466 self.error = Some("출력 보고 한도 초과".into());
1467 }
1468 }
1469 Event::CancelAck {
1470 request_sequence,
1471 status,
1472 } => {
1473 if run.cancel_sequence == Some(request_sequence) && self.cancel.is_none() {
1474 self.cancel = Some(status);
1475 } else {
1476 self.error = Some("취소 응답이 요청과 일치하지 않습니다".into());
1477 }
1478 }
1479 Event::Terminal(t) => {
1480 if matches!(run.start, Start::RecoverZip { .. }) {
1481 let business = t.outcome == Outcome::Completed
1482 || matches!(
1483 t.error,
1484 Some(
1485 ErrorCode::RecoveryIncomplete
1486 | ErrorCode::RecoveryImpossible
1487 )
1488 );
1489 if business
1490 && !self.recovery_end.as_ref().is_some_and(|s| {
1491 if s.verified_entries == 0 {
1492 t.outcome == Outcome::Failed
1493 && t.error == Some(ErrorCode::RecoveryImpossible)
1494 && t.publication == Publication::None
1495 && t.created_count == 0
1496 && self.outputs.is_empty()
1497 } else {
1498 t.publication == Publication::Complete
1499 && t.created_count == 1
1500 && self.outputs.len() == 1
1501 && self.outputs[0].1 == Disposition::Created
1502 && if s.complete() {
1503 t.outcome == Outcome::Completed && t.error.is_none()
1504 } else {
1505 t.outcome == Outcome::Failed
1506 && t.error
1507 == Some(ErrorCode::RecoveryIncomplete)
1508 }
1509 }
1510 })
1511 {
1512 self.error =
1513 Some("복구 결과와 저장 상태가 일치하지 않습니다".into());
1514 }
1515 }
1516 if run.cancel_sequence.is_none()
1517 && run.volume_problem.as_ref().is_some_and(|problem| {
1518 t.outcome != Outcome::Failed
1519 || t.error
1520 != match problem.reason {
1521 VolumeProblemReason::FirstVolumeRequired => {
1522 Some(ErrorCode::InvalidRequest)
1523 }
1524 VolumeProblemReason::MissingVolume => {
1525 Some(ErrorCode::MissingVolume)
1526 }
1527 VolumeProblemReason::IncompleteSet => {
1528 Some(ErrorCode::Integrity)
1529 }
1530 }
1531 })
1532 {
1533 self.error =
1534 Some("분할 조각 오류와 종료 상태가 일치하지 않습니다".into());
1535 }
1536 if matches!(run.start, Start::Preview { .. })
1537 && (t.publication != Publication::None
1538 || t.created_count != 0
1539 || t.retained_partial_count != 0
1540 || t.durability != Durability::NotApplicable)
1541 {
1542 self.error = Some("미리보기 종료 상태가 유효하지 않습니다".into());
1543 }
1544 if t.outcome != Outcome::Completed {
1545 run.preview = None;
1546 }
1547 self.challenge = None;
1548 self.conflict = None;
1549 self.terminal = Some(t);
1550 }
1551 }
1552 }
1553 }
1554 }
1555 pub fn status(&self) -> String {
1556 if let Some(error) = self.error.as_ref().or(self.input_error.as_ref()) {
1557 return error.clone();
1558 }
1559 if self.busy() {
1560 if self.terminal.is_some() {
1561 return "작업 결과 수신 / 프로세스 종료 확인 중".into();
1562 }
1563 if self.resource.is_some() {
1564 return "사용자 허용 대기".into();
1565 }
1566 if self.conflict.is_some() {
1567 return "같은 이름의 파일을 처리할 방법을 선택하세요".into();
1568 }
1569 if self.challenge.is_some() {
1570 return "암호를 입력하세요".into();
1571 }
1572 if let Some(c) = self.cancel {
1573 return match c {
1574 CancelStatus::Requested | CancelStatus::AlreadyRequested => {
1575 "취소 요청 접수 / 최종 결과 대기"
1576 }
1577 CancelStatus::TooLate => "취소할 수 없는 단계 / 최종 결과 대기",
1578 CancelStatus::Finished => "처리 종료 응답 / 프로세스 종료 확인 중",
1579 }
1580 .into();
1581 }
1582 if self
1583 .running
1584 .as_ref()
1585 .is_some_and(|r| r.cancel_sequence.is_some())
1586 {
1587 return "취소 요청 전송 / 최종 결과 대기".into();
1588 }
1589 return "작업 중".into();
1590 }
1591 match self
1592 .terminal
1593 .as_ref()
1594 .filter(|_| self.confirmed)
1595 .map(|t| t.outcome)
1596 {
1597 Some(Outcome::Completed) => "작업 완료",
1598 Some(Outcome::Cancelled) => "작업 취소됨",
1599 Some(Outcome::Failed) => "작업 실패",
1600 None => "압축파일을 열거나 ZIP 파일을 만드세요",
1601 }
1602 .into()
1603 }
1604}
1605pub fn valid_leaf(name: &str) -> bool {
1606 valid_relative(name) && !name.contains('/') && !name.contains('\\')
1607}
1608pub fn valid_relative(name: &str) -> bool {
1609 !name.is_empty()
1610 && !name.contains('\0')
1611 && !name.contains(':')
1612 && !name.starts_with('/')
1613 && !name.starts_with('\\')
1614 && name
1615 .split(['/', '\\'])
1616 .all(|p| !p.is_empty() && p != "." && p != "..")
1617}
1618
1619// 파일 연결로 전달된 원형 경로를 손실 변환 없이 보존함.
1620pub fn launch_args(
1621 args: Vec<std::ffi::OsString>,
1622 cwd: PathBuf,
1623) -> Result<(bool, Option<PathBuf>), &'static str> {
1624 let fixture = args.iter().any(|arg| arg == "--ui-fixture");
1625 let paths = args
1626 .into_iter()
1627 .filter(|arg| arg != "--ui-fixture")
1628 .collect::<Vec<_>>();
1629 if paths.len() > 1 {
1630 return Err("압축파일 하나를 지정하세요");
1631 }
1632 let path = paths
1633 .into_iter()
1634 .next()
1635 .map(PathBuf::from)
1636 .map(|p| if p.is_absolute() { p } else { cwd.join(p) });
1637 Ok((fixture, path))
1638}
1639
1640pub fn stage_label(stage: Stage) -> &'static str {
1641 match stage {
1642 Stage::Scan => "목록 읽는 중",
1643 Stage::Read => "파일 읽는 중",
1644 Stage::Decode => "압축 푸는 중",
1645 Stage::Write => "파일 쓰는 중",
1646 Stage::Verify => "검증 중",
1647 Stage::Commit => "저장 마무리 중",
1648 }
1649}
1650pub fn disposition_label(disposition: Disposition) -> &'static str {
1651 match disposition {
1652 Disposition::Created => "생성됨",
1653 Disposition::PartialRetained => "일부 파일 남음",
1654 Disposition::Removed => "작업 임시 파일 정리됨",
1655 Disposition::CommitUncertain => "저장 여부 불확실",
1656 }
1657}
1658pub fn terminal_lines(t: &Terminal) -> Vec<String> {
1659 let publication = match t.publication {
1660 Publication::None => "게시된 파일 없음",
1661 Publication::Partial => "일부 파일 게시됨",
1662 Publication::Complete => "파일 게시 완료",
1663 Publication::Uncertain => "파일 게시 여부 불확실 / 출력 폴더를 확인하세요",
1664 };
1665 let durability = match t.durability {
1666 Durability::NotApplicable => "동기화 해당 없음",
1667 Durability::Synced => "디스크 동기화 완료",
1668 Durability::Unconfirmed => "디스크 동기화 미확인",
1669 Durability::Failed => "디스크 동기화 실패",
1670 };
1671 let cleanup = match t.cleanup {
1672 Cleanup::Complete => "작업 임시 파일 정리 완료",
1673 Cleanup::Failed => "작업 임시 파일 정리 실패",
1674 Cleanup::Unconfirmed => "작업 임시 파일 정리 미확인",
1675 };
1676 let mut lines = vec![
1677 publication.into(),
1678 format!(
1679 "생성 {}개 / 남은 임시 파일 {}개",
1680 t.created_count, t.retained_partial_count
1681 ),
1682 format!("{durability} / {cleanup}"),
1683 ];
1684 if let Some(error) = t.error {
1685 lines.push(
1686 match error {
1687 ErrorCode::RecoveryIncomplete => "일부 항목만 복구했습니다",
1688 ErrorCode::RecoveryImpossible => "복구 가능한 항목이 없습니다",
1689 ErrorCode::MissingVolume => "분할 압축파일의 조각이 없습니다. 모든 조각을 같은 폴더에 모은 뒤 첫 조각을 다시 여세요",
1690 ErrorCode::Integrity => "압축파일이 손상됐습니다",
1691 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
1692 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
1693 ErrorCode::WrongPassword => "암호가 올바르지 않습니다",
1694 ErrorCode::UnsafePath => "안전하지 않은 경로가 있어 중단했습니다",
1695 ErrorCode::Conflict => "같은 이름의 파일이 있습니다. 다른 출력 폴더를 선택하세요",
1696 ErrorCode::Limit => "처리 한도를 초과했습니다",
1697 ErrorCode::Io => {
1698 "파일을 읽거나 쓰지 못했습니다. 파일과 폴더의 접근 권한을 확인하세요"
1699 }
1700 ErrorCode::DiskFull => {
1701 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
1702 }
1703 ErrorCode::Protocol => "작업자 응답이 올바르지 않습니다",
1704 ErrorCode::Internal => "작업자 처리 오류입니다",
1705 ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
1706 ErrorCode::InvalidRequest => "입력과 선택한 항목을 확인하세요",
1707 }
1708 .into(),
1709 );
1710 }
1711 lines
1712}