team-ljyzipelo

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