team-ljyzipelo

공개
1,004줄31 KB
1use crate::protocol::*;
2use std::io::{self, Read, Write};
3
4pub const MAX_BODY: usize = 1_048_576;
5pub const MAX_FRAMES: u64 = 1_000_000;
6const LEGACY_VECTOR_ITEMS: usize = 32_768;
7const MAX_SELECTION_IDS: usize = 200_000;
8fn invalid() -> io::Error {
9 io::Error::new(io::ErrorKind::InvalidData, "invalid worker frame")
10}
11struct Encoder {
12 bytes: Vec<u8>,
13 selection_limit: usize,
14}
15impl Encoder {
16 fn put(&mut self, b: &[u8]) -> io::Result<()> {
17 if self
18 .bytes
19 .len()
20 .checked_add(b.len())
21 .filter(|n| *n <= MAX_BODY)
22 .is_none()
23 {
24 return Err(invalid());
25 }
26 self.bytes.extend_from_slice(b);
27 Ok(())
28 }
29}
30struct Decoder<'a> {
31 bytes: &'a [u8],
32 at: usize,
33 selection_limit: usize,
34}
35impl<'a> Decoder<'a> {
36 fn take(&mut self, n: usize) -> io::Result<&'a [u8]> {
37 let end = self.at.checked_add(n).ok_or_else(invalid)?;
38 let b = self.bytes.get(self.at..end).ok_or_else(invalid)?;
39 self.at = end;
40 Ok(b)
41 }
42}
43trait Wire: Sized {
44 fn enc(&self, e: &mut Encoder) -> io::Result<()>;
45 fn dec(d: &mut Decoder<'_>) -> io::Result<Self>;
46}
47macro_rules! integer { ($($t:ty),*) => { $(impl Wire for $t {
48 fn enc(&self,e:&mut Encoder)->io::Result<()> { e.put(&self.to_le_bytes()) }
49 fn dec(d:&mut Decoder<'_>)->io::Result<Self> { Ok(Self::from_le_bytes(d.take(size_of::<Self>())?.try_into().map_err(|_|invalid())?)) }
50})* }; }
51integer!(u8, u16, u32, u64);
52impl<const N: usize> Wire for [u8; N] {
53 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
54 e.put(self)
55 }
56 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
57 d.take(N)?.try_into().map_err(|_| invalid())
58 }
59}
60impl Wire for bool {
61 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
62 u8::from(*self).enc(e)
63 }
64 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
65 match u8::dec(d)? {
66 0 => Ok(false),
67 1 => Ok(true),
68 _ => Err(invalid()),
69 }
70 }
71}
72impl<T: Wire> Wire for Option<T> {
73 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
74 self.is_some().enc(e)?;
75 if let Some(v) = self {
76 v.enc(e)?;
77 }
78 Ok(())
79 }
80 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
81 if bool::dec(d)? {
82 Ok(Some(T::dec(d)?))
83 } else {
84 Ok(None)
85 }
86 }
87}
88fn encode_vec<T: Wire>(values: &[T], limit: usize, e: &mut Encoder) -> io::Result<()> {
89 if values.len() > limit {
90 return Err(invalid());
91 }
92 (values.len() as u32).enc(e)?;
93 for value in values {
94 value.enc(e)?;
95 }
96 Ok(())
97}
98fn decode_vec<T: Wire>(limit: usize, d: &mut Decoder<'_>) -> io::Result<Vec<T>> {
99 let n = u32::dec(d)? as usize;
100 if n > limit || n > d.bytes.len() - d.at {
101 return Err(invalid());
102 }
103 let mut values = Vec::new();
104 values.try_reserve(n).map_err(|_| invalid())?;
105 for _ in 0..n {
106 values.push(T::dec(d)?);
107 }
108 Ok(values)
109}
110impl<T: Wire> Wire for Vec<T> {
111 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
112 encode_vec(self, LEGACY_VECTOR_ITEMS, e)
113 }
114 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
115 decode_vec(LEGACY_VECTOR_ITEMS, d)
116 }
117}
118impl Wire for String {
119 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
120 if self.len() > 32768 {
121 return Err(invalid());
122 }
123 (self.len() as u32).enc(e)?;
124 e.put(self.as_bytes())
125 }
126 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
127 let n = u32::dec(d)? as usize;
128 if n > 32768 {
129 return Err(invalid());
130 }
131 String::from_utf8(d.take(n)?.to_vec()).map_err(|_| invalid())
132 }
133}
134macro_rules! enumeration { ($t:ident {$($v:ident=$n:expr),*$(,)?}) => { impl Wire for $t {
135 fn enc(&self,e:&mut Encoder)->io::Result<()> { (match self {$(Self::$v=>$n,)*} as u8).enc(e) }
136 fn dec(d:&mut Decoder<'_>)->io::Result<Self> { match u8::dec(d)? {$($n=>Ok(Self::$v),)*_=>Err(invalid())} }
137} }; }
138enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3,SevenZip=4});
139enumeration!(Method{Store=0,Deflate=1});
140enumeration!(SevenZipMethod{Lzma2=0});
141enumeration!(Encryption{None=0,Aes256=1});
142enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3,CreateSevenZip=4,RecoverZip=5});
143enumeration!(RecoveryMode{CentralDirectory=0,LocalChain=1});
144enumeration!(RecoveryStatus{Verified=0,Lost=1,Unverified=2});
145enumeration!(RecoveryReason{None=0,HeaderRebuilt=1,Truncated=2,CrcMismatch=3,DecodeFailure=4,BoundaryUnknown=5,UnsupportedFeature=6,MetadataMissing=7});
146enumeration!(PreviewFormat{Utf8Text=0,Rgba8=1});
147enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3});
148enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5});
149enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3});
150enumeration!(Outcome{Completed=0,Failed=1,Cancelled=2});
151enumeration!(ErrorCode{None=0,Integrity=1,UnsupportedFormat=2,UnsupportedFeature=3,WrongPassword=4,UnsafePath=5,Conflict=6,Limit=7,Io=8,Protocol=9,Internal=10,SourceChanged=11,InvalidRequest=12,DiskFull=13,MissingVolume=14,RecoveryIncomplete=15,RecoveryImpossible=16});
152enumeration!(VolumeProblemReason{FirstVolumeRequired=0,MissingVolume=1,IncompleteSet=2});
153enumeration!(Publication{None=0,Partial=1,Complete=2,Uncertain=3});
154enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3});
155enumeration!(Cleanup{Complete=0,Failed=1,Unconfirmed=2});
156enumeration!(CancelStatus{Requested=0,AlreadyRequested=1,TooLate=2,Finished=3});
157enumeration!(PasswordPurpose{Decrypt=0,Encrypt=1});
158enumeration!(ConflictChoice{Overwrite=0,Skip=1,Rename=2});
159macro_rules! structure {($t:ident {$($f:ident),*})=>{impl Wire for $t {
160 fn enc(&self,e:&mut Encoder)->io::Result<()> {$(self.$f.enc(e)?;)*Ok(())}
161 fn dec(d:&mut Decoder<'_>)->io::Result<Self> {Ok(Self {$($f:Wire::dec(d)?,)*})}
162}};}
163structure!(Limits {
164 input,
165 output,
166 entries
167});
168impl Wire for ListId {
169 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
170 if !self.valid() {
171 return Err(invalid());
172 }
173 self.catalog_version.enc(e)?;
174 self.format.enc(e)?;
175 self.source_object.enc(e)?;
176 self.archive_bytes.enc(e)?;
177 self.archive_sha256.enc(e)
178 }
179 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
180 let id = Self {
181 catalog_version: Wire::dec(d)?,
182 format: Wire::dec(d)?,
183 source_object: Wire::dec(d)?,
184 archive_bytes: Wire::dec(d)?,
185 archive_sha256: Wire::dec(d)?,
186 };
187 if !id.valid() {
188 return Err(invalid());
189 }
190 Ok(id)
191 }
192}
193impl Wire for PreviewInfo {
194 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
195 if !self.valid() {
196 return Err(invalid());
197 }
198 self.entry_id.enc(e)?;
199 self.format.enc(e)?;
200 self.total_bytes.enc(e)?;
201 self.width.enc(e)?;
202 self.height.enc(e)
203 }
204 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
205 let info = Self {
206 entry_id: Wire::dec(d)?,
207 format: Wire::dec(d)?,
208 total_bytes: Wire::dec(d)?,
209 width: Wire::dec(d)?,
210 height: Wire::dec(d)?,
211 };
212 if !info.valid() {
213 return Err(invalid());
214 }
215 Ok(info)
216 }
217}
218impl Wire for RecoveryEntry {
219 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
220 if !self.valid() {
221 return Err(invalid());
222 }
223 self.candidate_id.enc(e)?;
224 self.source_offset.enc(e)?;
225 self.name.enc(e)?;
226 self.kind.enc(e)?;
227 self.status.enc(e)?;
228 self.reason.enc(e)?;
229 self.declared_size.enc(e)?;
230 self.verified_size.enc(e)?;
231 self.sha256.enc(e)?;
232 Ok(())
233 }
234 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
235 let value = Self {
236 candidate_id: Wire::dec(d)?,
237 source_offset: Wire::dec(d)?,
238 name: Wire::dec(d)?,
239 kind: Wire::dec(d)?,
240 status: Wire::dec(d)?,
241 reason: Wire::dec(d)?,
242 declared_size: Wire::dec(d)?,
243 verified_size: Wire::dec(d)?,
244 sha256: Wire::dec(d)?,
245 };
246 if !value.valid() {
247 return Err(invalid());
248 }
249 Ok(value)
250 }
251}
252impl Wire for RecoveryEnd {
253 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
254 if !self.valid() {
255 return Err(invalid());
256 }
257 self.mode.enc(e)?;
258 self.source_bytes.enc(e)?;
259 self.source_sha256.enc(e)?;
260 self.known_entries.enc(e)?;
261 self.verified_entries.enc(e)?;
262 self.lost_entries.enc(e)?;
263 self.unverified_entries.enc(e)?;
264 self.unknown_loss.enc(e)?;
265 Ok(())
266 }
267 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
268 let value = Self {
269 mode: Wire::dec(d)?,
270 source_bytes: Wire::dec(d)?,
271 source_sha256: Wire::dec(d)?,
272 known_entries: Wire::dec(d)?,
273 verified_entries: Wire::dec(d)?,
274 lost_entries: Wire::dec(d)?,
275 unverified_entries: Wire::dec(d)?,
276 unknown_loss: Wire::dec(d)?,
277 };
278 if !value.valid() {
279 return Err(invalid());
280 }
281 Ok(value)
282 }
283}
284structure!(Source { path, archive_name });
285structure!(Start { action, limits });
286structure!(GuardedStart {
287 start,
288 ceiling,
289 interactive
290});
291structure!(ResourceScope {
292 output,
293 entries,
294 ratio
295});
296structure!(ResourceUsage {
297 estimated_bytes,
298 actual_bytes,
299 estimated_entries,
300 actual_entries,
301 compressed_bytes,
302 ratio_output_bytes,
303 available_bytes
304});
305structure!(Entry {
306 entry_id,
307 name,
308 kind,
309 size,
310 compressed_size,
311 encrypted
312});
313structure!(Terminal {
314 outcome,
315 error,
316 publication,
317 created_count,
318 retained_partial_count,
319 durability,
320 cleanup,
321 detail
322});
323impl Wire for NativePath {
324 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
325 match self {
326 Self::Unix(v) => {
327 1u8.enc(e)?;
328 v.enc(e)
329 }
330 Self::Windows(v) => {
331 2u8.enc(e)?;
332 v.enc(e)
333 }
334 }
335 }
336 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
337 match u8::dec(d)? {
338 1 => Ok(Self::Unix(Wire::dec(d)?)),
339 2 => Ok(Self::Windows(Wire::dec(d)?)),
340 _ => Err(invalid()),
341 }
342 }
343}
344impl Wire for SourceObject {
345 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
346 match self {
347 Self::Unix { device, inode } => {
348 1u8.enc(e)?;
349 device.enc(e)?;
350 inode.enc(e)
351 }
352 Self::Windows {
353 volume_serial,
354 file_id,
355 } => {
356 2u8.enc(e)?;
357 volume_serial.enc(e)?;
358 file_id.enc(e)
359 }
360 Self::SplitSevenZip { manifest_sha256 } => {
361 3u8.enc(e)?;
362 manifest_sha256.enc(e)
363 }
364 }
365 }
366 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
367 match u8::dec(d)? {
368 1 => Ok(Self::Unix {
369 device: Wire::dec(d)?,
370 inode: Wire::dec(d)?,
371 }),
372 2 => Ok(Self::Windows {
373 volume_serial: Wire::dec(d)?,
374 file_id: Wire::dec(d)?,
375 }),
376 3 => Ok(Self::SplitSevenZip {
377 manifest_sha256: Wire::dec(d)?,
378 }),
379 _ => Err(invalid()),
380 }
381 }
382}
383pub(crate) fn encode_source_object(value: &SourceObject) -> io::Result<Vec<u8>> {
384 encode_component(value)
385}
386pub(crate) fn encode_native_path(value: &NativePath) -> io::Result<Vec<u8>> {
387 encode_component(value)
388}
389fn encode_component(value: &impl Wire) -> io::Result<Vec<u8>> {
390 let mut encoder = Encoder {
391 bytes: Vec::new(),
392 selection_limit: LEGACY_VECTOR_ITEMS,
393 };
394 value.enc(&mut encoder)?;
395 Ok(encoder.bytes)
396}
397impl Wire for Selection {
398 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
399 match self {
400 Self::All => 0u8.enc(e),
401 Self::EntryIds(ids) => {
402 1u8.enc(e)?;
403 encode_vec(ids, e.selection_limit, e)
404 }
405 }
406 }
407 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
408 match u8::dec(d)? {
409 0 => Ok(Self::All),
410 1 => Ok(Self::EntryIds(decode_vec(d.selection_limit, d)?)),
411 _ => Err(invalid()),
412 }
413 }
414}
415impl Wire for Action {
416 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
417 match self {
418 Self::RecoverZip {
419 archive,
420 output_file,
421 } => {
422 5u8.enc(e)?;
423 archive.enc(e)?;
424 output_file.enc(e)
425 }
426 Self::List { archive } => {
427 0u8.enc(e)?;
428 archive.enc(e)
429 }
430 Self::Extract {
431 archive,
432 destination,
433 selection,
434 list_id,
435 gzip_output_name,
436 } => {
437 1u8.enc(e)?;
438 archive.enc(e)?;
439 destination.enc(e)?;
440 selection.enc(e)?;
441 list_id.enc(e)?;
442 gzip_output_name.enc(e)
443 }
444 Self::CreateZip {
445 sources,
446 output_file,
447 method,
448 encryption,
449 } => {
450 2u8.enc(e)?;
451 sources.enc(e)?;
452 output_file.enc(e)?;
453 method.enc(e)?;
454 encryption.enc(e)
455 }
456 Self::Preview {
457 archive,
458 entry_id,
459 list_id,
460 } => {
461 3u8.enc(e)?;
462 archive.enc(e)?;
463 entry_id.enc(e)?;
464 list_id.enc(e)
465 }
466 Self::CreateSevenZip {
467 sources,
468 output_file,
469 method,
470 solid,
471 encryption,
472 } => {
473 4u8.enc(e)?;
474 sources.enc(e)?;
475 output_file.enc(e)?;
476 method.enc(e)?;
477 solid.enc(e)?;
478 encryption.enc(e)
479 }
480 }
481 }
482 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
483 match u8::dec(d)? {
484 0 => Ok(Self::List {
485 archive: Wire::dec(d)?,
486 }),
487 1 => Ok(Self::Extract {
488 archive: Wire::dec(d)?,
489 destination: Wire::dec(d)?,
490 selection: Wire::dec(d)?,
491 list_id: Wire::dec(d)?,
492 gzip_output_name: Wire::dec(d)?,
493 }),
494 2 => Ok(Self::CreateZip {
495 sources: Wire::dec(d)?,
496 output_file: Wire::dec(d)?,
497 method: Wire::dec(d)?,
498 encryption: Wire::dec(d)?,
499 }),
500 3 => Ok(Self::Preview {
501 archive: Wire::dec(d)?,
502 entry_id: Wire::dec(d)?,
503 list_id: Wire::dec(d)?,
504 }),
505 5 => Ok(Self::RecoverZip {
506 archive: Wire::dec(d)?,
507 output_file: Wire::dec(d)?,
508 }),
509 4 => Ok(Self::CreateSevenZip {
510 sources: Wire::dec(d)?,
511 output_file: Wire::dec(d)?,
512 method: Wire::dec(d)?,
513 solid: Wire::dec(d)?,
514 encryption: Wire::dec(d)?,
515 }),
516 _ => Err(invalid()),
517 }
518 }
519}
520fn valid_preview_chunk(offset: u64, length: usize) -> bool {
521 (1..=MAX_PREVIEW_CHUNK_BYTES).contains(&length)
522 && offset
523 .checked_add(length as u64)
524 .is_some_and(|end| end <= MAX_PREVIEW_RGBA_BYTES)
525}
526impl Message {
527 fn encode(&self) -> io::Result<(u16, Vec<u8>)> {
528 let mut e = Encoder {
529 bytes: Vec::new(),
530 selection_limit: LEGACY_VECTOR_ITEMS,
531 };
532 let kind = match self {
533 Self::Start(v) => {
534 if matches!(v.action, Action::Preview { .. }) {
535 return Err(invalid());
536 }
537 v.enc(&mut e)?;
538 1
539 }
540 Self::Password {
541 challenge_id,
542 secret,
543 } => {
544 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
545 return Err(invalid());
546 }
547 challenge_id.enc(&mut e)?;
548 secret.0.enc(&mut e)?;
549 2
550 }
551 Self::Cancel => 3,
552 Self::StartInteractive(v) => {
553 if !matches!(&v.action, Action::Extract { .. }) {
554 return Err(invalid());
555 }
556 v.enc(&mut e)?;
557 4
558 }
559 Self::ConflictReply {
560 challenge_id,
561 choice,
562 apply_to_remaining,
563 } => {
564 challenge_id.enc(&mut e)?;
565 choice.enc(&mut e)?;
566 apply_to_remaining.enc(&mut e)?;
567 5
568 }
569 Self::StartGuarded(v) => {
570 if !v.valid() {
571 return Err(invalid());
572 }
573 e.selection_limit = LEGACY_VECTOR_ITEMS.max(v.ceiling.entries as usize);
574 v.enc(&mut e)?;
575 6
576 }
577 Self::ResourceReply {
578 challenge_id,
579 scope,
580 allow,
581 } => {
582 challenge_id.enc(&mut e)?;
583 scope.enc(&mut e)?;
584 allow.enc(&mut e)?;
585 7
586 }
587 Self::ResourceRequired {
588 challenge_id,
589 action,
590 scope,
591 usage,
592 soft_limits,
593 ceiling,
594 } => {
595 challenge_id.enc(&mut e)?;
596 action.enc(&mut e)?;
597 scope.enc(&mut e)?;
598 usage.enc(&mut e)?;
599 soft_limits.enc(&mut e)?;
600 ceiling.enc(&mut e)?;
601 110
602 }
603 Self::Accepted { action, encryption } => {
604 if *action == ActionKind::RecoverZip && *encryption {
605 return Err(invalid());
606 }
607 action.enc(&mut e)?;
608 encryption.enc(&mut e)?;
609 100
610 }
611 Self::Entry(v) => {
612 v.enc(&mut e)?;
613 101
614 }
615 Self::ListEnd {
616 entry_count,
617 list_id,
618 } => {
619 entry_count.enc(&mut e)?;
620 list_id.enc(&mut e)?;
621 102
622 }
623 Self::PasswordRequired {
624 challenge_id,
625 attempt,
626 purpose,
627 } => {
628 challenge_id.enc(&mut e)?;
629 attempt.enc(&mut e)?;
630 purpose.enc(&mut e)?;
631 103
632 }
633 Self::Progress {
634 stage,
635 processed_bytes,
636 total_bytes,
637 completed_entries,
638 } => {
639 stage.enc(&mut e)?;
640 processed_bytes.enc(&mut e)?;
641 total_bytes.enc(&mut e)?;
642 completed_entries.enc(&mut e)?;
643 104
644 }
645 Self::Output {
646 entry_id,
647 relative_name,
648 disposition,
649 } => {
650 entry_id.enc(&mut e)?;
651 relative_name.enc(&mut e)?;
652 disposition.enc(&mut e)?;
653 105
654 }
655 Self::PreviewBegin(info) => {
656 info.enc(&mut e)?;
657 111
658 }
659 Self::PreviewChunk {
660 entry_id,
661 offset,
662 data,
663 } => {
664 if !valid_preview_chunk(*offset, data.len()) {
665 return Err(invalid());
666 }
667 entry_id.enc(&mut e)?;
668 offset.enc(&mut e)?;
669 (data.len() as u32).enc(&mut e)?;
670 e.put(data)?;
671 112
672 }
673 Self::PreviewEnd {
674 entry_id,
675 total_bytes,
676 sha256,
677 } => {
678 if *total_bytes > MAX_PREVIEW_RGBA_BYTES {
679 return Err(invalid());
680 }
681 entry_id.enc(&mut e)?;
682 total_bytes.enc(&mut e)?;
683 sha256.enc(&mut e)?;
684 113
685 }
686 Self::VolumeProblem { reason, volume } => {
687 if !volume.is_basename() {
688 return Err(invalid());
689 }
690 reason.enc(&mut e)?;
691 volume.enc(&mut e)?;
692 114
693 }
694 Self::RecoveryEntry(v) => {
695 v.enc(&mut e)?;
696 115
697 }
698 Self::RecoveryEnd(v) => {
699 v.enc(&mut e)?;
700 116
701 }
702 Self::Terminal(v) => {
703 if v.detail.len() > 4096 {
704 return Err(invalid());
705 }
706 v.enc(&mut e)?;
707 106
708 }
709 Self::CancelAck {
710 request_sequence,
711 status,
712 } => {
713 request_sequence.enc(&mut e)?;
714 status.enc(&mut e)?;
715 107
716 }
717 Self::ConflictRequired {
718 challenge_id,
719 entry_id,
720 relative_name,
721 incoming_size,
722 existing_size,
723 } => {
724 challenge_id.enc(&mut e)?;
725 entry_id.enc(&mut e)?;
726 relative_name.enc(&mut e)?;
727 incoming_size.enc(&mut e)?;
728 existing_size.enc(&mut e)?;
729 108
730 }
731 Self::ConflictResolved {
732 entry_id,
733 relative_name,
734 choice,
735 } => {
736 entry_id.enc(&mut e)?;
737 relative_name.enc(&mut e)?;
738 choice.enc(&mut e)?;
739 109
740 }
741 };
742 Ok((kind, e.bytes))
743 }
744 fn decode(kind: u16, b: &[u8]) -> io::Result<Self> {
745 let mut d = Decoder {
746 bytes: b,
747 at: 0,
748 selection_limit: if kind == 6 {
749 MAX_SELECTION_IDS
750 } else {
751 LEGACY_VECTOR_ITEMS
752 },
753 };
754 let m = match kind {
755 1 => {
756 let start = Start::dec(&mut d)?;
757 if matches!(start.action, Action::Preview { .. }) {
758 return Err(invalid());
759 }
760 Self::Start(start)
761 }
762 2 => {
763 let challenge_id = Wire::dec(&mut d)?;
764 let secret = Secret(Vec::<u8>::dec(&mut d)?);
765 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
766 return Err(invalid());
767 }
768 Self::Password {
769 challenge_id,
770 secret,
771 }
772 }
773 3 => Self::Cancel,
774 4 => {
775 let start = Start::dec(&mut d)?;
776 if !matches!(&start.action, Action::Extract { .. }) {
777 return Err(invalid());
778 }
779 Self::StartInteractive(start)
780 }
781 5 => Self::ConflictReply {
782 challenge_id: Wire::dec(&mut d)?,
783 choice: Wire::dec(&mut d)?,
784 apply_to_remaining: Wire::dec(&mut d)?,
785 },
786 6 => {
787 let start = GuardedStart::dec(&mut d)?;
788 let limit = LEGACY_VECTOR_ITEMS.max(start.ceiling.entries as usize);
789 if !start.valid()
790 || matches!(
791 &start.start.action,
792 Action::Extract { selection: Selection::EntryIds(ids), .. } if ids.len() > limit
793 )
794 {
795 return Err(invalid());
796 }
797 Self::StartGuarded(start)
798 }
799 7 => Self::ResourceReply {
800 challenge_id: Wire::dec(&mut d)?,
801 scope: Wire::dec(&mut d)?,
802 allow: Wire::dec(&mut d)?,
803 },
804 110 => Self::ResourceRequired {
805 challenge_id: Wire::dec(&mut d)?,
806 action: Wire::dec(&mut d)?,
807 scope: Wire::dec(&mut d)?,
808 usage: Wire::dec(&mut d)?,
809 soft_limits: Wire::dec(&mut d)?,
810 ceiling: Wire::dec(&mut d)?,
811 },
812 100 => {
813 let action = Wire::dec(&mut d)?;
814 let encryption = Wire::dec(&mut d)?;
815 if action == ActionKind::RecoverZip && encryption {
816 return Err(invalid());
817 }
818 Self::Accepted { action, encryption }
819 }
820 115 => Self::RecoveryEntry(Wire::dec(&mut d)?),
821 116 => Self::RecoveryEnd(Wire::dec(&mut d)?),
822 101 => Self::Entry(Wire::dec(&mut d)?),
823 102 => Self::ListEnd {
824 entry_count: Wire::dec(&mut d)?,
825 list_id: Wire::dec(&mut d)?,
826 },
827 103 => Self::PasswordRequired {
828 challenge_id: Wire::dec(&mut d)?,
829 attempt: Wire::dec(&mut d)?,
830 purpose: Wire::dec(&mut d)?,
831 },
832 104 => Self::Progress {
833 stage: Wire::dec(&mut d)?,
834 processed_bytes: Wire::dec(&mut d)?,
835 total_bytes: Wire::dec(&mut d)?,
836 completed_entries: Wire::dec(&mut d)?,
837 },
838 105 => Self::Output {
839 entry_id: Wire::dec(&mut d)?,
840 relative_name: Wire::dec(&mut d)?,
841 disposition: Wire::dec(&mut d)?,
842 },
843 111 => Self::PreviewBegin(Wire::dec(&mut d)?),
844 112 => {
845 let entry_id = Wire::dec(&mut d)?;
846 let offset = Wire::dec(&mut d)?;
847 let length = u32::dec(&mut d)? as usize;
848 if !valid_preview_chunk(offset, length) {
849 return Err(invalid());
850 }
851 let bytes = d.take(length)?;
852 let mut data = Vec::new();
853 data.try_reserve_exact(length).map_err(|_| invalid())?;
854 data.extend_from_slice(bytes);
855 Self::PreviewChunk {
856 entry_id,
857 offset,
858 data,
859 }
860 }
861 113 => {
862 let entry_id = Wire::dec(&mut d)?;
863 let total_bytes = u64::dec(&mut d)?;
864 if total_bytes > MAX_PREVIEW_RGBA_BYTES {
865 return Err(invalid());
866 }
867 Self::PreviewEnd {
868 entry_id,
869 total_bytes,
870 sha256: Wire::dec(&mut d)?,
871 }
872 }
873 114 => {
874 let reason = Wire::dec(&mut d)?;
875 let volume = NativePath::dec(&mut d)?;
876 if !volume.is_basename() {
877 return Err(invalid());
878 }
879 Self::VolumeProblem { reason, volume }
880 }
881 106 => {
882 let t = Terminal::dec(&mut d)?;
883 if t.detail.len() > 4096 {
884 return Err(invalid());
885 }
886 Self::Terminal(t)
887 }
888 107 => Self::CancelAck {
889 request_sequence: Wire::dec(&mut d)?,
890 status: Wire::dec(&mut d)?,
891 },
892 108 => Self::ConflictRequired {
893 challenge_id: Wire::dec(&mut d)?,
894 entry_id: Wire::dec(&mut d)?,
895 relative_name: Wire::dec(&mut d)?,
896 incoming_size: Wire::dec(&mut d)?,
897 existing_size: Wire::dec(&mut d)?,
898 },
899 109 => Self::ConflictResolved {
900 entry_id: Wire::dec(&mut d)?,
901 relative_name: Wire::dec(&mut d)?,
902 choice: Wire::dec(&mut d)?,
903 },
904 _ => return Err(invalid()),
905 };
906 if d.at != b.len() {
907 return Err(invalid());
908 }
909 Ok(m)
910 }
911}
912pub struct Reader<R> {
913 input: R,
914 sequence: u64,
915 job: Option<u64>,
916 terminal: bool,
917}
918impl<R: Read> Reader<R> {
919 pub fn new(input: R) -> Self {
920 Self {
921 input,
922 sequence: 0,
923 job: None,
924 terminal: false,
925 }
926 }
927 pub fn read(&mut self) -> io::Result<Option<(u64, u64, Message)>> {
928 let mut h = [0u8; 32];
929 loop {
930 match self.input.read(&mut h[..1]) {
931 Ok(0) => return Ok(None),
932 Ok(_) => break,
933 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
934 Err(e) => return Err(e),
935 }
936 }
937 if self.terminal {
938 return Err(invalid());
939 }
940 self.input.read_exact(&mut h[1..])?;
941 let len = u32::from_le_bytes(h[8..12].try_into().unwrap()) as usize;
942 let job = u64::from_le_bytes(h[16..24].try_into().unwrap());
943 let seq = u64::from_le_bytes(h[24..32].try_into().unwrap());
944 if &h[..4] != b"ZAW1"
945 || h[4..6] != 1u16.to_le_bytes()
946 || h[12..16] != [0; 4]
947 || len > MAX_BODY
948 || job == 0
949 || self.job.is_some_and(|j| j != job)
950 || seq != self.sequence
951 || seq >= MAX_FRAMES
952 {
953 return Err(invalid());
954 }
955 self.job = Some(job);
956 self.sequence += 1;
957 let mut b = zeroize::Zeroizing::new(vec![0; len]);
958 self.input.read_exact(&mut b)?;
959 let message = Message::decode(u16::from_le_bytes(h[6..8].try_into().unwrap()), &b)?;
960 self.terminal = matches!(message, Message::Terminal(_));
961 Ok(Some((job, seq, message)))
962 }
963}
964pub struct Writer<W> {
965 output: W,
966 sequence: u64,
967 job: u64,
968 terminal: bool,
969}
970impl<W: Write> Writer<W> {
971 pub fn new(output: W, job: u64) -> Self {
972 Self {
973 output,
974 sequence: 0,
975 job,
976 terminal: false,
977 }
978 }
979 pub fn send(&mut self, m: &Message) -> io::Result<()> {
980 if self.job == 0 || self.terminal || self.sequence >= MAX_FRAMES {
981 return Err(invalid());
982 }
983 let (kind, b) = m.encode()?;
984 let b = zeroize::Zeroizing::new(b);
985 let mut h = Vec::with_capacity(32);
986 h.extend(b"ZAW1");
987 h.extend(1u16.to_le_bytes());
988 h.extend(kind.to_le_bytes());
989 h.extend((b.len() as u32).to_le_bytes());
990 h.extend(0u32.to_le_bytes());
991 h.extend(self.job.to_le_bytes());
992 h.extend(self.sequence.to_le_bytes());
993 self.output.write_all(&h)?;
994 self.output.write_all(&b)?;
995 self.output.flush()?;
996 self.sequence += 1;
997 self.terminal = matches!(m, Message::Terminal(_));
998 Ok(())
999 }
1000}
1001
1002#[cfg(test)]
1003#[path = "../../../tests/rust-archive-worker/selection_wire.rs"]
1004mod tests;