| 1 | use crate::protocol::*; |
| 2 | use std::io::{self, Read, Write}; |
| 3 | |
| 4 | pub const MAX_BODY: usize = 1_048_576; |
| 5 | pub const MAX_FRAMES: u64 = 1_000_000; |
| 6 | fn invalid() -> io::Error { |
| 7 | io::Error::new(io::ErrorKind::InvalidData, "invalid worker frame") |
| 8 | } |
| 9 | struct Encoder { |
| 10 | bytes: Vec<u8>, |
| 11 | } |
| 12 | impl 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 | } |
| 27 | struct Decoder<'a> { |
| 28 | bytes: &'a [u8], |
| 29 | at: usize, |
| 30 | } |
| 31 | impl<'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 | } |
| 39 | trait Wire: Sized { |
| 40 | fn enc(&self, e: &mut Encoder) -> io::Result<()>; |
| 41 | fn dec(d: &mut Decoder<'_>) -> io::Result<Self>; |
| 42 | } |
| 43 | macro_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 | })* }; } |
| 47 | integer!(u8, u16, u32, u64); |
| 48 | impl<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 | } |
| 56 | impl 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 | } |
| 68 | impl<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 | } |
| 84 | impl<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 | } |
| 108 | impl 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 | } |
| 124 | macro_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 | } }; } |
| 128 | enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3}); |
| 129 | enumeration!(Method{Store=0,Deflate=1}); |
| 130 | enumeration!(Encryption{None=0,Aes256=1}); |
| 131 | enumeration!(ActionKind{List=0,Extract=1,CreateZip=2}); |
| 132 | enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3}); |
| 133 | enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5}); |
| 134 | enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3}); |
| 135 | enumeration!(Outcome{Completed=0,Failed=1,Cancelled=2}); |
| 136 | enumeration!(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}); |
| 137 | enumeration!(Publication{None=0,Partial=1,Complete=2,Uncertain=3}); |
| 138 | enumeration!(Durability{NotApplicable=0,Synced=1,Unconfirmed=2,Failed=3}); |
| 139 | enumeration!(Cleanup{Complete=0,Failed=1,Unconfirmed=2}); |
| 140 | enumeration!(CancelStatus{Requested=0,AlreadyRequested=1,TooLate=2,Finished=3}); |
| 141 | enumeration!(PasswordPurpose{Decrypt=0,Encrypt=1}); |
| 142 | macro_rules! structure {($t:ident {$($f:ident),*})=>{impl Wire for $t { |
| 143 | fn enc(&self,e:&mut Encoder)->io::Result<()> {$(self.$f.enc(e)?;)*Ok(())} |
| 144 | fn dec(d:&mut Decoder<'_>)->io::Result<Self> {Ok(Self {$($f:Wire::dec(d)?,)*})} |
| 145 | }};} |
| 146 | structure!(Limits { |
| 147 | input, |
| 148 | output, |
| 149 | entries |
| 150 | }); |
| 151 | structure!(ListId { |
| 152 | catalog_version, |
| 153 | format, |
| 154 | source_object, |
| 155 | archive_bytes, |
| 156 | archive_sha256 |
| 157 | }); |
| 158 | structure!(Source { path, archive_name }); |
| 159 | structure!(Start { action, limits }); |
| 160 | structure!(Entry { |
| 161 | entry_id, |
| 162 | name, |
| 163 | kind, |
| 164 | size, |
| 165 | compressed_size, |
| 166 | encrypted |
| 167 | }); |
| 168 | structure!(Terminal { |
| 169 | outcome, |
| 170 | error, |
| 171 | publication, |
| 172 | created_count, |
| 173 | retained_partial_count, |
| 174 | durability, |
| 175 | cleanup, |
| 176 | detail |
| 177 | }); |
| 178 | impl Wire for NativePath { |
| 179 | fn enc(&self, e: &mut Encoder) -> io::Result<()> { |
| 180 | match self { |
| 181 | Self::Unix(v) => { |
| 182 | 1u8.enc(e)?; |
| 183 | v.enc(e) |
| 184 | } |
| 185 | Self::Windows(v) => { |
| 186 | 2u8.enc(e)?; |
| 187 | v.enc(e) |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { |
| 192 | match u8::dec(d)? { |
| 193 | 1 => Ok(Self::Unix(Wire::dec(d)?)), |
| 194 | 2 => Ok(Self::Windows(Wire::dec(d)?)), |
| 195 | _ => Err(invalid()), |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | impl Wire for SourceObject { |
| 200 | fn enc(&self, e: &mut Encoder) -> io::Result<()> { |
| 201 | match self { |
| 202 | Self::Unix { device, inode } => { |
| 203 | 1u8.enc(e)?; |
| 204 | device.enc(e)?; |
| 205 | inode.enc(e) |
| 206 | } |
| 207 | Self::Windows { |
| 208 | volume_serial, |
| 209 | file_id, |
| 210 | } => { |
| 211 | 2u8.enc(e)?; |
| 212 | volume_serial.enc(e)?; |
| 213 | file_id.enc(e) |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { |
| 218 | match u8::dec(d)? { |
| 219 | 1 => Ok(Self::Unix { |
| 220 | device: Wire::dec(d)?, |
| 221 | inode: Wire::dec(d)?, |
| 222 | }), |
| 223 | 2 => Ok(Self::Windows { |
| 224 | volume_serial: Wire::dec(d)?, |
| 225 | file_id: Wire::dec(d)?, |
| 226 | }), |
| 227 | _ => Err(invalid()), |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | impl Wire for Selection { |
| 232 | fn enc(&self, e: &mut Encoder) -> io::Result<()> { |
| 233 | match self { |
| 234 | Self::All => 0u8.enc(e), |
| 235 | Self::EntryIds(ids) => { |
| 236 | 1u8.enc(e)?; |
| 237 | ids.enc(e) |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { |
| 242 | match u8::dec(d)? { |
| 243 | 0 => Ok(Self::All), |
| 244 | 1 => Ok(Self::EntryIds(Wire::dec(d)?)), |
| 245 | _ => Err(invalid()), |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | impl Wire for Action { |
| 250 | fn enc(&self, e: &mut Encoder) -> io::Result<()> { |
| 251 | match self { |
| 252 | Self::List { archive } => { |
| 253 | 0u8.enc(e)?; |
| 254 | archive.enc(e) |
| 255 | } |
| 256 | Self::Extract { |
| 257 | archive, |
| 258 | destination, |
| 259 | selection, |
| 260 | list_id, |
| 261 | gzip_output_name, |
| 262 | } => { |
| 263 | 1u8.enc(e)?; |
| 264 | archive.enc(e)?; |
| 265 | destination.enc(e)?; |
| 266 | selection.enc(e)?; |
| 267 | list_id.enc(e)?; |
| 268 | gzip_output_name.enc(e) |
| 269 | } |
| 270 | Self::CreateZip { |
| 271 | sources, |
| 272 | output_file, |
| 273 | method, |
| 274 | encryption, |
| 275 | } => { |
| 276 | 2u8.enc(e)?; |
| 277 | sources.enc(e)?; |
| 278 | output_file.enc(e)?; |
| 279 | method.enc(e)?; |
| 280 | encryption.enc(e) |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { |
| 285 | match u8::dec(d)? { |
| 286 | 0 => Ok(Self::List { |
| 287 | archive: Wire::dec(d)?, |
| 288 | }), |
| 289 | 1 => Ok(Self::Extract { |
| 290 | archive: Wire::dec(d)?, |
| 291 | destination: Wire::dec(d)?, |
| 292 | selection: Wire::dec(d)?, |
| 293 | list_id: Wire::dec(d)?, |
| 294 | gzip_output_name: Wire::dec(d)?, |
| 295 | }), |
| 296 | 2 => Ok(Self::CreateZip { |
| 297 | sources: Wire::dec(d)?, |
| 298 | output_file: Wire::dec(d)?, |
| 299 | method: Wire::dec(d)?, |
| 300 | encryption: Wire::dec(d)?, |
| 301 | }), |
| 302 | _ => Err(invalid()), |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | impl Message { |
| 307 | fn encode(&self) -> io::Result<(u16, Vec<u8>)> { |
| 308 | let mut e = Encoder { bytes: Vec::new() }; |
| 309 | let kind = match self { |
| 310 | Self::Start(v) => { |
| 311 | v.enc(&mut e)?; |
| 312 | 1 |
| 313 | } |
| 314 | Self::Password { |
| 315 | challenge_id, |
| 316 | secret, |
| 317 | } => { |
| 318 | if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() { |
| 319 | return Err(invalid()); |
| 320 | } |
| 321 | challenge_id.enc(&mut e)?; |
| 322 | secret.0.enc(&mut e)?; |
| 323 | 2 |
| 324 | } |
| 325 | Self::Cancel => 3, |
| 326 | Self::Accepted { action, encryption } => { |
| 327 | action.enc(&mut e)?; |
| 328 | encryption.enc(&mut e)?; |
| 329 | 100 |
| 330 | } |
| 331 | Self::Entry(v) => { |
| 332 | v.enc(&mut e)?; |
| 333 | 101 |
| 334 | } |
| 335 | Self::ListEnd { |
| 336 | entry_count, |
| 337 | list_id, |
| 338 | } => { |
| 339 | entry_count.enc(&mut e)?; |
| 340 | list_id.enc(&mut e)?; |
| 341 | 102 |
| 342 | } |
| 343 | Self::PasswordRequired { |
| 344 | challenge_id, |
| 345 | attempt, |
| 346 | purpose, |
| 347 | } => { |
| 348 | challenge_id.enc(&mut e)?; |
| 349 | attempt.enc(&mut e)?; |
| 350 | purpose.enc(&mut e)?; |
| 351 | 103 |
| 352 | } |
| 353 | Self::Progress { |
| 354 | stage, |
| 355 | processed_bytes, |
| 356 | total_bytes, |
| 357 | completed_entries, |
| 358 | } => { |
| 359 | stage.enc(&mut e)?; |
| 360 | processed_bytes.enc(&mut e)?; |
| 361 | total_bytes.enc(&mut e)?; |
| 362 | completed_entries.enc(&mut e)?; |
| 363 | 104 |
| 364 | } |
| 365 | Self::Output { |
| 366 | entry_id, |
| 367 | relative_name, |
| 368 | disposition, |
| 369 | } => { |
| 370 | entry_id.enc(&mut e)?; |
| 371 | relative_name.enc(&mut e)?; |
| 372 | disposition.enc(&mut e)?; |
| 373 | 105 |
| 374 | } |
| 375 | Self::Terminal(v) => { |
| 376 | if v.detail.len() > 4096 { |
| 377 | return Err(invalid()); |
| 378 | } |
| 379 | v.enc(&mut e)?; |
| 380 | 106 |
| 381 | } |
| 382 | Self::CancelAck { |
| 383 | request_sequence, |
| 384 | status, |
| 385 | } => { |
| 386 | request_sequence.enc(&mut e)?; |
| 387 | status.enc(&mut e)?; |
| 388 | 107 |
| 389 | } |
| 390 | }; |
| 391 | Ok((kind, e.bytes)) |
| 392 | } |
| 393 | fn decode(kind: u16, b: &[u8]) -> io::Result<Self> { |
| 394 | let mut d = Decoder { bytes: b, at: 0 }; |
| 395 | let m = match kind { |
| 396 | 1 => Self::Start(Wire::dec(&mut d)?), |
| 397 | 2 => { |
| 398 | let challenge_id = Wire::dec(&mut d)?; |
| 399 | let secret = Secret(Vec::<u8>::dec(&mut d)?); |
| 400 | if secret.0.len() > 1024 || std::str::from_utf8(&secret.0).is_err() { |
| 401 | return Err(invalid()); |
| 402 | } |
| 403 | Self::Password { |
| 404 | challenge_id, |
| 405 | secret, |
| 406 | } |
| 407 | } |
| 408 | 3 => Self::Cancel, |
| 409 | 100 => Self::Accepted { |
| 410 | action: Wire::dec(&mut d)?, |
| 411 | encryption: Wire::dec(&mut d)?, |
| 412 | }, |
| 413 | 101 => Self::Entry(Wire::dec(&mut d)?), |
| 414 | 102 => Self::ListEnd { |
| 415 | entry_count: Wire::dec(&mut d)?, |
| 416 | list_id: Wire::dec(&mut d)?, |
| 417 | }, |
| 418 | 103 => Self::PasswordRequired { |
| 419 | challenge_id: Wire::dec(&mut d)?, |
| 420 | attempt: Wire::dec(&mut d)?, |
| 421 | purpose: Wire::dec(&mut d)?, |
| 422 | }, |
| 423 | 104 => Self::Progress { |
| 424 | stage: Wire::dec(&mut d)?, |
| 425 | processed_bytes: Wire::dec(&mut d)?, |
| 426 | total_bytes: Wire::dec(&mut d)?, |
| 427 | completed_entries: Wire::dec(&mut d)?, |
| 428 | }, |
| 429 | 105 => Self::Output { |
| 430 | entry_id: Wire::dec(&mut d)?, |
| 431 | relative_name: Wire::dec(&mut d)?, |
| 432 | disposition: Wire::dec(&mut d)?, |
| 433 | }, |
| 434 | 106 => { |
| 435 | let t = Terminal::dec(&mut d)?; |
| 436 | if t.detail.len() > 4096 { |
| 437 | return Err(invalid()); |
| 438 | } |
| 439 | Self::Terminal(t) |
| 440 | } |
| 441 | 107 => Self::CancelAck { |
| 442 | request_sequence: Wire::dec(&mut d)?, |
| 443 | status: Wire::dec(&mut d)?, |
| 444 | }, |
| 445 | _ => return Err(invalid()), |
| 446 | }; |
| 447 | if d.at != b.len() { |
| 448 | return Err(invalid()); |
| 449 | } |
| 450 | Ok(m) |
| 451 | } |
| 452 | } |
| 453 | pub struct Reader<R> { |
| 454 | input: R, |
| 455 | sequence: u64, |
| 456 | job: Option<u64>, |
| 457 | terminal: bool, |
| 458 | } |
| 459 | impl<R: Read> Reader<R> { |
| 460 | pub fn new(input: R) -> Self { |
| 461 | Self { |
| 462 | input, |
| 463 | sequence: 0, |
| 464 | job: None, |
| 465 | terminal: false, |
| 466 | } |
| 467 | } |
| 468 | pub fn read(&mut self) -> io::Result<Option<(u64, u64, Message)>> { |
| 469 | let mut h = [0u8; 32]; |
| 470 | loop { |
| 471 | match self.input.read(&mut h[..1]) { |
| 472 | Ok(0) => return Ok(None), |
| 473 | Ok(_) => break, |
| 474 | Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, |
| 475 | Err(e) => return Err(e), |
| 476 | } |
| 477 | } |
| 478 | if self.terminal { |
| 479 | return Err(invalid()); |
| 480 | } |
| 481 | self.input.read_exact(&mut h[1..])?; |
| 482 | let len = u32::from_le_bytes(h[8..12].try_into().unwrap()) as usize; |
| 483 | let job = u64::from_le_bytes(h[16..24].try_into().unwrap()); |
| 484 | let seq = u64::from_le_bytes(h[24..32].try_into().unwrap()); |
| 485 | if &h[..4] != b"ZAW1" |
| 486 | || h[4..6] != 1u16.to_le_bytes() |
| 487 | || h[12..16] != [0; 4] |
| 488 | || len > MAX_BODY |
| 489 | || job == 0 |
| 490 | || self.job.is_some_and(|j| j != job) |
| 491 | || seq != self.sequence |
| 492 | || seq >= MAX_FRAMES |
| 493 | { |
| 494 | return Err(invalid()); |
| 495 | } |
| 496 | self.job = Some(job); |
| 497 | self.sequence += 1; |
| 498 | let mut b = vec![0; len]; |
| 499 | self.input.read_exact(&mut b)?; |
| 500 | let message = Message::decode(u16::from_le_bytes(h[6..8].try_into().unwrap()), &b)?; |
| 501 | self.terminal = matches!(message, Message::Terminal(_)); |
| 502 | Ok(Some((job, seq, message))) |
| 503 | } |
| 504 | } |
| 505 | pub struct Writer<W> { |
| 506 | output: W, |
| 507 | sequence: u64, |
| 508 | job: u64, |
| 509 | terminal: bool, |
| 510 | } |
| 511 | impl<W: Write> Writer<W> { |
| 512 | pub fn new(output: W, job: u64) -> Self { |
| 513 | Self { |
| 514 | output, |
| 515 | sequence: 0, |
| 516 | job, |
| 517 | terminal: false, |
| 518 | } |
| 519 | } |
| 520 | pub fn send(&mut self, m: &Message) -> io::Result<()> { |
| 521 | if self.job == 0 || self.terminal || self.sequence >= MAX_FRAMES { |
| 522 | return Err(invalid()); |
| 523 | } |
| 524 | let (kind, b) = m.encode()?; |
| 525 | let mut h = Vec::with_capacity(32); |
| 526 | h.extend(b"ZAW1"); |
| 527 | h.extend(1u16.to_le_bytes()); |
| 528 | h.extend(kind.to_le_bytes()); |
| 529 | h.extend((b.len() as u32).to_le_bytes()); |
| 530 | h.extend(0u32.to_le_bytes()); |
| 531 | h.extend(self.job.to_le_bytes()); |
| 532 | h.extend(self.sequence.to_le_bytes()); |
| 533 | self.output.write_all(&h)?; |
| 534 | self.output.write_all(&b)?; |
| 535 | self.output.flush()?; |
| 536 | self.sequence += 1; |
| 537 | self.terminal = matches!(m, Message::Terminal(_)); |
| 538 | Ok(()) |
| 539 | } |
| 540 | } |