Skip to main content

dprint_core/communication/
reader_writer.rs

1use std::io::ErrorKind;
2use std::io::Read;
3use std::io::Result;
4use std::io::Write;
5
6const SUCCESS_BYTES: &[u8; 4] = &[255, 255, 255, 255];
7
8pub struct MessageReader<TRead: Read + Unpin> {
9  reader: TRead,
10}
11
12impl<TRead: Read + Unpin> MessageReader<TRead> {
13  /// Creates a reader for messages from the provided reader.
14  ///
15  /// The reader must only write to the buffers passed to `Read::read` and
16  /// never read from them, which is the case for pipes such as `ChildStdout`
17  /// and `Stdin`. See `read_exact_into_uninit` for why.
18  pub fn new(reader: TRead) -> Self {
19    Self { reader }
20  }
21
22  /// Reads a u32 value.
23  pub fn read_u32(&mut self) -> Result<u32> {
24    let mut int_buf: [u8; 4] = [0; 4];
25    self.reader.read_exact(&mut int_buf)?;
26    Ok(u32::from_be_bytes(int_buf))
27  }
28
29  /// Reads a u32 value followed by a buffer.
30  pub fn read_sized_bytes(&mut self) -> Result<Vec<u8>> {
31    let size = self.read_u32()? as usize;
32    self.read_bytes(size)
33  }
34
35  pub fn read_bytes(&mut self, size: usize) -> Result<Vec<u8>> {
36    if size == 0 {
37      return Ok(Vec::new());
38    }
39    read_exact_into_uninit(&mut self.reader, size)
40  }
41
42  pub fn read_success_bytes(&mut self) -> Result<()> {
43    let read_bytes = self.inner_read_success_bytes()?;
44    if &read_bytes != SUCCESS_BYTES {
45      let message = format!(
46        "Catastrophic error reading from process. Did not receive the success bytes at end of message. Found: {:?}",
47        read_bytes
48      );
49      Result::Err(std::io::Error::new(ErrorKind::InvalidData, message))
50    } else {
51      Ok(())
52    }
53  }
54
55  fn inner_read_success_bytes(&mut self) -> Result<[u8; 4]> {
56    let mut read_buf: [u8; 4] = [0; 4];
57    self.reader.read_exact(&mut read_buf)?;
58    Ok(read_buf)
59  }
60}
61
62pub struct MessageWriter<TWrite: Write + Unpin> {
63  writer: TWrite,
64}
65
66impl<TWrite: Write + Unpin> MessageWriter<TWrite> {
67  pub fn new(writer: TWrite) -> Self {
68    Self { writer }
69  }
70
71  pub fn send_u32(&mut self, value: u32) -> Result<()> {
72    self.writer.write_all(&value.to_be_bytes())?;
73    Ok(())
74  }
75
76  pub fn send_sized_bytes(&mut self, bytes: &[u8]) -> Result<()> {
77    self.send_u32(bytes.len() as u32)?;
78    if !bytes.is_empty() {
79      self.writer.write_all(bytes)?;
80    }
81    Ok(())
82  }
83
84  pub fn send_success_bytes(&mut self) -> Result<()> {
85    self.writer.write_all(SUCCESS_BYTES)?;
86    self.writer.flush()?;
87    Ok(())
88  }
89
90  pub fn flush(&mut self) -> Result<()> {
91    self.writer.flush()
92  }
93}
94
95/// Reads exactly `size` bytes into a newly allocated buffer without zeroing
96/// it first.
97///
98/// This is not a security issue:
99///
100/// - The readers used with this (`ChildStdout` and `Stdin`) only write to the
101///   buffer they're given and never read from it. A plugin only controls the
102///   bytes sent over the pipe, not the `Read` implementation, so it can't make
103///   this read uninitialized memory.
104/// - The uninitialized bytes never escape. On success every byte has been
105///   overwritten and on failure the buffer is dropped with the error.
106///
107/// Every sound alternative was benchmarked and was measurably slower for large
108/// messages: `resize(size, 0)` zeroes the buffer before reading,
109/// `take().read_to_end()` reads in small chunks, and `vec![0; size]` aborts on
110/// allocation failure rather than erroring.
111#[inline(always)]
112#[allow(clippy::read_zero_byte_vec)] // false positive because it doesn't see set_len
113fn read_exact_into_uninit(reader: &mut impl Read, size: usize) -> Result<Vec<u8>> {
114  let mut buf = Vec::new();
115  buf.try_reserve_exact(size)?;
116  // SAFETY: capacity was reserved for `size` bytes and, given a reader that
117  // only writes to its buffer, the bytes are only observed once `read_exact`
118  // has overwritten them all (see above)
119  unsafe {
120    buf.set_len(size);
121  }
122  reader.read_exact(&mut buf)?;
123  Ok(buf)
124}
125
126#[cfg(test)]
127mod test {
128  use super::*;
129
130  #[test]
131  fn read_bytes_reads_exact_size() {
132    let data = [1, 2, 3, 4, 5];
133    let mut reader = MessageReader::new(&data[..]);
134    assert_eq!(reader.read_bytes(3).unwrap(), vec![1, 2, 3]);
135    assert_eq!(reader.read_bytes(0).unwrap(), Vec::<u8>::new());
136    assert_eq!(reader.read_bytes(2).unwrap(), vec![4, 5]);
137  }
138
139  #[test]
140  fn read_bytes_errors_on_eof() {
141    let data = [1, 2];
142    let mut reader = MessageReader::new(&data[..]);
143    let err = reader.read_bytes(3).unwrap_err();
144    assert_eq!(err.kind(), ErrorKind::UnexpectedEof);
145  }
146}