team-ljyzipelo

공개
870줄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}
313impl Wire for Selection {
314 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
315 match self {
316 Self::All => 0u8.enc(e),
317 Self::EntryIds(ids) => {
318 1u8.enc(e)?;
319 encode_vec(ids, e.selection_limit, e)
320 }
321 }
322 }
323 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
324 match u8::dec(d)? {
325 0 => Ok(Self::All),
326 1 => Ok(Self::EntryIds(decode_vec(d.selection_limit, d)?)),
327 _ => Err(invalid()),
328 }
329 }
330}
331impl Wire for Action {
332 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
333 match self {
334 Self::List { archive } => {
335 0u8.enc(e)?;
336 archive.enc(e)
337 }
338 Self::Extract {
339 archive,
340 destination,
341 selection,
342 list_id,
343 gzip_output_name,
344 } => {
345 1u8.enc(e)?;
346 archive.enc(e)?;
347 destination.enc(e)?;
348 selection.enc(e)?;
349 list_id.enc(e)?;
350 gzip_output_name.enc(e)
351 }
352 Self::CreateZip {
353 sources,
354 output_file,
355 method,
356 encryption,
357 } => {
358 2u8.enc(e)?;
359 sources.enc(e)?;
360 output_file.enc(e)?;
361 method.enc(e)?;
362 encryption.enc(e)
363 }
364 Self::Preview {
365 archive,
366 entry_id,
367 list_id,
368 } => {
369 3u8.enc(e)?;
370 archive.enc(e)?;
371 entry_id.enc(e)?;
372 list_id.enc(e)
373 }
374 }
375 }
376 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
377 match u8::dec(d)? {
378 0 => Ok(Self::List {
379 archive: Wire::dec(d)?,
380 }),
381 1 => Ok(Self::Extract {
382 archive: Wire::dec(d)?,
383 destination: Wire::dec(d)?,
384 selection: Wire::dec(d)?,
385 list_id: Wire::dec(d)?,
386 gzip_output_name: Wire::dec(d)?,
387 }),
388 2 => Ok(Self::CreateZip {
389 sources: Wire::dec(d)?,
390 output_file: Wire::dec(d)?,
391 method: Wire::dec(d)?,
392 encryption: Wire::dec(d)?,
393 }),
394 3 => Ok(Self::Preview {
395 archive: Wire::dec(d)?,
396 entry_id: Wire::dec(d)?,
397 list_id: Wire::dec(d)?,
398 }),
399 _ => Err(invalid()),
400 }
401 }
402}
403fn valid_preview_chunk(offset: u64, length: usize) -> bool {
404 (1..=MAX_PREVIEW_CHUNK_BYTES).contains(&length)
405 && offset
406 .checked_add(length as u64)
407 .is_some_and(|end| end <= MAX_PREVIEW_RGBA_BYTES)
408}
409impl Message {
410 fn encode(&self) -> io::Result<(u16, Vec<u8>)> {
411 let mut e = Encoder {
412 bytes: Vec::new(),
413 selection_limit: LEGACY_VECTOR_ITEMS,
414 };
415 let kind = match self {
416 Self::Start(v) => {
417 if matches!(v.action, Action::Preview { .. }) {
418 return Err(invalid());
419 }
420 v.enc(&mut e)?;
421 1
422 }
423 Self::Password {
424 challenge_id,
425 secret,
426 } => {
427 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
428 return Err(invalid());
429 }
430 challenge_id.enc(&mut e)?;
431 secret.0.enc(&mut e)?;
432 2
433 }
434 Self::Cancel => 3,
435 Self::StartInteractive(v) => {
436 if !matches!(&v.action, Action::Extract { .. }) {
437 return Err(invalid());
438 }
439 v.enc(&mut e)?;
440 4
441 }
442 Self::ConflictReply {
443 challenge_id,
444 choice,
445 apply_to_remaining,
446 } => {
447 challenge_id.enc(&mut e)?;
448 choice.enc(&mut e)?;
449 apply_to_remaining.enc(&mut e)?;
450 5
451 }
452 Self::StartGuarded(v) => {
453 if !v.valid() {
454 return Err(invalid());
455 }
456 e.selection_limit = LEGACY_VECTOR_ITEMS.max(v.ceiling.entries as usize);
457 v.enc(&mut e)?;
458 6
459 }
460 Self::ResourceReply {
461 challenge_id,
462 scope,
463 allow,
464 } => {
465 challenge_id.enc(&mut e)?;
466 scope.enc(&mut e)?;
467 allow.enc(&mut e)?;
468 7
469 }
470 Self::ResourceRequired {
471 challenge_id,
472 action,
473 scope,
474 usage,
475 soft_limits,
476 ceiling,
477 } => {
478 challenge_id.enc(&mut e)?;
479 action.enc(&mut e)?;
480 scope.enc(&mut e)?;
481 usage.enc(&mut e)?;
482 soft_limits.enc(&mut e)?;
483 ceiling.enc(&mut e)?;
484 110
485 }
486 Self::Accepted { action, encryption } => {
487 action.enc(&mut e)?;
488 encryption.enc(&mut e)?;
489 100
490 }
491 Self::Entry(v) => {
492 v.enc(&mut e)?;
493 101
494 }
495 Self::ListEnd {
496 entry_count,
497 list_id,
498 } => {
499 entry_count.enc(&mut e)?;
500 list_id.enc(&mut e)?;
501 102
502 }
503 Self::PasswordRequired {
504 challenge_id,
505 attempt,
506 purpose,
507 } => {
508 challenge_id.enc(&mut e)?;
509 attempt.enc(&mut e)?;
510 purpose.enc(&mut e)?;
511 103
512 }
513 Self::Progress {
514 stage,
515 processed_bytes,
516 total_bytes,
517 completed_entries,
518 } => {
519 stage.enc(&mut e)?;
520 processed_bytes.enc(&mut e)?;
521 total_bytes.enc(&mut e)?;
522 completed_entries.enc(&mut e)?;
523 104
524 }
525 Self::Output {
526 entry_id,
527 relative_name,
528 disposition,
529 } => {
530 entry_id.enc(&mut e)?;
531 relative_name.enc(&mut e)?;
532 disposition.enc(&mut e)?;
533 105
534 }
535 Self::PreviewBegin(info) => {
536 info.enc(&mut e)?;
537 111
538 }
539 Self::PreviewChunk {
540 entry_id,
541 offset,
542 data,
543 } => {
544 if !valid_preview_chunk(*offset, data.len()) {
545 return Err(invalid());
546 }
547 entry_id.enc(&mut e)?;
548 offset.enc(&mut e)?;
549 (data.len() as u32).enc(&mut e)?;
550 e.put(data)?;
551 112
552 }
553 Self::PreviewEnd {
554 entry_id,
555 total_bytes,
556 sha256,
557 } => {
558 if *total_bytes > MAX_PREVIEW_RGBA_BYTES {
559 return Err(invalid());
560 }
561 entry_id.enc(&mut e)?;
562 total_bytes.enc(&mut e)?;
563 sha256.enc(&mut e)?;
564 113
565 }
566 Self::VolumeProblem { reason, volume } => {
567 if !volume.is_basename() {
568 return Err(invalid());
569 }
570 reason.enc(&mut e)?;
571 volume.enc(&mut e)?;
572 114
573 }
574 Self::Terminal(v) => {
575 if v.detail.len() > 4096 {
576 return Err(invalid());
577 }
578 v.enc(&mut e)?;
579 106
580 }
581 Self::CancelAck {
582 request_sequence,
583 status,
584 } => {
585 request_sequence.enc(&mut e)?;
586 status.enc(&mut e)?;
587 107
588 }
589 Self::ConflictRequired {
590 challenge_id,
591 entry_id,
592 relative_name,
593 incoming_size,
594 existing_size,
595 } => {
596 challenge_id.enc(&mut e)?;
597 entry_id.enc(&mut e)?;
598 relative_name.enc(&mut e)?;
599 incoming_size.enc(&mut e)?;
600 existing_size.enc(&mut e)?;
601 108
602 }
603 Self::ConflictResolved {
604 entry_id,
605 relative_name,
606 choice,
607 } => {
608 entry_id.enc(&mut e)?;
609 relative_name.enc(&mut e)?;
610 choice.enc(&mut e)?;
611 109
612 }
613 };
614 Ok((kind, e.bytes))
615 }
616 fn decode(kind: u16, b: &[u8]) -> io::Result<Self> {
617 let mut d = Decoder {
618 bytes: b,
619 at: 0,
620 selection_limit: if kind == 6 {
621 MAX_SELECTION_IDS
622 } else {
623 LEGACY_VECTOR_ITEMS
624 },
625 };
626 let m = match kind {
627 1 => {
628 let start = Start::dec(&mut d)?;
629 if matches!(start.action, Action::Preview { .. }) {
630 return Err(invalid());
631 }
632 Self::Start(start)
633 }
634 2 => {
635 let challenge_id = Wire::dec(&mut d)?;
636 let secret = Secret(Vec::<u8>::dec(&mut d)?);
637 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
638 return Err(invalid());
639 }
640 Self::Password {
641 challenge_id,
642 secret,
643 }
644 }
645 3 => Self::Cancel,
646 4 => {
647 let start = Start::dec(&mut d)?;
648 if !matches!(&start.action, Action::Extract { .. }) {
649 return Err(invalid());
650 }
651 Self::StartInteractive(start)
652 }
653 5 => Self::ConflictReply {
654 challenge_id: Wire::dec(&mut d)?,
655 choice: Wire::dec(&mut d)?,
656 apply_to_remaining: Wire::dec(&mut d)?,
657 },
658 6 => {
659 let start = GuardedStart::dec(&mut d)?;
660 let limit = LEGACY_VECTOR_ITEMS.max(start.ceiling.entries as usize);
661 if !start.valid()
662 || matches!(
663 &start.start.action,
664 Action::Extract { selection: Selection::EntryIds(ids), .. } if ids.len() > limit
665 )
666 {
667 return Err(invalid());
668 }
669 Self::StartGuarded(start)
670 }
671 7 => Self::ResourceReply {
672 challenge_id: Wire::dec(&mut d)?,
673 scope: Wire::dec(&mut d)?,
674 allow: Wire::dec(&mut d)?,
675 },
676 110 => Self::ResourceRequired {
677 challenge_id: Wire::dec(&mut d)?,
678 action: Wire::dec(&mut d)?,
679 scope: Wire::dec(&mut d)?,
680 usage: Wire::dec(&mut d)?,
681 soft_limits: Wire::dec(&mut d)?,
682 ceiling: Wire::dec(&mut d)?,
683 },
684 100 => Self::Accepted {
685 action: Wire::dec(&mut d)?,
686 encryption: Wire::dec(&mut d)?,
687 },
688 101 => Self::Entry(Wire::dec(&mut d)?),
689 102 => Self::ListEnd {
690 entry_count: Wire::dec(&mut d)?,
691 list_id: Wire::dec(&mut d)?,
692 },
693 103 => Self::PasswordRequired {
694 challenge_id: Wire::dec(&mut d)?,
695 attempt: Wire::dec(&mut d)?,
696 purpose: Wire::dec(&mut d)?,
697 },
698 104 => Self::Progress {
699 stage: Wire::dec(&mut d)?,
700 processed_bytes: Wire::dec(&mut d)?,
701 total_bytes: Wire::dec(&mut d)?,
702 completed_entries: Wire::dec(&mut d)?,
703 },
704 105 => Self::Output {
705 entry_id: Wire::dec(&mut d)?,
706 relative_name: Wire::dec(&mut d)?,
707 disposition: Wire::dec(&mut d)?,
708 },
709 111 => Self::PreviewBegin(Wire::dec(&mut d)?),
710 112 => {
711 let entry_id = Wire::dec(&mut d)?;
712 let offset = Wire::dec(&mut d)?;
713 let length = u32::dec(&mut d)? as usize;
714 if !valid_preview_chunk(offset, length) {
715 return Err(invalid());
716 }
717 let bytes = d.take(length)?;
718 let mut data = Vec::new();
719 data.try_reserve_exact(length).map_err(|_| invalid())?;
720 data.extend_from_slice(bytes);
721 Self::PreviewChunk {
722 entry_id,
723 offset,
724 data,
725 }
726 }
727 113 => {
728 let entry_id = Wire::dec(&mut d)?;
729 let total_bytes = u64::dec(&mut d)?;
730 if total_bytes > MAX_PREVIEW_RGBA_BYTES {
731 return Err(invalid());
732 }
733 Self::PreviewEnd {
734 entry_id,
735 total_bytes,
736 sha256: Wire::dec(&mut d)?,
737 }
738 }
739 114 => {
740 let reason = Wire::dec(&mut d)?;
741 let volume = NativePath::dec(&mut d)?;
742 if !volume.is_basename() {
743 return Err(invalid());
744 }
745 Self::VolumeProblem { reason, volume }
746 }
747 106 => {
748 let t = Terminal::dec(&mut d)?;
749 if t.detail.len() > 4096 {
750 return Err(invalid());
751 }
752 Self::Terminal(t)
753 }
754 107 => Self::CancelAck {
755 request_sequence: Wire::dec(&mut d)?,
756 status: Wire::dec(&mut d)?,
757 },
758 108 => Self::ConflictRequired {
759 challenge_id: Wire::dec(&mut d)?,
760 entry_id: Wire::dec(&mut d)?,
761 relative_name: Wire::dec(&mut d)?,
762 incoming_size: Wire::dec(&mut d)?,
763 existing_size: Wire::dec(&mut d)?,
764 },
765 109 => Self::ConflictResolved {
766 entry_id: Wire::dec(&mut d)?,
767 relative_name: Wire::dec(&mut d)?,
768 choice: Wire::dec(&mut d)?,
769 },
770 _ => return Err(invalid()),
771 };
772 if d.at != b.len() {
773 return Err(invalid());
774 }
775 Ok(m)
776 }
777}
778pub struct Reader<R> {
779 input: R,
780 sequence: u64,
781 job: Option<u64>,
782 terminal: bool,
783}
784impl<R: Read> Reader<R> {
785 pub fn new(input: R) -> Self {
786 Self {
787 input,
788 sequence: 0,
789 job: None,
790 terminal: false,
791 }
792 }
793 pub fn read(&mut self) -> io::Result<Option<(u64, u64, Message)>> {
794 let mut h = [0u8; 32];
795 loop {
796 match self.input.read(&mut h[..1]) {
797 Ok(0) => return Ok(None),
798 Ok(_) => break,
799 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
800 Err(e) => return Err(e),
801 }
802 }
803 if self.terminal {
804 return Err(invalid());
805 }
806 self.input.read_exact(&mut h[1..])?;
807 let len = u32::from_le_bytes(h[8..12].try_into().unwrap()) as usize;
808 let job = u64::from_le_bytes(h[16..24].try_into().unwrap());
809 let seq = u64::from_le_bytes(h[24..32].try_into().unwrap());
810 if &h[..4] != b"ZAW1"
811 || h[4..6] != 1u16.to_le_bytes()
812 || h[12..16] != [0; 4]
813 || len > MAX_BODY
814 || job == 0
815 || self.job.is_some_and(|j| j != job)
816 || seq != self.sequence
817 || seq >= MAX_FRAMES
818 {
819 return Err(invalid());
820 }
821 self.job = Some(job);
822 self.sequence += 1;
823 let mut b = zeroize::Zeroizing::new(vec![0; len]);
824 self.input.read_exact(&mut b)?;
825 let message = Message::decode(u16::from_le_bytes(h[6..8].try_into().unwrap()), &b)?;
826 self.terminal = matches!(message, Message::Terminal(_));
827 Ok(Some((job, seq, message)))
828 }
829}
830pub struct Writer<W> {
831 output: W,
832 sequence: u64,
833 job: u64,
834 terminal: bool,
835}
836impl<W: Write> Writer<W> {
837 pub fn new(output: W, job: u64) -> Self {
838 Self {
839 output,
840 sequence: 0,
841 job,
842 terminal: false,
843 }
844 }
845 pub fn send(&mut self, m: &Message) -> io::Result<()> {
846 if self.job == 0 || self.terminal || self.sequence >= MAX_FRAMES {
847 return Err(invalid());
848 }
849 let (kind, b) = m.encode()?;
850 let b = zeroize::Zeroizing::new(b);
851 let mut h = Vec::with_capacity(32);
852 h.extend(b"ZAW1");
853 h.extend(1u16.to_le_bytes());
854 h.extend(kind.to_le_bytes());
855 h.extend((b.len() as u32).to_le_bytes());
856 h.extend(0u32.to_le_bytes());
857 h.extend(self.job.to_le_bytes());
858 h.extend(self.sequence.to_le_bytes());
859 self.output.write_all(&h)?;
860 self.output.write_all(&b)?;
861 self.output.flush()?;
862 self.sequence += 1;
863 self.terminal = matches!(m, Message::Terminal(_));
864 Ok(())
865 }
866}
867
868#[cfg(test)]
869#[path = "../../../tests/rust-archive-worker/selection_wire.rs"]
870mod tests;