team-ljyzipelo

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