team-ljyzipelo

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