team-ljyzipelo

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