team-ljyzipelo

공개
658줄17 KB
1use std::path::{Path, PathBuf};
2
3pub const MAX_PREVIEW_TEXT_BYTES: u64 = 1024 * 1024;
4pub const MAX_PREVIEW_IMAGE_BYTES: u64 = 8 * 1024 * 1024;
5pub const MAX_PREVIEW_RGBA_BYTES: u64 = 64 * 1024 * 1024;
6pub const MAX_PREVIEW_DIMENSION: u32 = 8192;
7pub const MAX_PREVIEW_PIXELS: u64 = 16_000_000;
8pub const MAX_PREVIEW_CHUNK_BYTES: usize = 32 * 1024;
9/// 7z 분할 볼륨 하나의 최소 크기 (1 MiB).
10pub const MIN_SEVEN_ZIP_VOLUME_BYTES: u64 = 1024 * 1024;
11/// 분할 7z 읽기가 받는 최대 볼륨 수 (`이름.7z.001`~`이름.7z.999`).
12pub const MAX_SEVEN_ZIP_VOLUMES: u64 = 999;
13
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub enum NativePath {
16 Unix(Vec<u8>),
17 Windows(Vec<u16>),
18}
19impl NativePath {
20 pub fn from_path(path: &Path) -> Self {
21 #[cfg(unix)]
22 {
23 use std::os::unix::ffi::OsStrExt;
24 Self::Unix(path.as_os_str().as_bytes().to_vec())
25 }
26 #[cfg(windows)]
27 {
28 use std::os::windows::ffi::OsStrExt;
29 Self::Windows(path.as_os_str().encode_wide().collect())
30 }
31 }
32 pub fn is_basename(&self) -> bool {
33 match self {
34 Self::Unix(bytes) => {
35 !bytes.is_empty()
36 && bytes != b"."
37 && bytes != b".."
38 && !bytes.iter().any(|byte| matches!(*byte, 0 | b'/' | b'\\'))
39 }
40 Self::Windows(units) => {
41 !units.is_empty()
42 && units != &[b'.' as u16]
43 && units != &[b'.' as u16, b'.' as u16]
44 && !units.iter().any(|unit| matches!(*unit, 0 | 47 | 92 | 58))
45 }
46 }
47 }
48 pub fn to_path(&self) -> Result<PathBuf, ErrorCode> {
49 #[cfg(unix)]
50 if let Self::Unix(bytes) = self {
51 use std::os::unix::ffi::OsStringExt;
52 if bytes.contains(&0) {
53 return Err(ErrorCode::InvalidRequest);
54 }
55 let path = PathBuf::from(std::ffi::OsString::from_vec(bytes.clone()));
56 return if path.is_absolute() {
57 Ok(path)
58 } else {
59 Err(ErrorCode::InvalidRequest)
60 };
61 }
62 #[cfg(windows)]
63 if let Self::Windows(units) = self {
64 use std::os::windows::ffi::OsStringExt;
65 if units.contains(&0) {
66 return Err(ErrorCode::InvalidRequest);
67 }
68 let path = PathBuf::from(std::ffi::OsString::from_wide(units));
69 let text = path.to_string_lossy();
70 if path.is_absolute() && !text.starts_with("\\\\") && !text.starts_with("//") {
71 return Ok(path);
72 }
73 return Err(ErrorCode::InvalidRequest);
74 }
75 Err(ErrorCode::UnsupportedFeature)
76 }
77}
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub struct Limits {
80 pub input: u64,
81 pub output: u64,
82 pub entries: u32,
83}
84impl Default for Limits {
85 fn default() -> Self {
86 Self {
87 input: u64::MAX,
88 output: 16 * 1024 * 1024 * 1024,
89 entries: 10_000,
90 }
91 }
92}
93impl Limits {
94 pub(crate) fn legacy(self) -> Self {
95 Self {
96 input: self.input.min(64 * 1024 * 1024),
97 output: self.output.min(128 * 1024 * 1024),
98 entries: self.entries,
99 }
100 }
101
102 pub fn valid(self) -> bool {
103 let hard = Self::default();
104 self.input > 0
105 && self.input <= hard.input
106 && self.output > 0
107 && self.output <= hard.output
108 && self.entries > 0
109 && self.entries <= hard.entries
110 }
111}
112#[derive(Clone, Debug, PartialEq, Eq)]
113pub struct GuardedStart {
114 pub start: Start,
115 pub ceiling: Limits,
116 pub interactive: bool,
117}
118impl GuardedStart {
119 pub fn valid(&self) -> bool {
120 self.start.limits.valid()
121 && self.ceiling.input == self.start.limits.input
122 && self.ceiling.output >= self.start.limits.output
123 && self.ceiling.output <= 64 * 1024 * 1024 * 1024
124 && self.ceiling.entries >= self.start.limits.entries
125 && self.ceiling.entries <= 200_000
126 && (!self.interactive
127 || matches!(
128 self.start.action,
129 Action::Extract { .. } | Action::Preview { .. }
130 ))
131 && (!matches!(self.start.action, Action::Preview { .. }) || self.interactive)
132 }
133}
134#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
135pub struct ResourceScope {
136 pub output: bool,
137 pub entries: bool,
138 pub ratio: bool,
139}
140impl ResourceScope {
141 pub fn any(self) -> bool {
142 self.output || self.entries || self.ratio
143 }
144}
145#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
146pub struct ResourceUsage {
147 pub estimated_bytes: Option<u64>,
148 pub actual_bytes: Option<u64>,
149 pub estimated_entries: Option<u32>,
150 pub actual_entries: Option<u32>,
151 pub compressed_bytes: Option<u64>,
152 pub ratio_output_bytes: Option<u64>,
153 pub available_bytes: Option<u64>,
154}
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156pub enum Format {
157 Zip,
158 Tar,
159 Gzip,
160 TarGzip,
161 SevenZip,
162}
163#[derive(Clone, Debug, PartialEq, Eq)]
164pub enum SourceObject {
165 Unix {
166 device: u64,
167 inode: u64,
168 },
169 Windows {
170 volume_serial: u64,
171 file_id: [u8; 16],
172 },
173 SplitSevenZip {
174 manifest_sha256: [u8; 32],
175 },
176}
177#[derive(Clone, Debug, PartialEq, Eq)]
178pub struct ListId {
179 pub catalog_version: u16,
180 pub format: Format,
181 pub source_object: SourceObject,
182 pub archive_bytes: u64,
183 pub archive_sha256: [u8; 32],
184}
185impl ListId {
186 pub fn valid(&self) -> bool {
187 matches!(
188 (self.catalog_version, self.format, &self.source_object),
189 (
190 1,
191 _,
192 SourceObject::Unix { .. } | SourceObject::Windows { .. }
193 ) | (2, Format::SevenZip, SourceObject::SplitSevenZip { .. })
194 )
195 }
196}
197#[derive(Clone, Debug, PartialEq, Eq)]
198pub enum Selection {
199 All,
200 EntryIds(Vec<u32>),
201}
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub enum Method {
204 Store,
205 Deflate,
206}
207#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub enum SevenZipMethod {
209 Lzma2,
210}
211#[derive(Clone, Copy, Debug, PartialEq, Eq)]
212pub enum Encryption {
213 None,
214 Aes256,
215}
216#[derive(Clone, Debug, PartialEq, Eq)]
217pub struct Source {
218 pub path: NativePath,
219 pub archive_name: String,
220}
221#[derive(Clone, Debug, PartialEq, Eq)]
222pub enum Action {
223 List {
224 archive: NativePath,
225 },
226 Extract {
227 archive: NativePath,
228 destination: NativePath,
229 selection: Selection,
230 list_id: Option<ListId>,
231 gzip_output_name: Option<String>,
232 },
233 CreateZip {
234 sources: Vec<Source>,
235 output_file: NativePath,
236 method: Method,
237 encryption: Encryption,
238 },
239 Preview {
240 archive: NativePath,
241 entry_id: u32,
242 list_id: ListId,
243 },
244 RecoverZip {
245 archive: NativePath,
246 output_file: NativePath,
247 },
248 CreateSevenZip {
249 sources: Vec<Source>,
250 output_file: NativePath,
251 method: SevenZipMethod,
252 solid: bool,
253 encryption: Encryption,
254 /// 있으면 `output_file`(이름.7z) 대신 이 크기로 나눈 `이름.7z.001`, `이름.7z.002`, …를 만듦.
255 volume_size: Option<u64>,
256 },
257}
258#[derive(Clone, Copy, Debug, PartialEq, Eq)]
259pub enum ActionKind {
260 List,
261 Extract,
262 CreateZip,
263 Preview,
264 CreateSevenZip,
265 RecoverZip,
266}
267impl Action {
268 pub fn kind(&self) -> ActionKind {
269 match self {
270 Self::List { .. } => ActionKind::List,
271 Self::Extract { .. } => ActionKind::Extract,
272 Self::CreateZip { .. } => ActionKind::CreateZip,
273 Self::Preview { .. } => ActionKind::Preview,
274 Self::CreateSevenZip { .. } => ActionKind::CreateSevenZip,
275 Self::RecoverZip { .. } => ActionKind::RecoverZip,
276 }
277 }
278}
279#[derive(Clone, Debug, PartialEq, Eq)]
280pub struct Start {
281 pub action: Action,
282 pub limits: Limits,
283}
284#[derive(Clone, Copy, Debug, PartialEq, Eq)]
285pub enum EntryKind {
286 File,
287 Directory,
288 Link,
289 Other,
290}
291#[derive(Clone, Debug, PartialEq, Eq)]
292pub struct Entry {
293 pub entry_id: u32,
294 pub name: String,
295 pub kind: EntryKind,
296 pub size: u64,
297 pub compressed_size: u64,
298 pub encrypted: bool,
299}
300#[derive(Clone, Copy, Debug, PartialEq, Eq)]
301pub enum PreviewFormat {
302 Utf8Text,
303 Rgba8,
304}
305#[derive(Clone, Copy, Debug, PartialEq, Eq)]
306pub struct PreviewInfo {
307 pub entry_id: u32,
308 pub format: PreviewFormat,
309 pub total_bytes: u64,
310 pub width: u32,
311 pub height: u32,
312}
313impl PreviewInfo {
314 pub fn valid(&self) -> bool {
315 match self.format {
316 PreviewFormat::Utf8Text => {
317 self.width == 0 && self.height == 0 && self.total_bytes <= MAX_PREVIEW_TEXT_BYTES
318 }
319 PreviewFormat::Rgba8 => {
320 if !(1..=MAX_PREVIEW_DIMENSION).contains(&self.width)
321 || !(1..=MAX_PREVIEW_DIMENSION).contains(&self.height)
322 {
323 return false;
324 }
325 let pixels = u64::from(self.width) * u64::from(self.height);
326 pixels <= MAX_PREVIEW_PIXELS
327 && pixels.checked_mul(4) == Some(self.total_bytes)
328 && self.total_bytes <= MAX_PREVIEW_RGBA_BYTES
329 }
330 }
331 }
332}
333#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334pub enum Stage {
335 Scan,
336 Read,
337 Decode,
338 Write,
339 Verify,
340 Commit,
341}
342#[derive(Clone, Copy, Debug, PartialEq, Eq)]
343pub enum Disposition {
344 Created,
345 PartialRetained,
346 Removed,
347 CommitUncertain,
348}
349#[derive(Clone, Copy, Debug, PartialEq, Eq)]
350pub enum Outcome {
351 Completed,
352 Failed,
353 Cancelled,
354}
355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
356pub enum ErrorCode {
357 None,
358 Integrity,
359 UnsupportedFormat,
360 UnsupportedFeature,
361 WrongPassword,
362 UnsafePath,
363 Conflict,
364 Limit,
365 Io,
366 Protocol,
367 Internal,
368 SourceChanged,
369 InvalidRequest,
370 DiskFull,
371 MissingVolume,
372 RecoveryIncomplete,
373 RecoveryImpossible,
374}
375#[derive(Clone, Copy, Debug, PartialEq, Eq)]
376pub enum VolumeProblemReason {
377 FirstVolumeRequired,
378 MissingVolume,
379 IncompleteSet,
380}
381impl VolumeProblemReason {
382 pub fn terminal_error(self) -> ErrorCode {
383 match self {
384 Self::FirstVolumeRequired => ErrorCode::InvalidRequest,
385 Self::MissingVolume => ErrorCode::MissingVolume,
386 Self::IncompleteSet => ErrorCode::Integrity,
387 }
388 }
389}
390#[derive(Clone, Copy, Debug, PartialEq, Eq)]
391pub enum Publication {
392 None,
393 Partial,
394 Complete,
395 Uncertain,
396}
397#[derive(Clone, Copy, Debug, PartialEq, Eq)]
398pub enum Durability {
399 NotApplicable,
400 Synced,
401 Unconfirmed,
402 Failed,
403}
404#[derive(Clone, Copy, Debug, PartialEq, Eq)]
405pub enum Cleanup {
406 Complete,
407 Failed,
408 Unconfirmed,
409}
410#[derive(Clone, Copy, Debug, PartialEq, Eq)]
411pub enum CancelStatus {
412 Requested,
413 AlreadyRequested,
414 TooLate,
415 Finished,
416}
417#[derive(Clone, Copy, Debug, PartialEq, Eq)]
418pub enum PasswordPurpose {
419 Decrypt,
420 Encrypt,
421}
422#[derive(Clone, Copy, Debug, PartialEq, Eq)]
423pub enum ConflictChoice {
424 Overwrite,
425 Skip,
426 Rename,
427}
428#[derive(Clone, Debug, PartialEq, Eq)]
429pub struct Terminal {
430 pub outcome: Outcome,
431 pub error: ErrorCode,
432 pub publication: Publication,
433 pub created_count: u64,
434 pub retained_partial_count: u64,
435 pub durability: Durability,
436 pub cleanup: Cleanup,
437 pub detail: String,
438}
439pub struct Secret(pub Vec<u8>);
440impl std::fmt::Debug for Secret {
441 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
442 f.write_str("[redacted]")
443 }
444}
445impl Drop for Secret {
446 fn drop(&mut self) {
447 zeroize::Zeroize::zeroize(&mut self.0);
448 }
449}
450#[derive(Debug)]
451pub enum Message {
452 Start(Start),
453 Password {
454 challenge_id: u64,
455 secret: Secret,
456 },
457 Cancel,
458 StartInteractive(Start),
459 StartGuarded(GuardedStart),
460 ResourceReply {
461 challenge_id: u64,
462 scope: ResourceScope,
463 allow: bool,
464 },
465 ResourceRequired {
466 challenge_id: u64,
467 action: ActionKind,
468 scope: ResourceScope,
469 usage: ResourceUsage,
470 soft_limits: Limits,
471 ceiling: Limits,
472 },
473 ConflictReply {
474 challenge_id: u64,
475 choice: ConflictChoice,
476 apply_to_remaining: bool,
477 },
478 Accepted {
479 action: ActionKind,
480 encryption: bool,
481 },
482 Entry(Entry),
483 ListEnd {
484 entry_count: u32,
485 list_id: ListId,
486 },
487 PasswordRequired {
488 challenge_id: u64,
489 attempt: u32,
490 purpose: PasswordPurpose,
491 },
492 Progress {
493 stage: Stage,
494 processed_bytes: u64,
495 total_bytes: Option<u64>,
496 completed_entries: u32,
497 },
498 Output {
499 entry_id: Option<u32>,
500 relative_name: String,
501 disposition: Disposition,
502 },
503 PreviewBegin(PreviewInfo),
504 PreviewChunk {
505 entry_id: u32,
506 offset: u64,
507 data: Vec<u8>,
508 },
509 PreviewEnd {
510 entry_id: u32,
511 total_bytes: u64,
512 sha256: [u8; 32],
513 },
514 VolumeProblem {
515 reason: VolumeProblemReason,
516 volume: NativePath,
517 },
518 RecoveryEntry(RecoveryEntry),
519 RecoveryEnd(RecoveryEnd),
520 Terminal(Terminal),
521 CancelAck {
522 request_sequence: u64,
523 status: CancelStatus,
524 },
525 ConflictRequired {
526 challenge_id: u64,
527 entry_id: u32,
528 relative_name: String,
529 incoming_size: u64,
530 existing_size: u64,
531 },
532 ConflictResolved {
533 entry_id: u32,
534 relative_name: String,
535 choice: ConflictChoice,
536 },
537}
538
539#[derive(Clone, Copy, Debug, PartialEq, Eq)]
540pub enum RecoveryMode {
541 CentralDirectory,
542 LocalChain,
543}
544#[derive(Clone, Copy, Debug, PartialEq, Eq)]
545pub enum RecoveryStatus {
546 Verified,
547 Lost,
548 Unverified,
549}
550#[derive(Clone, Copy, Debug, PartialEq, Eq)]
551pub enum RecoveryReason {
552 None,
553 HeaderRebuilt,
554 Truncated,
555 CrcMismatch,
556 DecodeFailure,
557 BoundaryUnknown,
558 UnsupportedFeature,
559 MetadataMissing,
560}
561#[derive(Clone, Debug, PartialEq, Eq)]
562pub struct RecoveryEntry {
563 pub candidate_id: u32,
564 pub source_offset: u64,
565 pub name: Option<String>,
566 pub kind: Option<EntryKind>,
567 pub status: RecoveryStatus,
568 pub reason: RecoveryReason,
569 pub declared_size: Option<u64>,
570 pub verified_size: Option<u64>,
571 pub sha256: Option<[u8; 32]>,
572}
573impl RecoveryEntry {
574 pub fn valid(&self) -> bool {
575 if self.name.as_ref().is_some_and(|name| name.is_empty()) {
576 return false;
577 }
578 if !matches!(
579 self.kind,
580 None | Some(EntryKind::File | EntryKind::Directory)
581 ) {
582 return false;
583 }
584 match self.status {
585 RecoveryStatus::Verified => {
586 if self.name.as_ref().is_none_or(|name| name.is_empty())
587 || !matches!(
588 self.reason,
589 RecoveryReason::None
590 | RecoveryReason::HeaderRebuilt
591 | RecoveryReason::MetadataMissing
592 )
593 || self.declared_size.is_none()
594 || self.declared_size != self.verified_size
595 {
596 return false;
597 }
598 match self.kind {
599 Some(EntryKind::File) => self.sha256.is_some(),
600 Some(EntryKind::Directory) => {
601 self.declared_size == Some(0) && self.sha256.is_none()
602 }
603 _ => false,
604 }
605 }
606 RecoveryStatus::Lost => {
607 self.verified_size.is_none()
608 && self.sha256.is_none()
609 && matches!(
610 self.reason,
611 RecoveryReason::Truncated
612 | RecoveryReason::CrcMismatch
613 | RecoveryReason::DecodeFailure
614 )
615 }
616 RecoveryStatus::Unverified => {
617 self.verified_size.is_none()
618 && self.sha256.is_none()
619 && matches!(
620 self.reason,
621 RecoveryReason::BoundaryUnknown
622 | RecoveryReason::UnsupportedFeature
623 | RecoveryReason::MetadataMissing
624 )
625 }
626 }
627 }
628}
629#[derive(Clone, Debug, PartialEq, Eq)]
630pub struct RecoveryEnd {
631 pub mode: RecoveryMode,
632 pub source_bytes: u64,
633 pub source_sha256: [u8; 32],
634 pub known_entries: Option<u32>,
635 pub verified_entries: u32,
636 pub lost_entries: u32,
637 pub unverified_entries: u32,
638 pub unknown_loss: bool,
639}
640impl RecoveryEnd {
641 pub fn valid(&self) -> bool {
642 let total = self
643 .verified_entries
644 .checked_add(self.lost_entries)
645 .and_then(|n| n.checked_add(self.unverified_entries));
646 let Some(total) = total else {
647 return false;
648 };
649 match (self.mode, self.known_entries, self.unknown_loss) {
650 (RecoveryMode::CentralDirectory, Some(known), false) => known == total,
651 (_, None, true) => true,
652 _ => false,
653 }
654 }
655 pub fn complete(&self) -> bool {
656 self.valid() && !self.unknown_loss && self.lost_entries == 0 && self.unverified_entries == 0
657 }
658}