team-ljyzipelo

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