team-ljyzipelo

공개
607줄18 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!(Entry {
162 entry_id,
163 name,
164 kind,
165 size,
166 compressed_size,
167 encrypted
168});
169structure!(Terminal {
170 outcome,
171 error,
172 publication,
173 created_count,
174 retained_partial_count,
175 durability,
176 cleanup,
177 detail
178});
179impl Wire for NativePath {
180 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
181 match self {
182 Self::Unix(v) => {
183 1u8.enc(e)?;
184 v.enc(e)
185 }
186 Self::Windows(v) => {
187 2u8.enc(e)?;
188 v.enc(e)
189 }
190 }
191 }
192 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
193 match u8::dec(d)? {
194 1 => Ok(Self::Unix(Wire::dec(d)?)),
195 2 => Ok(Self::Windows(Wire::dec(d)?)),
196 _ => Err(invalid()),
197 }
198 }
199}
200impl Wire for SourceObject {
201 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
202 match self {
203 Self::Unix { device, inode } => {
204 1u8.enc(e)?;
205 device.enc(e)?;
206 inode.enc(e)
207 }
208 Self::Windows {
209 volume_serial,
210 file_id,
211 } => {
212 2u8.enc(e)?;
213 volume_serial.enc(e)?;
214 file_id.enc(e)
215 }
216 }
217 }
218 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
219 match u8::dec(d)? {
220 1 => Ok(Self::Unix {
221 device: Wire::dec(d)?,
222 inode: Wire::dec(d)?,
223 }),
224 2 => Ok(Self::Windows {
225 volume_serial: Wire::dec(d)?,
226 file_id: Wire::dec(d)?,
227 }),
228 _ => Err(invalid()),
229 }
230 }
231}
232impl Wire for Selection {
233 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
234 match self {
235 Self::All => 0u8.enc(e),
236 Self::EntryIds(ids) => {
237 1u8.enc(e)?;
238 ids.enc(e)
239 }
240 }
241 }
242 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
243 match u8::dec(d)? {
244 0 => Ok(Self::All),
245 1 => Ok(Self::EntryIds(Wire::dec(d)?)),
246 _ => Err(invalid()),
247 }
248 }
249}
250impl Wire for Action {
251 fn enc(&self, e: &mut Encoder) -> io::Result<()> {
252 match self {
253 Self::List { archive } => {
254 0u8.enc(e)?;
255 archive.enc(e)
256 }
257 Self::Extract {
258 archive,
259 destination,
260 selection,
261 list_id,
262 gzip_output_name,
263 } => {
264 1u8.enc(e)?;
265 archive.enc(e)?;
266 destination.enc(e)?;
267 selection.enc(e)?;
268 list_id.enc(e)?;
269 gzip_output_name.enc(e)
270 }
271 Self::CreateZip {
272 sources,
273 output_file,
274 method,
275 encryption,
276 } => {
277 2u8.enc(e)?;
278 sources.enc(e)?;
279 output_file.enc(e)?;
280 method.enc(e)?;
281 encryption.enc(e)
282 }
283 }
284 }
285 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
286 match u8::dec(d)? {
287 0 => Ok(Self::List {
288 archive: Wire::dec(d)?,
289 }),
290 1 => Ok(Self::Extract {
291 archive: Wire::dec(d)?,
292 destination: Wire::dec(d)?,
293 selection: Wire::dec(d)?,
294 list_id: Wire::dec(d)?,
295 gzip_output_name: Wire::dec(d)?,
296 }),
297 2 => Ok(Self::CreateZip {
298 sources: Wire::dec(d)?,
299 output_file: Wire::dec(d)?,
300 method: Wire::dec(d)?,
301 encryption: Wire::dec(d)?,
302 }),
303 _ => Err(invalid()),
304 }
305 }
306}
307impl Message {
308 fn encode(&self) -> io::Result<(u16, Vec<u8>)> {
309 let mut e = Encoder { bytes: Vec::new() };
310 let kind = match self {
311 Self::Start(v) => {
312 v.enc(&mut e)?;
313 1
314 }
315 Self::Password {
316 challenge_id,
317 secret,
318 } => {
319 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
320 return Err(invalid());
321 }
322 challenge_id.enc(&mut e)?;
323 secret.0.enc(&mut e)?;
324 2
325 }
326 Self::Cancel => 3,
327 Self::StartInteractive(v) => {
328 if !matches!(&v.action, Action::Extract { .. }) {
329 return Err(invalid());
330 }
331 v.enc(&mut e)?;
332 4
333 }
334 Self::ConflictReply {
335 challenge_id,
336 choice,
337 apply_to_remaining,
338 } => {
339 challenge_id.enc(&mut e)?;
340 choice.enc(&mut e)?;
341 apply_to_remaining.enc(&mut e)?;
342 5
343 }
344 Self::Accepted { action, encryption } => {
345 action.enc(&mut e)?;
346 encryption.enc(&mut e)?;
347 100
348 }
349 Self::Entry(v) => {
350 v.enc(&mut e)?;
351 101
352 }
353 Self::ListEnd {
354 entry_count,
355 list_id,
356 } => {
357 entry_count.enc(&mut e)?;
358 list_id.enc(&mut e)?;
359 102
360 }
361 Self::PasswordRequired {
362 challenge_id,
363 attempt,
364 purpose,
365 } => {
366 challenge_id.enc(&mut e)?;
367 attempt.enc(&mut e)?;
368 purpose.enc(&mut e)?;
369 103
370 }
371 Self::Progress {
372 stage,
373 processed_bytes,
374 total_bytes,
375 completed_entries,
376 } => {
377 stage.enc(&mut e)?;
378 processed_bytes.enc(&mut e)?;
379 total_bytes.enc(&mut e)?;
380 completed_entries.enc(&mut e)?;
381 104
382 }
383 Self::Output {
384 entry_id,
385 relative_name,
386 disposition,
387 } => {
388 entry_id.enc(&mut e)?;
389 relative_name.enc(&mut e)?;
390 disposition.enc(&mut e)?;
391 105
392 }
393 Self::Terminal(v) => {
394 if v.detail.len() > 4096 {
395 return Err(invalid());
396 }
397 v.enc(&mut e)?;
398 106
399 }
400 Self::CancelAck {
401 request_sequence,
402 status,
403 } => {
404 request_sequence.enc(&mut e)?;
405 status.enc(&mut e)?;
406 107
407 }
408 Self::ConflictRequired {
409 challenge_id,
410 entry_id,
411 relative_name,
412 incoming_size,
413 existing_size,
414 } => {
415 challenge_id.enc(&mut e)?;
416 entry_id.enc(&mut e)?;
417 relative_name.enc(&mut e)?;
418 incoming_size.enc(&mut e)?;
419 existing_size.enc(&mut e)?;
420 108
421 }
422 Self::ConflictResolved {
423 entry_id,
424 relative_name,
425 choice,
426 } => {
427 entry_id.enc(&mut e)?;
428 relative_name.enc(&mut e)?;
429 choice.enc(&mut e)?;
430 109
431 }
432 };
433 Ok((kind, e.bytes))
434 }
435 fn decode(kind: u16, b: &[u8]) -> io::Result<Self> {
436 let mut d = Decoder { bytes: b, at: 0 };
437 let m = match kind {
438 1 => Self::Start(Wire::dec(&mut d)?),
439 2 => {
440 let challenge_id = Wire::dec(&mut d)?;
441 let secret = Secret(Vec::<u8>::dec(&mut d)?);
442 if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() {
443 return Err(invalid());
444 }
445 Self::Password {
446 challenge_id,
447 secret,
448 }
449 }
450 3 => Self::Cancel,
451 4 => {
452 let start = Start::dec(&mut d)?;
453 if !matches!(&start.action, Action::Extract { .. }) {
454 return Err(invalid());
455 }
456 Self::StartInteractive(start)
457 }
458 5 => Self::ConflictReply {
459 challenge_id: Wire::dec(&mut d)?,
460 choice: Wire::dec(&mut d)?,
461 apply_to_remaining: Wire::dec(&mut d)?,
462 },
463 100 => Self::Accepted {
464 action: Wire::dec(&mut d)?,
465 encryption: Wire::dec(&mut d)?,
466 },
467 101 => Self::Entry(Wire::dec(&mut d)?),
468 102 => Self::ListEnd {
469 entry_count: Wire::dec(&mut d)?,
470 list_id: Wire::dec(&mut d)?,
471 },
472 103 => Self::PasswordRequired {
473 challenge_id: Wire::dec(&mut d)?,
474 attempt: Wire::dec(&mut d)?,
475 purpose: Wire::dec(&mut d)?,
476 },
477 104 => Self::Progress {
478 stage: Wire::dec(&mut d)?,
479 processed_bytes: Wire::dec(&mut d)?,
480 total_bytes: Wire::dec(&mut d)?,
481 completed_entries: Wire::dec(&mut d)?,
482 },
483 105 => Self::Output {
484 entry_id: Wire::dec(&mut d)?,
485 relative_name: Wire::dec(&mut d)?,
486 disposition: Wire::dec(&mut d)?,
487 },
488 106 => {
489 let t = Terminal::dec(&mut d)?;
490 if t.detail.len() > 4096 {
491 return Err(invalid());
492 }
493 Self::Terminal(t)
494 }
495 107 => Self::CancelAck {
496 request_sequence: Wire::dec(&mut d)?,
497 status: Wire::dec(&mut d)?,
498 },
499 108 => Self::ConflictRequired {
500 challenge_id: Wire::dec(&mut d)?,
501 entry_id: Wire::dec(&mut d)?,
502 relative_name: Wire::dec(&mut d)?,
503 incoming_size: Wire::dec(&mut d)?,
504 existing_size: Wire::dec(&mut d)?,
505 },
506 109 => Self::ConflictResolved {
507 entry_id: Wire::dec(&mut d)?,
508 relative_name: Wire::dec(&mut d)?,
509 choice: Wire::dec(&mut d)?,
510 },
511 _ => return Err(invalid()),
512 };
513 if d.at != b.len() {
514 return Err(invalid());
515 }
516 Ok(m)
517 }
518}
519pub struct Reader<R> {
520 input: R,
521 sequence: u64,
522 job: Option<u64>,
523 terminal: bool,
524}
525impl<R: Read> Reader<R> {
526 pub fn new(input: R) -> Self {
527 Self {
528 input,
529 sequence: 0,
530 job: None,
531 terminal: false,
532 }
533 }
534 pub fn read(&mut self) -> io::Result<Option<(u64, u64, Message)>> {
535 let mut h = [0u8; 32];
536 loop {
537 match self.input.read(&mut h[..1]) {
538 Ok(0) => return Ok(None),
539 Ok(_) => break,
540 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
541 Err(e) => return Err(e),
542 }
543 }
544 if self.terminal {
545 return Err(invalid());
546 }
547 self.input.read_exact(&mut h[1..])?;
548 let len = u32::from_le_bytes(h[8..12].try_into().unwrap()) as usize;
549 let job = u64::from_le_bytes(h[16..24].try_into().unwrap());
550 let seq = u64::from_le_bytes(h[24..32].try_into().unwrap());
551 if &h[..4] != b"ZAW1"
552 || h[4..6] != 1u16.to_le_bytes()
553 || h[12..16] != [0; 4]
554 || len > MAX_BODY
555 || job == 0
556 || self.job.is_some_and(|j| j != job)
557 || seq != self.sequence
558 || seq >= MAX_FRAMES
559 {
560 return Err(invalid());
561 }
562 self.job = Some(job);
563 self.sequence += 1;
564 let mut b = zeroize::Zeroizing::new(vec![0; len]);
565 self.input.read_exact(&mut b)?;
566 let message = Message::decode(u16::from_le_bytes(h[6..8].try_into().unwrap()), &b)?;
567 self.terminal = matches!(message, Message::Terminal(_));
568 Ok(Some((job, seq, message)))
569 }
570}
571pub struct Writer<W> {
572 output: W,
573 sequence: u64,
574 job: u64,
575 terminal: bool,
576}
577impl<W: Write> Writer<W> {
578 pub fn new(output: W, job: u64) -> Self {
579 Self {
580 output,
581 sequence: 0,
582 job,
583 terminal: false,
584 }
585 }
586 pub fn send(&mut self, m: &Message) -> io::Result<()> {
587 if self.job == 0 || self.terminal || self.sequence >= MAX_FRAMES {
588 return Err(invalid());
589 }
590 let (kind, b) = m.encode()?;
591 let b = zeroize::Zeroizing::new(b);
592 let mut h = Vec::with_capacity(32);
593 h.extend(b"ZAW1");
594 h.extend(1u16.to_le_bytes());
595 h.extend(kind.to_le_bytes());
596 h.extend((b.len() as u32).to_le_bytes());
597 h.extend(0u32.to_le_bytes());
598 h.extend(self.job.to_le_bytes());
599 h.extend(self.sequence.to_le_bytes());
600 self.output.write_all(&h)?;
601 self.output.write_all(&b)?;
602 self.output.flush()?;
603 self.sequence += 1;
604 self.terminal = matches!(m, Message::Terminal(_));
605 Ok(())
606 }
607}