team-ljyzipelo

공개
806줄25 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}
10#[derive(Clone, Debug, Eq, PartialEq)]
11pub enum SourceObject {
12 Unix { device: u64, inode: u64 },
13 Windows { volume: u64, file_id: [u8; 16] },
14}
15#[derive(Clone, Debug, Eq, PartialEq)]
16pub struct ListId {
17 pub catalog_version: u16,
18 pub format: Format,
19 pub source_object: SourceObject,
20 pub archive_bytes: u64,
21 pub archive_sha256: [u8; 32],
22}
23#[derive(Clone, Debug, Eq, PartialEq)]
24pub enum Selection {
25 All,
26 EntryIds(Vec<u32>),
27}
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub enum Method {
30 Store,
31 Deflate,
32}
33#[derive(Clone, Debug, Eq, PartialEq)]
34pub enum Start {
35 List {
36 archive: PathBuf,
37 },
38 Extract {
39 archive: PathBuf,
40 destination: PathBuf,
41 selection: Selection,
42 list_id: ListId,
43 gzip_output_name: Option<String>,
44 },
45 CreateZip {
46 sources: Vec<(PathBuf, String)>,
47 output_file: PathBuf,
48 method: Method,
49 aes256: bool,
50 },
51}
52// 암호를 Debug와 로그에서 제외하고 소유 버퍼를 해제 전에 지움.
53pub struct Secret(Vec<u8>);
54impl Secret {
55 pub fn new(text: String) -> Result<Self, &'static str> {
56 if text.is_empty() || text.len() > 1024 {
57 return Err("암호는 UTF-8 1~1024바이트로 입력하세요");
58 }
59 Ok(Self(text.into_bytes()))
60 }
61 pub fn as_bytes(&self) -> &[u8] {
62 &self.0
63 }
64}
65impl Drop for Secret {
66 fn drop(&mut self) {
67 self.0.fill(0);
68 }
69}
70pub enum Command {
71 Start(Start),
72 Password { challenge_id: u64, secret: Secret },
73 Cancel,
74}
75pub struct Request {
76 pub job_id: u64,
77 pub sequence: u64,
78 pub command: Command,
79}
80#[derive(Clone, Copy, Debug, Eq, PartialEq)]
81pub enum Kind {
82 File,
83 Directory,
84 Link,
85 Other,
86}
87#[derive(Clone, Debug, Eq, PartialEq)]
88pub struct Entry {
89 pub id: u32,
90 pub name: String,
91 pub kind: Kind,
92 pub bytes: Option<u64>,
93 pub packed: Option<u64>,
94 pub encrypted: bool,
95}
96#[derive(Clone, Copy, Debug, Eq, PartialEq)]
97pub enum CancelStatus {
98 Requested,
99 AlreadyRequested,
100 TooLate,
101 Finished,
102}
103#[derive(Clone, Copy, Debug, Eq, PartialEq)]
104pub enum Stage {
105 Scan,
106 Read,
107 Decode,
108 Write,
109 Verify,
110 Commit,
111}
112#[derive(Clone, Copy, Debug, Eq, PartialEq)]
113pub enum Outcome {
114 Completed,
115 Failed,
116 Cancelled,
117}
118#[derive(Clone, Copy, Debug, Eq, PartialEq)]
119pub enum ErrorCode {
120 Integrity,
121 UnsupportedFormat,
122 UnsupportedFeature,
123 WrongPassword,
124 UnsafePath,
125 Conflict,
126 Limit,
127 Io,
128 Protocol,
129 Internal,
130 SourceChanged,
131 InvalidRequest,
132}
133#[derive(Clone, Copy, Debug, Eq, PartialEq)]
134pub enum Publication {
135 None,
136 Partial,
137 Complete,
138 Uncertain,
139}
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
141pub enum Durability {
142 NotApplicable,
143 Synced,
144 Unconfirmed,
145 Failed,
146}
147#[derive(Clone, Copy, Debug, Eq, PartialEq)]
148pub enum Cleanup {
149 Complete,
150 Failed,
151 Unconfirmed,
152}
153#[derive(Clone, Copy, Debug, Eq, PartialEq)]
154pub enum Disposition {
155 Created,
156 PartialRetained,
157 Removed,
158 CommitUncertain,
159}
160#[derive(Clone, Debug)]
161pub struct Terminal {
162 pub outcome: Outcome,
163 pub error: Option<ErrorCode>,
164 pub publication: Publication,
165 pub created_count: u64,
166 pub retained_partial_count: u64,
167 pub durability: Durability,
168 pub cleanup: Cleanup,
169}
170#[derive(Clone, Debug)]
171pub enum Event {
172 Accepted {
173 encryption: bool,
174 },
175 Entry(Entry),
176 ListEnd {
177 entry_count: u32,
178 list_id: ListId,
179 },
180 PasswordRequired {
181 challenge_id: u64,
182 attempt: u32,
183 encrypt: bool,
184 },
185 Progress {
186 stage: Stage,
187 processed: u64,
188 total: Option<u64>,
189 completed_entries: u64,
190 },
191 Output {
192 entry_id: Option<u32>,
193 relative_name: String,
194 disposition: Disposition,
195 },
196 CancelAck {
197 request_sequence: u64,
198 status: CancelStatus,
199 },
200 Terminal(Terminal),
201}
202pub enum HostEvent {
203 Frame {
204 job_id: u64,
205 sequence: u64,
206 event: Event,
207 },
208 StdoutEof,
209 StderrEof,
210 Exited {
211 success: bool,
212 },
213}
214// 바이트 codec과 프로세스 소유는 작업자 어댑터에서 담당함.
215// 전송 실패 후에도 poll로 양쪽 EOF와 자식 회수 결과를 전달함.
216pub trait Connection {
217 fn send(&mut self, request: Request) -> Result<(), String>;
218 fn poll(&mut self) -> Option<HostEvent>;
219}
220pub trait Factory {
221 fn connect(&mut self, job_id: u64) -> Result<Box<dyn Connection>, String>;
222}
223pub struct Unavailable;
224impl Factory for Unavailable {
225 fn connect(&mut self, _: u64) -> Result<Box<dyn Connection>, String> {
226 Err("작업자 연결이 아직 준비되지 않았습니다".into())
227 }
228}
229struct Running {
230 id: u64,
231 outgoing: u64,
232 incoming: u64,
233 accepted: bool,
234 start_failed: bool,
235 start: Start,
236 connection: Box<dyn Connection>,
237 entries: Vec<Entry>,
238 list_end: Option<(u32, ListId)>,
239 stdout_eof: bool,
240 stderr_eof: bool,
241 exit: Option<bool>,
242 cancel_sequence: Option<u64>,
243}
244#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
245pub enum Close {
246 #[default]
247 Open,
248 Confirm,
249 Waiting,
250 Review,
251 Allowed,
252}
253#[derive(Default)]
254pub struct Model {
255 running: Option<Running>,
256 next_id: u64,
257 pub archive: Option<PathBuf>,
258 pub entries: Vec<Entry>,
259 pub list_id: Option<ListId>,
260 pub selected: BTreeSet<u32>,
261 pub terminal: Option<Terminal>,
262 pub challenge: Option<(u64, u32, bool)>,
263 pub progress: Option<(Stage, u64, Option<u64>, u64)>,
264 pub outputs: Vec<(String, Disposition)>,
265 pub cancel: Option<CancelStatus>,
266 pub error: Option<String>,
267 pub encryption: bool,
268 pub close: Close,
269 pub confirmed: bool,
270}
271impl Model {
272 pub fn busy(&self) -> bool {
273 self.running.is_some()
274 }
275 pub fn job_id(&self) -> Option<u64> {
276 self.running.as_ref().map(|r| r.id)
277 }
278 pub fn can_extract(&self) -> bool {
279 !self.busy()
280 && self.list_id.is_some()
281 && self.archive.is_some()
282 && self.close == Close::Open
283 }
284 pub fn begin(&mut self, start: Start, factory: &mut dyn Factory) -> bool {
285 if self.busy() || self.close != Close::Open {
286 return false;
287 }
288 let validation = match &start {
289 Start::List { archive } => archive.is_absolute(),
290 Start::Extract {
291 archive,
292 destination,
293 selection,
294 gzip_output_name,
295 list_id,
296 } => {
297 archive.is_absolute()
298 && destination.is_absolute()
299 && self.archive.as_ref() == Some(archive)
300 && self.list_id.as_ref() == Some(list_id)
301 && match list_id.format {
302 Format::Gzip => gzip_output_name.as_ref().is_some_and(|s| valid_leaf(s)),
303 _ => gzip_output_name.is_none(),
304 }
305 && match selection {
306 Selection::All => true,
307 Selection::EntryIds(ids) => {
308 !ids.is_empty()
309 && ids.iter().collect::<BTreeSet<_>>().len() == ids.len()
310 && ids.iter().all(|id| {
311 self.entries.iter().any(|e| {
312 e.id == *id
313 && matches!(e.kind, Kind::File | Kind::Directory)
314 })
315 })
316 }
317 }
318 }
319 Start::CreateZip {
320 sources,
321 output_file,
322 aes256,
323 ..
324 } => {
325 !sources.is_empty()
326 && output_file.is_absolute()
327 && (!aes256 || self.encryption)
328 && sources
329 .iter()
330 .all(|(p, n)| p.is_absolute() && valid_relative(n))
331 }
332 };
333 if !validation {
334 self.error = Some("입력 경로, 출력명과 선택한 목록을 확인하세요".into());
335 return false;
336 }
337 let Some(id) = self.next_id.checked_add(1) else {
338 self.error = Some("작업 ID 한도에 도달했습니다".into());
339 return false;
340 };
341 let mut connection = match factory.connect(id) {
342 Ok(c) => c,
343 Err(e) => {
344 self.error = Some(e);
345 return false;
346 }
347 };
348 let send_error = connection
349 .send(Request {
350 job_id: id,
351 sequence: 0,
352 command: Command::Start(start.clone()),
353 })
354 .err();
355 let started = send_error.is_none();
356 if let Start::List { archive } = &start
357 && started
358 {
359 self.archive = Some(archive.clone());
360 self.list_id = None;
361 self.entries.clear();
362 self.selected.clear();
363 }
364 self.next_id = id;
365 self.terminal = None;
366 self.challenge = None;
367 self.progress = None;
368 self.outputs.clear();
369 self.cancel = None;
370 self.error = send_error;
371 self.confirmed = false;
372 self.running = Some(Running {
373 id,
374 outgoing: 1,
375 incoming: 0,
376 accepted: false,
377 start_failed: !started,
378 start,
379 connection,
380 entries: Vec::new(),
381 list_end: None,
382 stdout_eof: false,
383 stderr_eof: false,
384 exit: None,
385 cancel_sequence: None,
386 });
387 started
388 }
389 pub fn extract(
390 &mut self,
391 destination: PathBuf,
392 selected_only: bool,
393 gzip_output_name: Option<String>,
394 factory: &mut dyn Factory,
395 ) -> bool {
396 if !self.can_extract() {
397 return false;
398 }
399 self.begin(
400 Start::Extract {
401 archive: self.archive.clone().unwrap(),
402 destination,
403 selection: if selected_only {
404 Selection::EntryIds(self.selected.iter().copied().collect())
405 } else {
406 Selection::All
407 },
408 list_id: self.list_id.clone().unwrap(),
409 gzip_output_name,
410 },
411 factory,
412 )
413 }
414 pub fn password(&mut self, text: String) -> bool {
415 let Some((challenge_id, _, _)) = self.challenge else {
416 return false;
417 };
418 let secret = match Secret::new(text) {
419 Ok(s) => s,
420 Err(e) => {
421 self.error = Some(e.into());
422 return false;
423 }
424 };
425 if self
426 .send(Command::Password {
427 challenge_id,
428 secret,
429 })
430 .is_some()
431 {
432 self.challenge = None;
433 self.error = None;
434 true
435 } else {
436 false
437 }
438 }
439 fn send(&mut self, command: Command) -> Option<u64> {
440 let run = self.running.as_mut()?;
441 if run.start_failed || self.terminal.is_some() || run.exit.is_some() {
442 return None;
443 }
444 let seq = run.outgoing;
445 let Some(next) = seq.checked_add(1) else {
446 self.error = Some("요청 순서 한도 초과".into());
447 return None;
448 };
449 match run.connection.send(Request {
450 job_id: run.id,
451 sequence: seq,
452 command,
453 }) {
454 Ok(()) => {
455 run.outgoing = next;
456 Some(seq)
457 }
458 Err(e) => {
459 self.error = Some(e);
460 None
461 }
462 }
463 }
464 pub fn cancel(&mut self) {
465 if self
466 .running
467 .as_ref()
468 .is_some_and(|r| r.cancel_sequence.is_none())
469 {
470 if let Some(seq) = self.send(Command::Cancel) {
471 self.running.as_mut().unwrap().cancel_sequence = Some(seq);
472 self.challenge = None;
473 }
474 }
475 }
476 pub fn request_close(&mut self) {
477 if self.close == Close::Open {
478 self.close = if self.busy() {
479 Close::Confirm
480 } else {
481 Close::Review
482 };
483 }
484 }
485 pub fn confirm_close(&mut self) {
486 if self.close == Close::Confirm {
487 self.cancel();
488 self.close = if self.busy() {
489 Close::Waiting
490 } else {
491 Close::Review
492 };
493 }
494 }
495 pub fn keep_open(&mut self) {
496 if self.close != Close::Allowed {
497 self.close = Close::Open;
498 }
499 }
500 pub fn acknowledge_close(&mut self) {
501 if !self.busy() && self.close == Close::Review {
502 self.close = Close::Allowed;
503 }
504 }
505 pub fn poll(&mut self) {
506 for _ in 0..128 {
507 let Some(event) = self.running.as_mut().and_then(|r| r.connection.poll()) else {
508 break;
509 };
510 self.receive(event);
511 }
512 let complete = self
513 .running
514 .as_ref()
515 .is_some_and(|r| r.stdout_eof && r.stderr_eof && r.exit.is_some());
516 if complete {
517 let run = self.running.take().unwrap();
518 self.confirmed =
519 self.terminal.is_some() && run.exit == Some(true) && self.error.is_none();
520 if !self.confirmed {
521 self.error.get_or_insert(
522 "작업자 종료 결과를 확인할 수 없습니다. 출력 상태를 확인하세요".into(),
523 );
524 }
525 if self.confirmed
526 && self
527 .terminal
528 .as_ref()
529 .is_some_and(|t| t.outcome == Outcome::Completed)
530 {
531 if matches!(run.start, Start::List { .. }) {
532 if let Some((count, id)) = run
533 .list_end
534 .filter(|(n, _)| *n as usize == run.entries.len())
535 {
536 let _ = count;
537 self.entries = run.entries;
538 self.list_id = Some(id);
539 } else {
540 self.error = Some("목록 완료 정보가 일치하지 않습니다. 다시 여세요".into());
541 self.confirmed = false;
542 }
543 }
544 }
545 if self
546 .terminal
547 .as_ref()
548 .is_some_and(|t| t.error == Some(ErrorCode::SourceChanged))
549 {
550 self.list_id = None;
551 self.selected.clear();
552 }
553 self.challenge = None;
554 if matches!(self.close, Close::Waiting | Close::Confirm) {
555 self.close = Close::Review;
556 }
557 }
558 }
559 fn receive(&mut self, host: HostEvent) {
560 let run = self.running.as_mut().unwrap();
561 match host {
562 HostEvent::StdoutEof => run.stdout_eof = true,
563 HostEvent::StderrEof => run.stderr_eof = true,
564 HostEvent::Exited { success } => run.exit = Some(success),
565 HostEvent::Frame {
566 job_id,
567 sequence,
568 event,
569 } => {
570 if job_id != run.id
571 || sequence != run.incoming
572 || self.terminal.is_some()
573 || run.stdout_eof
574 || sequence >= 1_000_000
575 {
576 self.error = Some("작업자 응답 순서나 작업 ID가 일치하지 않습니다".into());
577 return;
578 }
579 run.incoming += 1;
580 if !run.accepted && !matches!(event, Event::Accepted { .. }) {
581 self.error = Some("작업 승인 응답이 없습니다".into());
582 return;
583 }
584 match event {
585 Event::Accepted { encryption } => {
586 if run.accepted {
587 self.error = Some("작업 승인 중복".into());
588 }
589 run.accepted = true;
590 self.encryption = encryption;
591 }
592 Event::Entry(entry) => {
593 if !matches!(run.start, Start::List { .. })
594 || run.list_end.is_some()
595 || entry.id as usize != run.entries.len()
596 || entry.name.len() > 4096
597 || run.entries.len() >= 100_000
598 {
599 self.error = Some("목록 응답이 유효하지 않습니다".into());
600 } else {
601 run.entries.push(entry);
602 }
603 }
604 Event::ListEnd {
605 entry_count,
606 list_id,
607 } => {
608 if !matches!(run.start, Start::List { .. })
609 || run.list_end.is_some()
610 || list_id.catalog_version != 1
611 {
612 self.error = Some("목록 완료 응답이 유효하지 않습니다".into());
613 } else {
614 run.list_end = Some((entry_count, list_id));
615 }
616 }
617 Event::PasswordRequired {
618 challenge_id,
619 attempt,
620 encrypt,
621 } => {
622 if self.challenge.is_some() || challenge_id == 0 {
623 self.error = Some("암호 요청이 유효하지 않습니다".into());
624 } else {
625 self.challenge = Some((challenge_id, attempt, encrypt));
626 }
627 }
628 Event::Progress {
629 stage,
630 processed,
631 total,
632 completed_entries,
633 } => self.progress = Some((stage, processed, total, completed_entries)),
634 Event::Output {
635 relative_name,
636 disposition,
637 ..
638 } => {
639 if self.outputs.len() < 100_000 && relative_name.len() <= 4096 {
640 self.outputs.push((relative_name, disposition));
641 } else {
642 self.error = Some("출력 보고 한도 초과".into());
643 }
644 }
645 Event::CancelAck {
646 request_sequence,
647 status,
648 } => {
649 if run.cancel_sequence == Some(request_sequence) && self.cancel.is_none() {
650 self.cancel = Some(status);
651 } else {
652 self.error = Some("취소 응답이 요청과 일치하지 않습니다".into());
653 }
654 }
655 Event::Terminal(t) => {
656 self.challenge = None;
657 self.terminal = Some(t);
658 }
659 }
660 }
661 }
662 }
663 pub fn status(&self) -> String {
664 if let Some(error) = &self.error {
665 return error.clone();
666 }
667 if self.busy() {
668 if self.terminal.is_some() {
669 return "작업 결과 수신 / 프로세스 종료 확인 중".into();
670 }
671 if self.challenge.is_some() {
672 return "암호를 입력하세요".into();
673 }
674 if let Some(c) = self.cancel {
675 return match c {
676 CancelStatus::Requested | CancelStatus::AlreadyRequested => {
677 "취소 요청 접수 / 최종 결과 대기"
678 }
679 CancelStatus::TooLate => "취소할 수 없는 단계 / 최종 결과 대기",
680 CancelStatus::Finished => "처리 종료 응답 / 프로세스 종료 확인 중",
681 }
682 .into();
683 }
684 if self
685 .running
686 .as_ref()
687 .is_some_and(|r| r.cancel_sequence.is_some())
688 {
689 return "취소 요청 전송 / 최종 결과 대기".into();
690 }
691 return "작업 중".into();
692 }
693 match self
694 .terminal
695 .as_ref()
696 .filter(|_| self.confirmed)
697 .map(|t| t.outcome)
698 {
699 Some(Outcome::Completed) => "작업 완료",
700 Some(Outcome::Cancelled) => "작업 취소됨",
701 Some(Outcome::Failed) => "작업 실패",
702 None => "압축파일을 열거나 ZIP 파일을 만드세요",
703 }
704 .into()
705 }
706}
707pub fn valid_leaf(name: &str) -> bool {
708 valid_relative(name) && !name.contains('/') && !name.contains('\\')
709}
710pub fn valid_relative(name: &str) -> bool {
711 !name.is_empty()
712 && !name.contains('\0')
713 && !name.contains(':')
714 && !name.starts_with('/')
715 && !name.starts_with('\\')
716 && name
717 .split(['/', '\\'])
718 .all(|p| !p.is_empty() && p != "." && p != "..")
719}
720
721// 파일 연결로 전달된 원형 경로를 손실 변환 없이 보존함.
722pub fn launch_args(
723 args: Vec<std::ffi::OsString>,
724 cwd: PathBuf,
725) -> Result<(bool, Option<PathBuf>), &'static str> {
726 let fixture = args.iter().any(|arg| arg == "--ui-fixture");
727 let paths = args
728 .into_iter()
729 .filter(|arg| arg != "--ui-fixture")
730 .collect::<Vec<_>>();
731 if paths.len() > 1 {
732 return Err("압축파일 하나를 지정하세요");
733 }
734 let path = paths
735 .into_iter()
736 .next()
737 .map(PathBuf::from)
738 .map(|p| if p.is_absolute() { p } else { cwd.join(p) });
739 Ok((fixture, path))
740}
741
742pub fn stage_label(stage: Stage) -> &'static str {
743 match stage {
744 Stage::Scan => "목록 읽는 중",
745 Stage::Read => "파일 읽는 중",
746 Stage::Decode => "압축 푸는 중",
747 Stage::Write => "파일 쓰는 중",
748 Stage::Verify => "검증 중",
749 Stage::Commit => "저장 마무리 중",
750 }
751}
752pub fn disposition_label(disposition: Disposition) -> &'static str {
753 match disposition {
754 Disposition::Created => "생성됨",
755 Disposition::PartialRetained => "일부 파일 남음",
756 Disposition::Removed => "작업 임시 파일 정리됨",
757 Disposition::CommitUncertain => "저장 여부 불확실",
758 }
759}
760pub fn terminal_lines(t: &Terminal) -> Vec<String> {
761 let publication = match t.publication {
762 Publication::None => "게시된 파일 없음",
763 Publication::Partial => "일부 파일 게시됨",
764 Publication::Complete => "파일 게시 완료",
765 Publication::Uncertain => "파일 게시 여부 불확실 / 출력 폴더를 확인하세요",
766 };
767 let durability = match t.durability {
768 Durability::NotApplicable => "동기화 해당 없음",
769 Durability::Synced => "디스크 동기화 완료",
770 Durability::Unconfirmed => "디스크 동기화 미확인",
771 Durability::Failed => "디스크 동기화 실패",
772 };
773 let cleanup = match t.cleanup {
774 Cleanup::Complete => "작업 임시 파일 정리 완료",
775 Cleanup::Failed => "작업 임시 파일 정리 실패",
776 Cleanup::Unconfirmed => "작업 임시 파일 정리 미확인",
777 };
778 let mut lines = vec![
779 publication.into(),
780 format!(
781 "생성 {}개 / 남은 임시 파일 {}개",
782 t.created_count, t.retained_partial_count
783 ),
784 format!("{durability} / {cleanup}"),
785 ];
786 if let Some(error) = t.error {
787 lines.push(
788 match error {
789 ErrorCode::Integrity => "압축파일이 손상됐습니다",
790 ErrorCode::UnsupportedFormat => "지원하지 않는 압축 형식입니다",
791 ErrorCode::UnsupportedFeature => "아직 지원하지 않는 기능입니다",
792 ErrorCode::WrongPassword => "암호가 올바르지 않습니다",
793 ErrorCode::UnsafePath => "안전하지 않은 경로가 있어 중단했습니다",
794 ErrorCode::Conflict => "같은 이름의 파일이 있습니다. 다른 출력 폴더를 선택하세요",
795 ErrorCode::Limit => "처리 한도를 초과했습니다",
796 ErrorCode::Io => "파일을 읽거나 쓰지 못했습니다",
797 ErrorCode::Protocol => "작업자 응답이 올바르지 않습니다",
798 ErrorCode::Internal => "작업자 처리 오류입니다",
799 ErrorCode::SourceChanged => "원본 파일이 바뀌었습니다. 압축파일을 다시 여세요",
800 ErrorCode::InvalidRequest => "입력과 선택한 항목을 확인하세요",
801 }
802 .into(),
803 );
804 }
805 lines
806}