team-ljyzipelo

공개
508줄13 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
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub enum NativePath {
12 Unix(Vec<u8>),
13 Windows(Vec<u16>),
14}
15impl NativePath {
16 pub fn from_path(path: &Path) -> Self {
17 #[cfg(unix)]
18 {
19 use std::os::unix::ffi::OsStrExt;
20 Self::Unix(path.as_os_str().as_bytes().to_vec())
21 }
22 #[cfg(windows)]
23 {
24 use std::os::windows::ffi::OsStrExt;
25 Self::Windows(path.as_os_str().encode_wide().collect())
26 }
27 }
28 pub fn is_basename(&self) -> bool {
29 match self {
30 Self::Unix(bytes) => {
31 !bytes.is_empty()
32 && bytes != b"."
33 && bytes != b".."
34 && !bytes.iter().any(|byte| matches!(*byte, 0 | b'/' | b'\\'))
35 }
36 Self::Windows(units) => {
37 !units.is_empty()
38 && units != &[b'.' as u16]
39 && units != &[b'.' as u16, b'.' as u16]
40 && !units.iter().any(|unit| matches!(*unit, 0 | 47 | 92 | 58))
41 }
42 }
43 }
44 pub fn to_path(&self) -> Result<PathBuf, ErrorCode> {
45 #[cfg(unix)]
46 if let Self::Unix(bytes) = self {
47 use std::os::unix::ffi::OsStringExt;
48 if bytes.contains(&0) {
49 return Err(ErrorCode::InvalidRequest);
50 }
51 let path = PathBuf::from(std::ffi::OsString::from_vec(bytes.clone()));
52 return if path.is_absolute() {
53 Ok(path)
54 } else {
55 Err(ErrorCode::InvalidRequest)
56 };
57 }
58 #[cfg(windows)]
59 if let Self::Windows(units) = self {
60 use std::os::windows::ffi::OsStringExt;
61 if units.contains(&0) {
62 return Err(ErrorCode::InvalidRequest);
63 }
64 let path = PathBuf::from(std::ffi::OsString::from_wide(units));
65 let text = path.to_string_lossy();
66 if path.is_absolute() && !text.starts_with("\\\\") && !text.starts_with("//") {
67 return Ok(path);
68 }
69 return Err(ErrorCode::InvalidRequest);
70 }
71 Err(ErrorCode::UnsupportedFeature)
72 }
73}
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
75pub struct Limits {
76 pub input: u64,
77 pub output: u64,
78 pub entries: u32,
79}
80impl Default for Limits {
81 fn default() -> Self {
82 Self {
83 input: u64::MAX,
84 output: 16 * 1024 * 1024 * 1024,
85 entries: 10_000,
86 }
87 }
88}
89impl Limits {
90 pub(crate) fn legacy(self) -> Self {
91 Self {
92 input: self.input.min(64 * 1024 * 1024),
93 output: self.output.min(128 * 1024 * 1024),
94 entries: self.entries,
95 }
96 }
97
98 pub fn valid(self) -> bool {
99 let hard = Self::default();
100 self.input > 0
101 && self.input <= hard.input
102 && self.output > 0
103 && self.output <= hard.output
104 && self.entries > 0
105 && self.entries <= hard.entries
106 }
107}
108#[derive(Clone, Debug, PartialEq, Eq)]
109pub struct GuardedStart {
110 pub start: Start,
111 pub ceiling: Limits,
112 pub interactive: bool,
113}
114impl GuardedStart {
115 pub fn valid(&self) -> bool {
116 self.start.limits.valid()
117 && self.ceiling.input == self.start.limits.input
118 && self.ceiling.output >= self.start.limits.output
119 && self.ceiling.output <= 64 * 1024 * 1024 * 1024
120 && self.ceiling.entries >= self.start.limits.entries
121 && self.ceiling.entries <= 200_000
122 && (!self.interactive
123 || matches!(
124 self.start.action,
125 Action::Extract { .. } | Action::Preview { .. }
126 ))
127 && (!matches!(self.start.action, Action::Preview { .. }) || self.interactive)
128 }
129}
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
131pub struct ResourceScope {
132 pub output: bool,
133 pub entries: bool,
134 pub ratio: bool,
135}
136impl ResourceScope {
137 pub fn any(self) -> bool {
138 self.output || self.entries || self.ratio
139 }
140}
141#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142pub struct ResourceUsage {
143 pub estimated_bytes: Option<u64>,
144 pub actual_bytes: Option<u64>,
145 pub estimated_entries: Option<u32>,
146 pub actual_entries: Option<u32>,
147 pub compressed_bytes: Option<u64>,
148 pub ratio_output_bytes: Option<u64>,
149 pub available_bytes: Option<u64>,
150}
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152pub enum Format {
153 Zip,
154 Tar,
155 Gzip,
156 TarGzip,
157 SevenZip,
158}
159#[derive(Clone, Debug, PartialEq, Eq)]
160pub enum SourceObject {
161 Unix {
162 device: u64,
163 inode: u64,
164 },
165 Windows {
166 volume_serial: u64,
167 file_id: [u8; 16],
168 },
169 SplitSevenZip {
170 manifest_sha256: [u8; 32],
171 },
172}
173#[derive(Clone, Debug, PartialEq, Eq)]
174pub struct ListId {
175 pub catalog_version: u16,
176 pub format: Format,
177 pub source_object: SourceObject,
178 pub archive_bytes: u64,
179 pub archive_sha256: [u8; 32],
180}
181impl ListId {
182 pub fn valid(&self) -> bool {
183 matches!(
184 (self.catalog_version, self.format, &self.source_object),
185 (
186 1,
187 _,
188 SourceObject::Unix { .. } | SourceObject::Windows { .. }
189 ) | (2, Format::SevenZip, SourceObject::SplitSevenZip { .. })
190 )
191 }
192}
193#[derive(Clone, Debug, PartialEq, Eq)]
194pub enum Selection {
195 All,
196 EntryIds(Vec<u32>),
197}
198#[derive(Clone, Copy, Debug, PartialEq, Eq)]
199pub enum Method {
200 Store,
201 Deflate,
202}
203#[derive(Clone, Copy, Debug, PartialEq, Eq)]
204pub enum Encryption {
205 None,
206 Aes256,
207}
208#[derive(Clone, Debug, PartialEq, Eq)]
209pub struct Source {
210 pub path: NativePath,
211 pub archive_name: String,
212}
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub enum Action {
215 List {
216 archive: NativePath,
217 },
218 Extract {
219 archive: NativePath,
220 destination: NativePath,
221 selection: Selection,
222 list_id: Option<ListId>,
223 gzip_output_name: Option<String>,
224 },
225 CreateZip {
226 sources: Vec<Source>,
227 output_file: NativePath,
228 method: Method,
229 encryption: Encryption,
230 },
231 Preview {
232 archive: NativePath,
233 entry_id: u32,
234 list_id: ListId,
235 },
236}
237#[derive(Clone, Copy, Debug, PartialEq, Eq)]
238pub enum ActionKind {
239 List,
240 Extract,
241 CreateZip,
242 Preview,
243}
244impl Action {
245 pub fn kind(&self) -> ActionKind {
246 match self {
247 Self::List { .. } => ActionKind::List,
248 Self::Extract { .. } => ActionKind::Extract,
249 Self::CreateZip { .. } => ActionKind::CreateZip,
250 Self::Preview { .. } => ActionKind::Preview,
251 }
252 }
253}
254#[derive(Clone, Debug, PartialEq, Eq)]
255pub struct Start {
256 pub action: Action,
257 pub limits: Limits,
258}
259#[derive(Clone, Copy, Debug, PartialEq, Eq)]
260pub enum EntryKind {
261 File,
262 Directory,
263 Link,
264 Other,
265}
266#[derive(Clone, Debug, PartialEq, Eq)]
267pub struct Entry {
268 pub entry_id: u32,
269 pub name: String,
270 pub kind: EntryKind,
271 pub size: u64,
272 pub compressed_size: u64,
273 pub encrypted: bool,
274}
275#[derive(Clone, Copy, Debug, PartialEq, Eq)]
276pub enum PreviewFormat {
277 Utf8Text,
278 Rgba8,
279}
280#[derive(Clone, Copy, Debug, PartialEq, Eq)]
281pub struct PreviewInfo {
282 pub entry_id: u32,
283 pub format: PreviewFormat,
284 pub total_bytes: u64,
285 pub width: u32,
286 pub height: u32,
287}
288impl PreviewInfo {
289 pub fn valid(&self) -> bool {
290 match self.format {
291 PreviewFormat::Utf8Text => {
292 self.width == 0 && self.height == 0 && self.total_bytes <= MAX_PREVIEW_TEXT_BYTES
293 }
294 PreviewFormat::Rgba8 => {
295 if !(1..=MAX_PREVIEW_DIMENSION).contains(&self.width)
296 || !(1..=MAX_PREVIEW_DIMENSION).contains(&self.height)
297 {
298 return false;
299 }
300 let pixels = u64::from(self.width) * u64::from(self.height);
301 pixels <= MAX_PREVIEW_PIXELS
302 && pixels.checked_mul(4) == Some(self.total_bytes)
303 && self.total_bytes <= MAX_PREVIEW_RGBA_BYTES
304 }
305 }
306 }
307}
308#[derive(Clone, Copy, Debug, PartialEq, Eq)]
309pub enum Stage {
310 Scan,
311 Read,
312 Decode,
313 Write,
314 Verify,
315 Commit,
316}
317#[derive(Clone, Copy, Debug, PartialEq, Eq)]
318pub enum Disposition {
319 Created,
320 PartialRetained,
321 Removed,
322 CommitUncertain,
323}
324#[derive(Clone, Copy, Debug, PartialEq, Eq)]
325pub enum Outcome {
326 Completed,
327 Failed,
328 Cancelled,
329}
330#[derive(Clone, Copy, Debug, PartialEq, Eq)]
331pub enum ErrorCode {
332 None,
333 Integrity,
334 UnsupportedFormat,
335 UnsupportedFeature,
336 WrongPassword,
337 UnsafePath,
338 Conflict,
339 Limit,
340 Io,
341 Protocol,
342 Internal,
343 SourceChanged,
344 InvalidRequest,
345 DiskFull,
346 MissingVolume,
347}
348#[derive(Clone, Copy, Debug, PartialEq, Eq)]
349pub enum VolumeProblemReason {
350 FirstVolumeRequired,
351 MissingVolume,
352 IncompleteSet,
353}
354impl VolumeProblemReason {
355 pub fn terminal_error(self) -> ErrorCode {
356 match self {
357 Self::FirstVolumeRequired => ErrorCode::InvalidRequest,
358 Self::MissingVolume => ErrorCode::MissingVolume,
359 Self::IncompleteSet => ErrorCode::Integrity,
360 }
361 }
362}
363#[derive(Clone, Copy, Debug, PartialEq, Eq)]
364pub enum Publication {
365 None,
366 Partial,
367 Complete,
368 Uncertain,
369}
370#[derive(Clone, Copy, Debug, PartialEq, Eq)]
371pub enum Durability {
372 NotApplicable,
373 Synced,
374 Unconfirmed,
375 Failed,
376}
377#[derive(Clone, Copy, Debug, PartialEq, Eq)]
378pub enum Cleanup {
379 Complete,
380 Failed,
381 Unconfirmed,
382}
383#[derive(Clone, Copy, Debug, PartialEq, Eq)]
384pub enum CancelStatus {
385 Requested,
386 AlreadyRequested,
387 TooLate,
388 Finished,
389}
390#[derive(Clone, Copy, Debug, PartialEq, Eq)]
391pub enum PasswordPurpose {
392 Decrypt,
393 Encrypt,
394}
395#[derive(Clone, Copy, Debug, PartialEq, Eq)]
396pub enum ConflictChoice {
397 Overwrite,
398 Skip,
399 Rename,
400}
401#[derive(Clone, Debug, PartialEq, Eq)]
402pub struct Terminal {
403 pub outcome: Outcome,
404 pub error: ErrorCode,
405 pub publication: Publication,
406 pub created_count: u64,
407 pub retained_partial_count: u64,
408 pub durability: Durability,
409 pub cleanup: Cleanup,
410 pub detail: String,
411}
412pub struct Secret(pub Vec<u8>);
413impl std::fmt::Debug for Secret {
414 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
415 f.write_str("[redacted]")
416 }
417}
418impl Drop for Secret {
419 fn drop(&mut self) {
420 zeroize::Zeroize::zeroize(&mut self.0);
421 }
422}
423#[derive(Debug)]
424pub enum Message {
425 Start(Start),
426 Password {
427 challenge_id: u64,
428 secret: Secret,
429 },
430 Cancel,
431 StartInteractive(Start),
432 StartGuarded(GuardedStart),
433 ResourceReply {
434 challenge_id: u64,
435 scope: ResourceScope,
436 allow: bool,
437 },
438 ResourceRequired {
439 challenge_id: u64,
440 action: ActionKind,
441 scope: ResourceScope,
442 usage: ResourceUsage,
443 soft_limits: Limits,
444 ceiling: Limits,
445 },
446 ConflictReply {
447 challenge_id: u64,
448 choice: ConflictChoice,
449 apply_to_remaining: bool,
450 },
451 Accepted {
452 action: ActionKind,
453 encryption: bool,
454 },
455 Entry(Entry),
456 ListEnd {
457 entry_count: u32,
458 list_id: ListId,
459 },
460 PasswordRequired {
461 challenge_id: u64,
462 attempt: u32,
463 purpose: PasswordPurpose,
464 },
465 Progress {
466 stage: Stage,
467 processed_bytes: u64,
468 total_bytes: Option<u64>,
469 completed_entries: u32,
470 },
471 Output {
472 entry_id: Option<u32>,
473 relative_name: String,
474 disposition: Disposition,
475 },
476 PreviewBegin(PreviewInfo),
477 PreviewChunk {
478 entry_id: u32,
479 offset: u64,
480 data: Vec<u8>,
481 },
482 PreviewEnd {
483 entry_id: u32,
484 total_bytes: u64,
485 sha256: [u8; 32],
486 },
487 VolumeProblem {
488 reason: VolumeProblemReason,
489 volume: NativePath,
490 },
491 Terminal(Terminal),
492 CancelAck {
493 request_sequence: u64,
494 status: CancelStatus,
495 },
496 ConflictRequired {
497 challenge_id: u64,
498 entry_id: u32,
499 relative_name: String,
500 incoming_size: u64,
501 existing_size: u64,
502 },
503 ConflictResolved {
504 entry_id: u32,
505 relative_name: String,
506 choice: ConflictChoice,
507 },
508}