team-ljyzipelo

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