team-ljyzipelo

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