team-ljyzipelo

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