team-ljyzipelo

공개
679줄20 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;
6fn invalid() -> io::Error {
7 io::Error::new(io::ErrorKind::InvalidData, "invalid worker frame")
8}
9struct Encoder {
10 bytes: Vec<u8>,
11}
12impl Encoder {
13 fn put(&mut self, b: &[u8]) -> io::Result<()> {
14 if self
15 .bytes
16 .len()
17 .checked_add(b.len())
18 .filter(|n| *n <= MAX_BODY)
19 .is_none()
20 {
21 return Err(invalid());
22 }
23 self.bytes.extend_from_slice(b);
24 Ok(())
25 }
26}
27struct Decoder<'a> {
28 bytes: &'a [u8],
29 at: usize,
30}
31impl<'a> Decoder<'a> {
32 fn take(&mut self, n: usize) -> io::Result<&'a [u8]> {
33 let end = self.at.checked_add(n).ok_or_else(invalid)?;
34 let b = self.bytes.get(self.at..end).ok_or_else(invalid)?;
35 self.at = end;
36 Ok(b)
37 }
38}
39trait Wire: Sized {
40 fn enc(&self, e: &mut Encoder) -> io::Result<()>;
41 fn dec(d: &mut Decoder<'_>) -> io::Result<Self>;
42}
43macro_rules! integer { ($($t:ty),*) => { $(impl Wire for $t {
44 fn enc(&self,e:&mut Encoder)->io::Result<()> { e.put(&self.to_le_bytes()) }
45 fn dec(d:&mut Decoder<'_>)->io::Result<Self> { Ok(Self::from_le_bytes(d.take(size_of::<Self>())?.try_into().map_err(|_|invalid())?)) }
46})* }; }
47integer!(u8, u16, u32, u64);
48impl<const N: usize> Wire for [u8; N] {
49 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
50 e.put(self)
51 }
52 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
53 d.take(N)?.try_into().map_err(|_| invalid())
54 }
55}
56impl Wire for bool {
57 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
58 u8::from(*self).enc(e)
59 }
60 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
61 match u8::dec(d)? {
62 0 => Ok(false),
63 1 => Ok(true),
64 _ => Err(invalid()),
65 }
66 }
67}
68impl<T: Wire> Wire for Option<T> {
69 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
70 self.is_some().enc(e)?;
71 if let Some(v) = self {
72 v.enc(e)?;
73 }
74 Ok(())
75 }
76 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
77 if bool::dec(d)? {
78 Ok(Some(T::dec(d)?))
79 } else {
80 Ok(None)
81 }
82 }
83}
84impl<T: Wire> Wire for Vec<T> {
85 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
86 if self.len() > 32768 {
87 return Err(invalid());
88 }
89 (self.len() as u32).enc(e)?;
90 for v in self {
91 v.enc(e)?;
92 }
93 Ok(())
94 }
95 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
96 let n = u32::dec(d)? as usize;
97 if n > 32768 || n > d.bytes.len() - d.at {
98 return Err(invalid());
99 }
100 let mut v = Vec::new();
101 v.try_reserve(n).map_err(|_| invalid())?;
102 for _ in 0..n {
103 v.push(T::dec(d)?);
104 }
105 Ok(v)
106 }
107}
108impl Wire for String {
109 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
110 if self.len() > 32768 {
111 return Err(invalid());
112 }
113 (self.len() as u32).enc(e)?;
114 e.put(self.as_bytes())
115 }
116 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
117 let n = u32::dec(d)? as usize;
118 if n > 32768 {
119 return Err(invalid());
120 }
121 String::from_utf8(d.take(n)?.to_vec()).map_err(|_| invalid())
122 }
123}
124macro_rules! enumeration { ($t:ident {$($v:ident=$n:expr),*$(,)?}) => { impl Wire for $t {
125 fn enc(&self,e:&mut Encoder)->io::Result<()> { (match self {$(Self::$v=>$n,)*} as u8).enc(e) }
126 fn dec(d:&mut Decoder<'_>)->io::Result<Self> { match u8::dec(d)? {$($n=>Ok(Self::$v),)*_=>Err(invalid())} }
127} }; }
128enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3,SevenZip=4});
129enumeration!(Method{Store=0,Deflate=1});
130enumeration!(Encryption{None=0,Aes256=1});
131enumeration!(ActionKind{List=0,Extract=1,CreateZip=2});
132enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3});
133enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5});
134enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3});
135enumeration!(Outcome{Completed=0,Failed=1,Cancelled=2});
136enumeration!(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});
137enumeration!(Publication{None=0,Partial=1,Complete=2,Uncertain=3});
138enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3});
139enumeration!(Cleanup{Complete=0,Failed=1,Unconfirmed=2});
140enumeration!(CancelStatus{Requested=0,AlreadyRequested=1,TooLate=2,Finished=3});
141enumeration!(PasswordPurpose{Decrypt=0,Encrypt=1});
142enumeration!(ConflictChoice{Overwrite=0,Skip=1,Rename=2});
143macro_rules! structure {($t:ident {$($f:ident),*})=>{impl Wire for $t {
144 fn enc(&self,e:&mut Encoder)->io::Result<()> {$(self.$f.enc(e)?;)*Ok(())}
145 fn dec(d:&mut Decoder<'_>)->io::Result<Self> {Ok(Self {$($f:Wire::dec(d)?,)*})}
146}};}
147structure!(Limits {
148 input,
149 output,
150 entries
151});
152structure!(ListId {
153 catalog_version,
154 format,
155 source_object,
156 archive_bytes,
157 archive_sha256
158});
159structure!(Source { path, archive_name });
160structure!(Start { action, limits });
161structure!(GuardedStart {
162 start,
163 ceiling,
164 interactive
165});
166structure!(ResourceScope {
167 output,
168 entries,
169 ratio
170});
171structure!(ResourceUsage {
172 estimated_bytes,
173 actual_bytes,
174 estimated_entries,
175 actual_entries,
176 compressed_bytes,
177 ratio_output_bytes,
178 available_bytes
179});
180structure!(Entry {
181 entry_id,
182 name,
183 kind,
184 size,
185 compressed_size,
186 encrypted
187});
188structure!(Terminal {
189 outcome,
190 error,
191 publication,
192 created_count,
193 retained_partial_count,
194 durability,
195 cleanup,
196 detail
197});
198impl Wire for NativePath {
199 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
200 match self {
201 Self::Unix(v) => {
202 1u8.enc(e)?;
203 v.enc(e)
204 }
205 Self::Windows(v) => {
206 2u8.enc(e)?;
207 v.enc(e)
208 }
209 }
210 }
211 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
212 match u8::dec(d)? {
213 1 => Ok(Self::Unix(Wire::dec(d)?)),
214 2 => Ok(Self::Windows(Wire::dec(d)?)),
215 _ => Err(invalid()),
216 }
217 }
218}
219impl Wire for SourceObject {
220 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
221 match self {
222 Self::Unix { device, inode } => {
223 1u8.enc(e)?;
224 device.enc(e)?;
225 inode.enc(e)
226 }
227 Self::Windows {
228 volume_serial,
229 file_id,
230 } => {
231 2u8.enc(e)?;
232 volume_serial.enc(e)?;
233 file_id.enc(e)
234 }
235 }
236 }
237 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
238 match u8::dec(d)? {
239 1 => Ok(Self::Unix {
240 device: Wire::dec(d)?,
241 inode: Wire::dec(d)?,
242 }),
243 2 => Ok(Self::Windows {
244 volume_serial: Wire::dec(d)?,
245 file_id: Wire::dec(d)?,
246 }),
247 _ => Err(invalid()),
248 }
249 }
250}
251impl Wire for Selection {
252 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
253 match self {
254 Self::All => 0u8.enc(e),
255 Self::EntryIds(ids) => {
256 1u8.enc(e)?;
257 ids.enc(e)
258 }
259 }
260 }
261 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
262 match u8::dec(d)? {
263 0 => Ok(Self::All),
264 1 => Ok(Self::EntryIds(Wire::dec(d)?)),
265 _ => Err(invalid()),
266 }
267 }
268}
269impl Wire for Action {
270 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
271 match self {
272 Self::List { archive } => {
273 0u8.enc(e)?;
274 archive.enc(e)
275 }
276 Self::Extract {
277 archive,
278 destination,
279 selection,
280 list_id,
281 gzip_output_name,
282 } => {
283 1u8.enc(e)?;
284 archive.enc(e)?;
285 destination.enc(e)?;
286 selection.enc(e)?;
287 list_id.enc(e)?;
288 gzip_output_name.enc(e)
289 }
290 Self::CreateZip {
291 sources,
292 output_file,
293 method,
294 encryption,
295 } => {
296 2u8.enc(e)?;
297 sources.enc(e)?;
298 output_file.enc(e)?;
299 method.enc(e)?;
300 encryption.enc(e)
301 }
302 }
303 }
304 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
305 match u8::dec(d)? {
306 0 => Ok(Self::List {
307 archive: Wire::dec(d)?,
308 }),
309 1 => Ok(Self::Extract {
310 archive: Wire::dec(d)?,
311 destination: Wire::dec(d)?,
312 selection: Wire::dec(d)?,
313 list_id: Wire::dec(d)?,
314 gzip_output_name: Wire::dec(d)?,
315 }),
316 2 => Ok(Self::CreateZip {
317 sources: Wire::dec(d)?,
318 output_file: Wire::dec(d)?,
319 method: Wire::dec(d)?,
320 encryption: Wire::dec(d)?,
321 }),
322 _ => Err(invalid()),
323 }
324 }
325}
326impl Message {
327 fn encode(&self) -> io::Result<(u16, Vec<u8>)> {
328 let mut e = Encoder { bytes: Vec::new() };
329 let kind = match self {
330 Self::Start(v) => {
331 v.enc(&mut e)?;
332 1
333 }
334 Self::Password {
335 challenge_id,
336 secret,
337 } => {
338 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
339 return Err(invalid());
340 }
341 challenge_id.enc(&mut e)?;
342 secret.0.enc(&mut e)?;
343 2
344 }
345 Self::Cancel => 3,
346 Self::StartInteractive(v) => {
347 if !matches!(&v.action, Action::Extract { .. }) {
348 return Err(invalid());
349 }
350 v.enc(&mut e)?;
351 4
352 }
353 Self::ConflictReply {
354 challenge_id,
355 choice,
356 apply_to_remaining,
357 } => {
358 challenge_id.enc(&mut e)?;
359 choice.enc(&mut e)?;
360 apply_to_remaining.enc(&mut e)?;
361 5
362 }
363 Self::StartGuarded(v) => {
364 if !v.valid() {
365 return Err(invalid());
366 }
367 v.enc(&mut e)?;
368 6
369 }
370 Self::ResourceReply {
371 challenge_id,
372 scope,
373 allow,
374 } => {
375 challenge_id.enc(&mut e)?;
376 scope.enc(&mut e)?;
377 allow.enc(&mut e)?;
378 7
379 }
380 Self::ResourceRequired {
381 challenge_id,
382 action,
383 scope,
384 usage,
385 soft_limits,
386 ceiling,
387 } => {
388 challenge_id.enc(&mut e)?;
389 action.enc(&mut e)?;
390 scope.enc(&mut e)?;
391 usage.enc(&mut e)?;
392 soft_limits.enc(&mut e)?;
393 ceiling.enc(&mut e)?;
394 110
395 }
396 Self::Accepted { action, encryption } => {
397 action.enc(&mut e)?;
398 encryption.enc(&mut e)?;
399 100
400 }
401 Self::Entry(v) => {
402 v.enc(&mut e)?;
403 101
404 }
405 Self::ListEnd {
406 entry_count,
407 list_id,
408 } => {
409 entry_count.enc(&mut e)?;
410 list_id.enc(&mut e)?;
411 102
412 }
413 Self::PasswordRequired {
414 challenge_id,
415 attempt,
416 purpose,
417 } => {
418 challenge_id.enc(&mut e)?;
419 attempt.enc(&mut e)?;
420 purpose.enc(&mut e)?;
421 103
422 }
423 Self::Progress {
424 stage,
425 processed_bytes,
426 total_bytes,
427 completed_entries,
428 } => {
429 stage.enc(&mut e)?;
430 processed_bytes.enc(&mut e)?;
431 total_bytes.enc(&mut e)?;
432 completed_entries.enc(&mut e)?;
433 104
434 }
435 Self::Output {
436 entry_id,
437 relative_name,
438 disposition,
439 } => {
440 entry_id.enc(&mut e)?;
441 relative_name.enc(&mut e)?;
442 disposition.enc(&mut e)?;
443 105
444 }
445 Self::Terminal(v) => {
446 if v.detail.len() > 4096 {
447 return Err(invalid());
448 }
449 v.enc(&mut e)?;
450 106
451 }
452 Self::CancelAck {
453 request_sequence,
454 status,
455 } => {
456 request_sequence.enc(&mut e)?;
457 status.enc(&mut e)?;
458 107
459 }
460 Self::ConflictRequired {
461 challenge_id,
462 entry_id,
463 relative_name,
464 incoming_size,
465 existing_size,
466 } => {
467 challenge_id.enc(&mut e)?;
468 entry_id.enc(&mut e)?;
469 relative_name.enc(&mut e)?;
470 incoming_size.enc(&mut e)?;
471 existing_size.enc(&mut e)?;
472 108
473 }
474 Self::ConflictResolved {
475 entry_id,
476 relative_name,
477 choice,
478 } => {
479 entry_id.enc(&mut e)?;
480 relative_name.enc(&mut e)?;
481 choice.enc(&mut e)?;
482 109
483 }
484 };
485 Ok((kind, e.bytes))
486 }
487 fn decode(kind: u16, b: &[u8]) -> io::Result<Self> {
488 let mut d = Decoder { bytes: b, at: 0 };
489 let m = match kind {
490 1 => Self::Start(Wire::dec(&mut d)?),
491 2 => {
492 let challenge_id = Wire::dec(&mut d)?;
493 let secret = Secret(Vec::<u8>::dec(&mut d)?);
494 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
495 return Err(invalid());
496 }
497 Self::Password {
498 challenge_id,
499 secret,
500 }
501 }
502 3 => Self::Cancel,
503 4 => {
504 let start = Start::dec(&mut d)?;
505 if !matches!(&start.action, Action::Extract { .. }) {
506 return Err(invalid());
507 }
508 Self::StartInteractive(start)
509 }
510 5 => Self::ConflictReply {
511 challenge_id: Wire::dec(&mut d)?,
512 choice: Wire::dec(&mut d)?,
513 apply_to_remaining: Wire::dec(&mut d)?,
514 },
515 6 => {
516 let start = GuardedStart::dec(&mut d)?;
517 if !start.valid() {
518 return Err(invalid());
519 }
520 Self::StartGuarded(start)
521 }
522 7 => Self::ResourceReply {
523 challenge_id: Wire::dec(&mut d)?,
524 scope: Wire::dec(&mut d)?,
525 allow: Wire::dec(&mut d)?,
526 },
527 110 => Self::ResourceRequired {
528 challenge_id: Wire::dec(&mut d)?,
529 action: Wire::dec(&mut d)?,
530 scope: Wire::dec(&mut d)?,
531 usage: Wire::dec(&mut d)?,
532 soft_limits: Wire::dec(&mut d)?,
533 ceiling: Wire::dec(&mut d)?,
534 },
535 100 => Self::Accepted {
536 action: Wire::dec(&mut d)?,
537 encryption: Wire::dec(&mut d)?,
538 },
539 101 => Self::Entry(Wire::dec(&mut d)?),
540 102 => Self::ListEnd {
541 entry_count: Wire::dec(&mut d)?,
542 list_id: Wire::dec(&mut d)?,
543 },
544 103 => Self::PasswordRequired {
545 challenge_id: Wire::dec(&mut d)?,
546 attempt: Wire::dec(&mut d)?,
547 purpose: Wire::dec(&mut d)?,
548 },
549 104 => Self::Progress {
550 stage: Wire::dec(&mut d)?,
551 processed_bytes: Wire::dec(&mut d)?,
552 total_bytes: Wire::dec(&mut d)?,
553 completed_entries: Wire::dec(&mut d)?,
554 },
555 105 => Self::Output {
556 entry_id: Wire::dec(&mut d)?,
557 relative_name: Wire::dec(&mut d)?,
558 disposition: Wire::dec(&mut d)?,
559 },
560 106 => {
561 let t = Terminal::dec(&mut d)?;
562 if t.detail.len() > 4096 {
563 return Err(invalid());
564 }
565 Self::Terminal(t)
566 }
567 107 => Self::CancelAck {
568 request_sequence: Wire::dec(&mut d)?,
569 status: Wire::dec(&mut d)?,
570 },
571 108 => Self::ConflictRequired {
572 challenge_id: Wire::dec(&mut d)?,
573 entry_id: Wire::dec(&mut d)?,
574 relative_name: Wire::dec(&mut d)?,
575 incoming_size: Wire::dec(&mut d)?,
576 existing_size: Wire::dec(&mut d)?,
577 },
578 109 => Self::ConflictResolved {
579 entry_id: Wire::dec(&mut d)?,
580 relative_name: Wire::dec(&mut d)?,
581 choice: Wire::dec(&mut d)?,
582 },
583 _ => return Err(invalid()),
584 };
585 if d.at != b.len() {
586 return Err(invalid());
587 }
588 Ok(m)
589 }
590}
591pub struct Reader<R> {
592 input: R,
593 sequence: u64,
594 job: Option<u64>,
595 terminal: bool,
596}
597impl<R: Read> Reader<R> {
598 pub fn new(input: R) -> Self {
599 Self {
600 input,
601 sequence: 0,
602 job: None,
603 terminal: false,
604 }
605 }
606 pub fn read(&mut self) -> io::Result<Option<(u64, u64, Message)>> {
607 let mut h = [0u8; 32];
608 loop {
609 match self.input.read(&mut h[..1]) {
610 Ok(0) => return Ok(None),
611 Ok(_) => break,
612 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
613 Err(e) => return Err(e),
614 }
615 }
616 if self.terminal {
617 return Err(invalid());
618 }
619 self.input.read_exact(&mut h[1..])?;
620 let len = u32::from_le_bytes(h[8..12].try_into().unwrap()) as usize;
621 let job = u64::from_le_bytes(h[16..24].try_into().unwrap());
622 let seq = u64::from_le_bytes(h[24..32].try_into().unwrap());
623 if &h[..4] != b"ZAW1"
624 || h[4..6] != 1u16.to_le_bytes()
625 || h[12..16] != [0; 4]
626 || len > MAX_BODY
627 || job == 0
628 || self.job.is_some_and(|j| j != job)
629 || seq != self.sequence
630 || seq >= MAX_FRAMES
631 {
632 return Err(invalid());
633 }
634 self.job = Some(job);
635 self.sequence += 1;
636 let mut b = zeroize::Zeroizing::new(vec![0; len]);
637 self.input.read_exact(&mut b)?;
638 let message = Message::decode(u16::from_le_bytes(h[6..8].try_into().unwrap()), &b)?;
639 self.terminal = matches!(message, Message::Terminal(_));
640 Ok(Some((job, seq, message)))
641 }
642}
643pub struct Writer<W> {
644 output: W,
645 sequence: u64,
646 job: u64,
647 terminal: bool,
648}
649impl<W: Write> Writer<W> {
650 pub fn new(output: W, job: u64) -> Self {
651 Self {
652 output,
653 sequence: 0,
654 job,
655 terminal: false,
656 }
657 }
658 pub fn send(&mut self, m: &Message) -> io::Result<()> {
659 if self.job == 0 || self.terminal || self.sequence >= MAX_FRAMES {
660 return Err(invalid());
661 }
662 let (kind, b) = m.encode()?;
663 let b = zeroize::Zeroizing::new(b);
664 let mut h = Vec::with_capacity(32);
665 h.extend(b"ZAW1");
666 h.extend(1u16.to_le_bytes());
667 h.extend(kind.to_le_bytes());
668 h.extend((b.len() as u32).to_le_bytes());
669 h.extend(0u32.to_le_bytes());
670 h.extend(self.job.to_le_bytes());
671 h.extend(self.sequence.to_le_bytes());
672 self.output.write_all(&h)?;
673 self.output.write_all(&b)?;
674 self.output.flush()?;
675 self.sequence += 1;
676 self.terminal = matches!(m, Message::Terminal(_));
677 Ok(())
678 }
679}