team-ljyzipelo

공개
884줄27 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!(Encryption{None=0,Aes256=1});
141enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3});
142enumeration!(PreviewFormat{Utf8Text=0,Rgba8=1});
143enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3});
144enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5});
145enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3});
146enumeration!(Outcome{Completed=0,Failed=1,Cancelled=2});
147enumeration!(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});
148enumeration!(VolumeProblemReason{FirstVolumeRequired=0,MissingVolume=1,IncompleteSet=2});
149enumeration!(Publication{None=0,Partial=1,Complete=2,Uncertain=3});
150enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3});
151enumeration!(Cleanup{Complete=0,Failed=1,Unconfirmed=2});
152enumeration!(CancelStatus{Requested=0,AlreadyRequested=1,TooLate=2,Finished=3});
153enumeration!(PasswordPurpose{Decrypt=0,Encrypt=1});
154enumeration!(ConflictChoice{Overwrite=0,Skip=1,Rename=2});
155macro_rules! structure {($t:ident {$($f:ident),*})=>{impl Wire for $t {
156 fn enc(&self,e:&mut Encoder)->io::Result<()> {$(self.$f.enc(e)?;)*Ok(())}
157 fn dec(d:&mut Decoder<'_>)->io::Result<Self> {Ok(Self {$($f:Wire::dec(d)?,)*})}
158}};}
159structure!(Limits {
160 input,
161 output,
162 entries
163});
164impl Wire for ListId {
165 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
166 if !self.valid() {
167 return Err(invalid());
168 }
169 self.catalog_version.enc(e)?;
170 self.format.enc(e)?;
171 self.source_object.enc(e)?;
172 self.archive_bytes.enc(e)?;
173 self.archive_sha256.enc(e)
174 }
175 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
176 let id = Self {
177 catalog_version: Wire::dec(d)?,
178 format: Wire::dec(d)?,
179 source_object: Wire::dec(d)?,
180 archive_bytes: Wire::dec(d)?,
181 archive_sha256: Wire::dec(d)?,
182 };
183 if !id.valid() {
184 return Err(invalid());
185 }
186 Ok(id)
187 }
188}
189impl Wire for PreviewInfo {
190 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
191 if !self.valid() {
192 return Err(invalid());
193 }
194 self.entry_id.enc(e)?;
195 self.format.enc(e)?;
196 self.total_bytes.enc(e)?;
197 self.width.enc(e)?;
198 self.height.enc(e)
199 }
200 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
201 let info = Self {
202 entry_id: Wire::dec(d)?,
203 format: Wire::dec(d)?,
204 total_bytes: Wire::dec(d)?,
205 width: Wire::dec(d)?,
206 height: Wire::dec(d)?,
207 };
208 if !info.valid() {
209 return Err(invalid());
210 }
211 Ok(info)
212 }
213}
214structure!(Source { path, archive_name });
215structure!(Start { action, limits });
216structure!(GuardedStart {
217 start,
218 ceiling,
219 interactive
220});
221structure!(ResourceScope {
222 output,
223 entries,
224 ratio
225});
226structure!(ResourceUsage {
227 estimated_bytes,
228 actual_bytes,
229 estimated_entries,
230 actual_entries,
231 compressed_bytes,
232 ratio_output_bytes,
233 available_bytes
234});
235structure!(Entry {
236 entry_id,
237 name,
238 kind,
239 size,
240 compressed_size,
241 encrypted
242});
243structure!(Terminal {
244 outcome,
245 error,
246 publication,
247 created_count,
248 retained_partial_count,
249 durability,
250 cleanup,
251 detail
252});
253impl Wire for NativePath {
254 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
255 match self {
256 Self::Unix(v) => {
257 1u8.enc(e)?;
258 v.enc(e)
259 }
260 Self::Windows(v) => {
261 2u8.enc(e)?;
262 v.enc(e)
263 }
264 }
265 }
266 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
267 match u8::dec(d)? {
268 1 => Ok(Self::Unix(Wire::dec(d)?)),
269 2 => Ok(Self::Windows(Wire::dec(d)?)),
270 _ => Err(invalid()),
271 }
272 }
273}
274impl Wire for SourceObject {
275 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
276 match self {
277 Self::Unix { device, inode } => {
278 1u8.enc(e)?;
279 device.enc(e)?;
280 inode.enc(e)
281 }
282 Self::Windows {
283 volume_serial,
284 file_id,
285 } => {
286 2u8.enc(e)?;
287 volume_serial.enc(e)?;
288 file_id.enc(e)
289 }
290 Self::SplitSevenZip { manifest_sha256 } => {
291 3u8.enc(e)?;
292 manifest_sha256.enc(e)
293 }
294 }
295 }
296 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
297 match u8::dec(d)? {
298 1 => Ok(Self::Unix {
299 device: Wire::dec(d)?,
300 inode: Wire::dec(d)?,
301 }),
302 2 => Ok(Self::Windows {
303 volume_serial: Wire::dec(d)?,
304 file_id: Wire::dec(d)?,
305 }),
306 3 => Ok(Self::SplitSevenZip {
307 manifest_sha256: Wire::dec(d)?,
308 }),
309 _ => Err(invalid()),
310 }
311 }
312}
313pub(crate) fn encode_source_object(value: &SourceObject) -> io::Result<Vec<u8>> {
314 encode_component(value)
315}
316pub(crate) fn encode_native_path(value: &NativePath) -> io::Result<Vec<u8>> {
317 encode_component(value)
318}
319fn encode_component(value: &impl Wire) -> io::Result<Vec<u8>> {
320 let mut encoder = Encoder {
321 bytes: Vec::new(),
322 selection_limit: LEGACY_VECTOR_ITEMS,
323 };
324 value.enc(&mut encoder)?;
325 Ok(encoder.bytes)
326}
327impl Wire for Selection {
328 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
329 match self {
330 Self::All => 0u8.enc(e),
331 Self::EntryIds(ids) => {
332 1u8.enc(e)?;
333 encode_vec(ids, e.selection_limit, e)
334 }
335 }
336 }
337 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
338 match u8::dec(d)? {
339 0 => Ok(Self::All),
340 1 => Ok(Self::EntryIds(decode_vec(d.selection_limit, d)?)),
341 _ => Err(invalid()),
342 }
343 }
344}
345impl Wire for Action {
346 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
347 match self {
348 Self::List { archive } => {
349 0u8.enc(e)?;
350 archive.enc(e)
351 }
352 Self::Extract {
353 archive,
354 destination,
355 selection,
356 list_id,
357 gzip_output_name,
358 } => {
359 1u8.enc(e)?;
360 archive.enc(e)?;
361 destination.enc(e)?;
362 selection.enc(e)?;
363 list_id.enc(e)?;
364 gzip_output_name.enc(e)
365 }
366 Self::CreateZip {
367 sources,
368 output_file,
369 method,
370 encryption,
371 } => {
372 2u8.enc(e)?;
373 sources.enc(e)?;
374 output_file.enc(e)?;
375 method.enc(e)?;
376 encryption.enc(e)
377 }
378 Self::Preview {
379 archive,
380 entry_id,
381 list_id,
382 } => {
383 3u8.enc(e)?;
384 archive.enc(e)?;
385 entry_id.enc(e)?;
386 list_id.enc(e)
387 }
388 }
389 }
390 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
391 match u8::dec(d)? {
392 0 => Ok(Self::List {
393 archive: Wire::dec(d)?,
394 }),
395 1 => Ok(Self::Extract {
396 archive: Wire::dec(d)?,
397 destination: Wire::dec(d)?,
398 selection: Wire::dec(d)?,
399 list_id: Wire::dec(d)?,
400 gzip_output_name: Wire::dec(d)?,
401 }),
402 2 => Ok(Self::CreateZip {
403 sources: Wire::dec(d)?,
404 output_file: Wire::dec(d)?,
405 method: Wire::dec(d)?,
406 encryption: Wire::dec(d)?,
407 }),
408 3 => Ok(Self::Preview {
409 archive: Wire::dec(d)?,
410 entry_id: Wire::dec(d)?,
411 list_id: Wire::dec(d)?,
412 }),
413 _ => Err(invalid()),
414 }
415 }
416}
417fn valid_preview_chunk(offset: u64, length: usize) -> bool {
418 (1..=MAX_PREVIEW_CHUNK_BYTES).contains(&length)
419 && offset
420 .checked_add(length as u64)
421 .is_some_and(|end| end <= MAX_PREVIEW_RGBA_BYTES)
422}
423impl Message {
424 fn encode(&self) -> io::Result<(u16, Vec<u8>)> {
425 let mut e = Encoder {
426 bytes: Vec::new(),
427 selection_limit: LEGACY_VECTOR_ITEMS,
428 };
429 let kind = match self {
430 Self::Start(v) => {
431 if matches!(v.action, Action::Preview { .. }) {
432 return Err(invalid());
433 }
434 v.enc(&mut e)?;
435 1
436 }
437 Self::Password {
438 challenge_id,
439 secret,
440 } => {
441 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
442 return Err(invalid());
443 }
444 challenge_id.enc(&mut e)?;
445 secret.0.enc(&mut e)?;
446 2
447 }
448 Self::Cancel => 3,
449 Self::StartInteractive(v) => {
450 if !matches!(&v.action, Action::Extract { .. }) {
451 return Err(invalid());
452 }
453 v.enc(&mut e)?;
454 4
455 }
456 Self::ConflictReply {
457 challenge_id,
458 choice,
459 apply_to_remaining,
460 } => {
461 challenge_id.enc(&mut e)?;
462 choice.enc(&mut e)?;
463 apply_to_remaining.enc(&mut e)?;
464 5
465 }
466 Self::StartGuarded(v) => {
467 if !v.valid() {
468 return Err(invalid());
469 }
470 e.selection_limit = LEGACY_VECTOR_ITEMS.max(v.ceiling.entries as usize);
471 v.enc(&mut e)?;
472 6
473 }
474 Self::ResourceReply {
475 challenge_id,
476 scope,
477 allow,
478 } => {
479 challenge_id.enc(&mut e)?;
480 scope.enc(&mut e)?;
481 allow.enc(&mut e)?;
482 7
483 }
484 Self::ResourceRequired {
485 challenge_id,
486 action,
487 scope,
488 usage,
489 soft_limits,
490 ceiling,
491 } => {
492 challenge_id.enc(&mut e)?;
493 action.enc(&mut e)?;
494 scope.enc(&mut e)?;
495 usage.enc(&mut e)?;
496 soft_limits.enc(&mut e)?;
497 ceiling.enc(&mut e)?;
498 110
499 }
500 Self::Accepted { action, encryption } => {
501 action.enc(&mut e)?;
502 encryption.enc(&mut e)?;
503 100
504 }
505 Self::Entry(v) => {
506 v.enc(&mut e)?;
507 101
508 }
509 Self::ListEnd {
510 entry_count,
511 list_id,
512 } => {
513 entry_count.enc(&mut e)?;
514 list_id.enc(&mut e)?;
515 102
516 }
517 Self::PasswordRequired {
518 challenge_id,
519 attempt,
520 purpose,
521 } => {
522 challenge_id.enc(&mut e)?;
523 attempt.enc(&mut e)?;
524 purpose.enc(&mut e)?;
525 103
526 }
527 Self::Progress {
528 stage,
529 processed_bytes,
530 total_bytes,
531 completed_entries,
532 } => {
533 stage.enc(&mut e)?;
534 processed_bytes.enc(&mut e)?;
535 total_bytes.enc(&mut e)?;
536 completed_entries.enc(&mut e)?;
537 104
538 }
539 Self::Output {
540 entry_id,
541 relative_name,
542 disposition,
543 } => {
544 entry_id.enc(&mut e)?;
545 relative_name.enc(&mut e)?;
546 disposition.enc(&mut e)?;
547 105
548 }
549 Self::PreviewBegin(info) => {
550 info.enc(&mut e)?;
551 111
552 }
553 Self::PreviewChunk {
554 entry_id,
555 offset,
556 data,
557 } => {
558 if !valid_preview_chunk(*offset, data.len()) {
559 return Err(invalid());
560 }
561 entry_id.enc(&mut e)?;
562 offset.enc(&mut e)?;
563 (data.len() as u32).enc(&mut e)?;
564 e.put(data)?;
565 112
566 }
567 Self::PreviewEnd {
568 entry_id,
569 total_bytes,
570 sha256,
571 } => {
572 if *total_bytes > MAX_PREVIEW_RGBA_BYTES {
573 return Err(invalid());
574 }
575 entry_id.enc(&mut e)?;
576 total_bytes.enc(&mut e)?;
577 sha256.enc(&mut e)?;
578 113
579 }
580 Self::VolumeProblem { reason, volume } => {
581 if !volume.is_basename() {
582 return Err(invalid());
583 }
584 reason.enc(&mut e)?;
585 volume.enc(&mut e)?;
586 114
587 }
588 Self::Terminal(v) => {
589 if v.detail.len() > 4096 {
590 return Err(invalid());
591 }
592 v.enc(&mut e)?;
593 106
594 }
595 Self::CancelAck {
596 request_sequence,
597 status,
598 } => {
599 request_sequence.enc(&mut e)?;
600 status.enc(&mut e)?;
601 107
602 }
603 Self::ConflictRequired {
604 challenge_id,
605 entry_id,
606 relative_name,
607 incoming_size,
608 existing_size,
609 } => {
610 challenge_id.enc(&mut e)?;
611 entry_id.enc(&mut e)?;
612 relative_name.enc(&mut e)?;
613 incoming_size.enc(&mut e)?;
614 existing_size.enc(&mut e)?;
615 108
616 }
617 Self::ConflictResolved {
618 entry_id,
619 relative_name,
620 choice,
621 } => {
622 entry_id.enc(&mut e)?;
623 relative_name.enc(&mut e)?;
624 choice.enc(&mut e)?;
625 109
626 }
627 };
628 Ok((kind, e.bytes))
629 }
630 fn decode(kind: u16, b: &[u8]) -> io::Result<Self> {
631 let mut d = Decoder {
632 bytes: b,
633 at: 0,
634 selection_limit: if kind == 6 {
635 MAX_SELECTION_IDS
636 } else {
637 LEGACY_VECTOR_ITEMS
638 },
639 };
640 let m = match kind {
641 1 => {
642 let start = Start::dec(&mut d)?;
643 if matches!(start.action, Action::Preview { .. }) {
644 return Err(invalid());
645 }
646 Self::Start(start)
647 }
648 2 => {
649 let challenge_id = Wire::dec(&mut d)?;
650 let secret = Secret(Vec::<u8>::dec(&mut d)?);
651 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
652 return Err(invalid());
653 }
654 Self::Password {
655 challenge_id,
656 secret,
657 }
658 }
659 3 => Self::Cancel,
660 4 => {
661 let start = Start::dec(&mut d)?;
662 if !matches!(&start.action, Action::Extract { .. }) {
663 return Err(invalid());
664 }
665 Self::StartInteractive(start)
666 }
667 5 => Self::ConflictReply {
668 challenge_id: Wire::dec(&mut d)?,
669 choice: Wire::dec(&mut d)?,
670 apply_to_remaining: Wire::dec(&mut d)?,
671 },
672 6 => {
673 let start = GuardedStart::dec(&mut d)?;
674 let limit = LEGACY_VECTOR_ITEMS.max(start.ceiling.entries as usize);
675 if !start.valid()
676 || matches!(
677 &start.start.action,
678 Action::Extract { selection: Selection::EntryIds(ids), .. } if ids.len() > limit
679 )
680 {
681 return Err(invalid());
682 }
683 Self::StartGuarded(start)
684 }
685 7 => Self::ResourceReply {
686 challenge_id: Wire::dec(&mut d)?,
687 scope: Wire::dec(&mut d)?,
688 allow: Wire::dec(&mut d)?,
689 },
690 110 => Self::ResourceRequired {
691 challenge_id: Wire::dec(&mut d)?,
692 action: Wire::dec(&mut d)?,
693 scope: Wire::dec(&mut d)?,
694 usage: Wire::dec(&mut d)?,
695 soft_limits: Wire::dec(&mut d)?,
696 ceiling: Wire::dec(&mut d)?,
697 },
698 100 => Self::Accepted {
699 action: Wire::dec(&mut d)?,
700 encryption: Wire::dec(&mut d)?,
701 },
702 101 => Self::Entry(Wire::dec(&mut d)?),
703 102 => Self::ListEnd {
704 entry_count: Wire::dec(&mut d)?,
705 list_id: Wire::dec(&mut d)?,
706 },
707 103 => Self::PasswordRequired {
708 challenge_id: Wire::dec(&mut d)?,
709 attempt: Wire::dec(&mut d)?,
710 purpose: Wire::dec(&mut d)?,
711 },
712 104 => Self::Progress {
713 stage: Wire::dec(&mut d)?,
714 processed_bytes: Wire::dec(&mut d)?,
715 total_bytes: Wire::dec(&mut d)?,
716 completed_entries: Wire::dec(&mut d)?,
717 },
718 105 => Self::Output {
719 entry_id: Wire::dec(&mut d)?,
720 relative_name: Wire::dec(&mut d)?,
721 disposition: Wire::dec(&mut d)?,
722 },
723 111 => Self::PreviewBegin(Wire::dec(&mut d)?),
724 112 => {
725 let entry_id = Wire::dec(&mut d)?;
726 let offset = Wire::dec(&mut d)?;
727 let length = u32::dec(&mut d)? as usize;
728 if !valid_preview_chunk(offset, length) {
729 return Err(invalid());
730 }
731 let bytes = d.take(length)?;
732 let mut data = Vec::new();
733 data.try_reserve_exact(length).map_err(|_| invalid())?;
734 data.extend_from_slice(bytes);
735 Self::PreviewChunk {
736 entry_id,
737 offset,
738 data,
739 }
740 }
741 113 => {
742 let entry_id = Wire::dec(&mut d)?;
743 let total_bytes = u64::dec(&mut d)?;
744 if total_bytes > MAX_PREVIEW_RGBA_BYTES {
745 return Err(invalid());
746 }
747 Self::PreviewEnd {
748 entry_id,
749 total_bytes,
750 sha256: Wire::dec(&mut d)?,
751 }
752 }
753 114 => {
754 let reason = Wire::dec(&mut d)?;
755 let volume = NativePath::dec(&mut d)?;
756 if !volume.is_basename() {
757 return Err(invalid());
758 }
759 Self::VolumeProblem { reason, volume }
760 }
761 106 => {
762 let t = Terminal::dec(&mut d)?;
763 if t.detail.len() > 4096 {
764 return Err(invalid());
765 }
766 Self::Terminal(t)
767 }
768 107 => Self::CancelAck {
769 request_sequence: Wire::dec(&mut d)?,
770 status: Wire::dec(&mut d)?,
771 },
772 108 => Self::ConflictRequired {
773 challenge_id: Wire::dec(&mut d)?,
774 entry_id: Wire::dec(&mut d)?,
775 relative_name: Wire::dec(&mut d)?,
776 incoming_size: Wire::dec(&mut d)?,
777 existing_size: Wire::dec(&mut d)?,
778 },
779 109 => Self::ConflictResolved {
780 entry_id: Wire::dec(&mut d)?,
781 relative_name: Wire::dec(&mut d)?,
782 choice: Wire::dec(&mut d)?,
783 },
784 _ => return Err(invalid()),
785 };
786 if d.at != b.len() {
787 return Err(invalid());
788 }
789 Ok(m)
790 }
791}
792pub struct Reader<R> {
793 input: R,
794 sequence: u64,
795 job: Option<u64>,
796 terminal: bool,
797}
798impl<R: Read> Reader<R> {
799 pub fn new(input: R) -> Self {
800 Self {
801 input,
802 sequence: 0,
803 job: None,
804 terminal: false,
805 }
806 }
807 pub fn read(&mut self) -> io::Result<Option<(u64, u64, Message)>> {
808 let mut h = [0u8; 32];
809 loop {
810 match self.input.read(&mut h[..1]) {
811 Ok(0) => return Ok(None),
812 Ok(_) => break,
813 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
814 Err(e) => return Err(e),
815 }
816 }
817 if self.terminal {
818 return Err(invalid());
819 }
820 self.input.read_exact(&mut h[1..])?;
821 let len = u32::from_le_bytes(h[8..12].try_into().unwrap()) as usize;
822 let job = u64::from_le_bytes(h[16..24].try_into().unwrap());
823 let seq = u64::from_le_bytes(h[24..32].try_into().unwrap());
824 if &h[..4] != b"ZAW1"
825 || h[4..6] != 1u16.to_le_bytes()
826 || h[12..16] != [0; 4]
827 || len > MAX_BODY
828 || job == 0
829 || self.job.is_some_and(|j| j != job)
830 || seq != self.sequence
831 || seq >= MAX_FRAMES
832 {
833 return Err(invalid());
834 }
835 self.job = Some(job);
836 self.sequence += 1;
837 let mut b = zeroize::Zeroizing::new(vec![0; len]);
838 self.input.read_exact(&mut b)?;
839 let message = Message::decode(u16::from_le_bytes(h[6..8].try_into().unwrap()), &b)?;
840 self.terminal = matches!(message, Message::Terminal(_));
841 Ok(Some((job, seq, message)))
842 }
843}
844pub struct Writer<W> {
845 output: W,
846 sequence: u64,
847 job: u64,
848 terminal: bool,
849}
850impl<W: Write> Writer<W> {
851 pub fn new(output: W, job: u64) -> Self {
852 Self {
853 output,
854 sequence: 0,
855 job,
856 terminal: false,
857 }
858 }
859 pub fn send(&mut self, m: &Message) -> io::Result<()> {
860 if self.job == 0 || self.terminal || self.sequence >= MAX_FRAMES {
861 return Err(invalid());
862 }
863 let (kind, b) = m.encode()?;
864 let b = zeroize::Zeroizing::new(b);
865 let mut h = Vec::with_capacity(32);
866 h.extend(b"ZAW1");
867 h.extend(1u16.to_le_bytes());
868 h.extend(kind.to_le_bytes());
869 h.extend((b.len() as u32).to_le_bytes());
870 h.extend(0u32.to_le_bytes());
871 h.extend(self.job.to_le_bytes());
872 h.extend(self.sequence.to_le_bytes());
873 self.output.write_all(&h)?;
874 self.output.write_all(&b)?;
875 self.output.flush()?;
876 self.sequence += 1;
877 self.terminal = matches!(m, Message::Terminal(_));
878 Ok(())
879 }
880}
881
882#[cfg(test)]
883#[path = "../../../tests/rust-archive-worker/selection_wire.rs"]
884mod tests;