team-ljyzipelo

공개
1,007줄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 volume_size,
473 } => {
474 4u8.enc(e)?;
475 sources.enc(e)?;
476 output_file.enc(e)?;
477 method.enc(e)?;
478 solid.enc(e)?;
479 encryption.enc(e)?;
480 volume_size.enc(e)
481 }
482 }
483 }
484 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
485 match u8::dec(d)? {
486 0 => Ok(Self::List {
487 archive: Wire::dec(d)?,
488 }),
489 1 => Ok(Self::Extract {
490 archive: Wire::dec(d)?,
491 destination: Wire::dec(d)?,
492 selection: Wire::dec(d)?,
493 list_id: Wire::dec(d)?,
494 gzip_output_name: Wire::dec(d)?,
495 }),
496 2 => Ok(Self::CreateZip {
497 sources: Wire::dec(d)?,
498 output_file: Wire::dec(d)?,
499 method: Wire::dec(d)?,
500 encryption: Wire::dec(d)?,
501 }),
502 3 => Ok(Self::Preview {
503 archive: Wire::dec(d)?,
504 entry_id: Wire::dec(d)?,
505 list_id: Wire::dec(d)?,
506 }),
507 5 => Ok(Self::RecoverZip {
508 archive: Wire::dec(d)?,
509 output_file: Wire::dec(d)?,
510 }),
511 4 => Ok(Self::CreateSevenZip {
512 sources: Wire::dec(d)?,
513 output_file: Wire::dec(d)?,
514 method: Wire::dec(d)?,
515 solid: Wire::dec(d)?,
516 encryption: Wire::dec(d)?,
517 volume_size: Wire::dec(d)?,
518 }),
519 _ => Err(invalid()),
520 }
521 }
522}
523fn valid_preview_chunk(offset: u64, length: usize) -> bool {
524 (1..=MAX_PREVIEW_CHUNK_BYTES).contains(&length)
525 && offset
526 .checked_add(length as u64)
527 .is_some_and(|end| end <= MAX_PREVIEW_RGBA_BYTES)
528}
529impl Message {
530 fn encode(&self) -> io::Result<(u16, Vec<u8>)> {
531 let mut e = Encoder {
532 bytes: Vec::new(),
533 selection_limit: LEGACY_VECTOR_ITEMS,
534 };
535 let kind = match self {
536 Self::Start(v) => {
537 if matches!(v.action, Action::Preview { .. }) {
538 return Err(invalid());
539 }
540 v.enc(&mut e)?;
541 1
542 }
543 Self::Password {
544 challenge_id,
545 secret,
546 } => {
547 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
548 return Err(invalid());
549 }
550 challenge_id.enc(&mut e)?;
551 secret.0.enc(&mut e)?;
552 2
553 }
554 Self::Cancel => 3,
555 Self::StartInteractive(v) => {
556 if !matches!(&v.action, Action::Extract { .. }) {
557 return Err(invalid());
558 }
559 v.enc(&mut e)?;
560 4
561 }
562 Self::ConflictReply {
563 challenge_id,
564 choice,
565 apply_to_remaining,
566 } => {
567 challenge_id.enc(&mut e)?;
568 choice.enc(&mut e)?;
569 apply_to_remaining.enc(&mut e)?;
570 5
571 }
572 Self::StartGuarded(v) => {
573 if !v.valid() {
574 return Err(invalid());
575 }
576 e.selection_limit = LEGACY_VECTOR_ITEMS.max(v.ceiling.entries as usize);
577 v.enc(&mut e)?;
578 6
579 }
580 Self::ResourceReply {
581 challenge_id,
582 scope,
583 allow,
584 } => {
585 challenge_id.enc(&mut e)?;
586 scope.enc(&mut e)?;
587 allow.enc(&mut e)?;
588 7
589 }
590 Self::ResourceRequired {
591 challenge_id,
592 action,
593 scope,
594 usage,
595 soft_limits,
596 ceiling,
597 } => {
598 challenge_id.enc(&mut e)?;
599 action.enc(&mut e)?;
600 scope.enc(&mut e)?;
601 usage.enc(&mut e)?;
602 soft_limits.enc(&mut e)?;
603 ceiling.enc(&mut e)?;
604 110
605 }
606 Self::Accepted { action, encryption } => {
607 if *action == ActionKind::RecoverZip && *encryption {
608 return Err(invalid());
609 }
610 action.enc(&mut e)?;
611 encryption.enc(&mut e)?;
612 100
613 }
614 Self::Entry(v) => {
615 v.enc(&mut e)?;
616 101
617 }
618 Self::ListEnd {
619 entry_count,
620 list_id,
621 } => {
622 entry_count.enc(&mut e)?;
623 list_id.enc(&mut e)?;
624 102
625 }
626 Self::PasswordRequired {
627 challenge_id,
628 attempt,
629 purpose,
630 } => {
631 challenge_id.enc(&mut e)?;
632 attempt.enc(&mut e)?;
633 purpose.enc(&mut e)?;
634 103
635 }
636 Self::Progress {
637 stage,
638 processed_bytes,
639 total_bytes,
640 completed_entries,
641 } => {
642 stage.enc(&mut e)?;
643 processed_bytes.enc(&mut e)?;
644 total_bytes.enc(&mut e)?;
645 completed_entries.enc(&mut e)?;
646 104
647 }
648 Self::Output {
649 entry_id,
650 relative_name,
651 disposition,
652 } => {
653 entry_id.enc(&mut e)?;
654 relative_name.enc(&mut e)?;
655 disposition.enc(&mut e)?;
656 105
657 }
658 Self::PreviewBegin(info) => {
659 info.enc(&mut e)?;
660 111
661 }
662 Self::PreviewChunk {
663 entry_id,
664 offset,
665 data,
666 } => {
667 if !valid_preview_chunk(*offset, data.len()) {
668 return Err(invalid());
669 }
670 entry_id.enc(&mut e)?;
671 offset.enc(&mut e)?;
672 (data.len() as u32).enc(&mut e)?;
673 e.put(data)?;
674 112
675 }
676 Self::PreviewEnd {
677 entry_id,
678 total_bytes,
679 sha256,
680 } => {
681 if *total_bytes > MAX_PREVIEW_RGBA_BYTES {
682 return Err(invalid());
683 }
684 entry_id.enc(&mut e)?;
685 total_bytes.enc(&mut e)?;
686 sha256.enc(&mut e)?;
687 113
688 }
689 Self::VolumeProblem { reason, volume } => {
690 if !volume.is_basename() {
691 return Err(invalid());
692 }
693 reason.enc(&mut e)?;
694 volume.enc(&mut e)?;
695 114
696 }
697 Self::RecoveryEntry(v) => {
698 v.enc(&mut e)?;
699 115
700 }
701 Self::RecoveryEnd(v) => {
702 v.enc(&mut e)?;
703 116
704 }
705 Self::Terminal(v) => {
706 if v.detail.len() > 4096 {
707 return Err(invalid());
708 }
709 v.enc(&mut e)?;
710 106
711 }
712 Self::CancelAck {
713 request_sequence,
714 status,
715 } => {
716 request_sequence.enc(&mut e)?;
717 status.enc(&mut e)?;
718 107
719 }
720 Self::ConflictRequired {
721 challenge_id,
722 entry_id,
723 relative_name,
724 incoming_size,
725 existing_size,
726 } => {
727 challenge_id.enc(&mut e)?;
728 entry_id.enc(&mut e)?;
729 relative_name.enc(&mut e)?;
730 incoming_size.enc(&mut e)?;
731 existing_size.enc(&mut e)?;
732 108
733 }
734 Self::ConflictResolved {
735 entry_id,
736 relative_name,
737 choice,
738 } => {
739 entry_id.enc(&mut e)?;
740 relative_name.enc(&mut e)?;
741 choice.enc(&mut e)?;
742 109
743 }
744 };
745 Ok((kind, e.bytes))
746 }
747 fn decode(kind: u16, b: &[u8]) -> io::Result<Self> {
748 let mut d = Decoder {
749 bytes: b,
750 at: 0,
751 selection_limit: if kind == 6 {
752 MAX_SELECTION_IDS
753 } else {
754 LEGACY_VECTOR_ITEMS
755 },
756 };
757 let m = match kind {
758 1 => {
759 let start = Start::dec(&mut d)?;
760 if matches!(start.action, Action::Preview { .. }) {
761 return Err(invalid());
762 }
763 Self::Start(start)
764 }
765 2 => {
766 let challenge_id = Wire::dec(&mut d)?;
767 let secret = Secret(Vec::<u8>::dec(&mut d)?);
768 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
769 return Err(invalid());
770 }
771 Self::Password {
772 challenge_id,
773 secret,
774 }
775 }
776 3 => Self::Cancel,
777 4 => {
778 let start = Start::dec(&mut d)?;
779 if !matches!(&start.action, Action::Extract { .. }) {
780 return Err(invalid());
781 }
782 Self::StartInteractive(start)
783 }
784 5 => Self::ConflictReply {
785 challenge_id: Wire::dec(&mut d)?,
786 choice: Wire::dec(&mut d)?,
787 apply_to_remaining: Wire::dec(&mut d)?,
788 },
789 6 => {
790 let start = GuardedStart::dec(&mut d)?;
791 let limit = LEGACY_VECTOR_ITEMS.max(start.ceiling.entries as usize);
792 if !start.valid()
793 || matches!(
794 &start.start.action,
795 Action::Extract { selection: Selection::EntryIds(ids), .. } if ids.len() > limit
796 )
797 {
798 return Err(invalid());
799 }
800 Self::StartGuarded(start)
801 }
802 7 => Self::ResourceReply {
803 challenge_id: Wire::dec(&mut d)?,
804 scope: Wire::dec(&mut d)?,
805 allow: Wire::dec(&mut d)?,
806 },
807 110 => Self::ResourceRequired {
808 challenge_id: Wire::dec(&mut d)?,
809 action: Wire::dec(&mut d)?,
810 scope: Wire::dec(&mut d)?,
811 usage: Wire::dec(&mut d)?,
812 soft_limits: Wire::dec(&mut d)?,
813 ceiling: Wire::dec(&mut d)?,
814 },
815 100 => {
816 let action = Wire::dec(&mut d)?;
817 let encryption = Wire::dec(&mut d)?;
818 if action == ActionKind::RecoverZip && encryption {
819 return Err(invalid());
820 }
821 Self::Accepted { action, encryption }
822 }
823 115 => Self::RecoveryEntry(Wire::dec(&mut d)?),
824 116 => Self::RecoveryEnd(Wire::dec(&mut d)?),
825 101 => Self::Entry(Wire::dec(&mut d)?),
826 102 => Self::ListEnd {
827 entry_count: Wire::dec(&mut d)?,
828 list_id: Wire::dec(&mut d)?,
829 },
830 103 => Self::PasswordRequired {
831 challenge_id: Wire::dec(&mut d)?,
832 attempt: Wire::dec(&mut d)?,
833 purpose: Wire::dec(&mut d)?,
834 },
835 104 => Self::Progress {
836 stage: Wire::dec(&mut d)?,
837 processed_bytes: Wire::dec(&mut d)?,
838 total_bytes: Wire::dec(&mut d)?,
839 completed_entries: Wire::dec(&mut d)?,
840 },
841 105 => Self::Output {
842 entry_id: Wire::dec(&mut d)?,
843 relative_name: Wire::dec(&mut d)?,
844 disposition: Wire::dec(&mut d)?,
845 },
846 111 => Self::PreviewBegin(Wire::dec(&mut d)?),
847 112 => {
848 let entry_id = Wire::dec(&mut d)?;
849 let offset = Wire::dec(&mut d)?;
850 let length = u32::dec(&mut d)? as usize;
851 if !valid_preview_chunk(offset, length) {
852 return Err(invalid());
853 }
854 let bytes = d.take(length)?;
855 let mut data = Vec::new();
856 data.try_reserve_exact(length).map_err(|_| invalid())?;
857 data.extend_from_slice(bytes);
858 Self::PreviewChunk {
859 entry_id,
860 offset,
861 data,
862 }
863 }
864 113 => {
865 let entry_id = Wire::dec(&mut d)?;
866 let total_bytes = u64::dec(&mut d)?;
867 if total_bytes > MAX_PREVIEW_RGBA_BYTES {
868 return Err(invalid());
869 }
870 Self::PreviewEnd {
871 entry_id,
872 total_bytes,
873 sha256: Wire::dec(&mut d)?,
874 }
875 }
876 114 => {
877 let reason = Wire::dec(&mut d)?;
878 let volume = NativePath::dec(&mut d)?;
879 if !volume.is_basename() {
880 return Err(invalid());
881 }
882 Self::VolumeProblem { reason, volume }
883 }
884 106 => {
885 let t = Terminal::dec(&mut d)?;
886 if t.detail.len() > 4096 {
887 return Err(invalid());
888 }
889 Self::Terminal(t)
890 }
891 107 => Self::CancelAck {
892 request_sequence: Wire::dec(&mut d)?,
893 status: Wire::dec(&mut d)?,
894 },
895 108 => Self::ConflictRequired {
896 challenge_id: Wire::dec(&mut d)?,
897 entry_id: Wire::dec(&mut d)?,
898 relative_name: Wire::dec(&mut d)?,
899 incoming_size: Wire::dec(&mut d)?,
900 existing_size: Wire::dec(&mut d)?,
901 },
902 109 => Self::ConflictResolved {
903 entry_id: Wire::dec(&mut d)?,
904 relative_name: Wire::dec(&mut d)?,
905 choice: Wire::dec(&mut d)?,
906 },
907 _ => return Err(invalid()),
908 };
909 if d.at != b.len() {
910 return Err(invalid());
911 }
912 Ok(m)
913 }
914}
915pub struct Reader<R> {
916 input: R,
917 sequence: u64,
918 job: Option<u64>,
919 terminal: bool,
920}
921impl<R: Read> Reader<R> {
922 pub fn new(input: R) -> Self {
923 Self {
924 input,
925 sequence: 0,
926 job: None,
927 terminal: false,
928 }
929 }
930 pub fn read(&mut self) -> io::Result<Option<(u64, u64, Message)>> {
931 let mut h = [0u8; 32];
932 loop {
933 match self.input.read(&mut h[..1]) {
934 Ok(0) => return Ok(None),
935 Ok(_) => break,
936 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
937 Err(e) => return Err(e),
938 }
939 }
940 if self.terminal {
941 return Err(invalid());
942 }
943 self.input.read_exact(&mut h[1..])?;
944 let len = u32::from_le_bytes(h[8..12].try_into().unwrap()) as usize;
945 let job = u64::from_le_bytes(h[16..24].try_into().unwrap());
946 let seq = u64::from_le_bytes(h[24..32].try_into().unwrap());
947 if &h[..4] != b"ZAW1"
948 || h[4..6] != 1u16.to_le_bytes()
949 || h[12..16] != [0; 4]
950 || len > MAX_BODY
951 || job == 0
952 || self.job.is_some_and(|j| j != job)
953 || seq != self.sequence
954 || seq >= MAX_FRAMES
955 {
956 return Err(invalid());
957 }
958 self.job = Some(job);
959 self.sequence += 1;
960 let mut b = zeroize::Zeroizing::new(vec![0; len]);
961 self.input.read_exact(&mut b)?;
962 let message = Message::decode(u16::from_le_bytes(h[6..8].try_into().unwrap()), &b)?;
963 self.terminal = matches!(message, Message::Terminal(_));
964 Ok(Some((job, seq, message)))
965 }
966}
967pub struct Writer<W> {
968 output: W,
969 sequence: u64,
970 job: u64,
971 terminal: bool,
972}
973impl<W: Write> Writer<W> {
974 pub fn new(output: W, job: u64) -> Self {
975 Self {
976 output,
977 sequence: 0,
978 job,
979 terminal: false,
980 }
981 }
982 pub fn send(&mut self, m: &Message) -> io::Result<()> {
983 if self.job == 0 || self.terminal || self.sequence >= MAX_FRAMES {
984 return Err(invalid());
985 }
986 let (kind, b) = m.encode()?;
987 let b = zeroize::Zeroizing::new(b);
988 let mut h = Vec::with_capacity(32);
989 h.extend(b"ZAW1");
990 h.extend(1u16.to_le_bytes());
991 h.extend(kind.to_le_bytes());
992 h.extend((b.len() as u32).to_le_bytes());
993 h.extend(0u32.to_le_bytes());
994 h.extend(self.job.to_le_bytes());
995 h.extend(self.sequence.to_le_bytes());
996 self.output.write_all(&h)?;
997 self.output.write_all(&b)?;
998 self.output.flush()?;
999 self.sequence += 1;
1000 self.terminal = matches!(m, Message::Terminal(_));
1001 Ok(())
1002 }
1003}
1004
1005#[cfg(test)]
1006#[path = "../../../tests/rust-archive-worker/selection_wire.rs"]
1007mod tests;