team-ljyzipelo

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