tor_rtmock/
io.rs

1//! Mocking helpers for testing with futures::io types.
2//!
3//! Note that some of this code might be of general use, but for now
4//! we're only trying it for testing.
5
6#![forbid(unsafe_code)] // if you remove this, enable (or write) miri tests (git grep miri)
7
8use crate::util::mpsc_channel;
9use futures::channel::mpsc;
10use futures::io::{AsyncRead, AsyncWrite};
11use futures::sink::{Sink, SinkExt};
12use futures::stream::Stream;
13use std::io::{Error as IoError, ErrorKind, Result as IoResult};
14use std::pin::Pin;
15use std::task::{Context, Poll};
16use tor_rtcompat::{StreamOps, UnsupportedStreamOp};
17
18/// Channel capacity for our internal MPSC channels.
19///
20/// We keep this intentionally low to make sure that some blocking
21/// will occur occur.
22const CAPACITY: usize = 4;
23
24/// Maximum size for a queued buffer on a local chunk.
25///
26/// This size is deliberately weird, to try to find errors.
27const CHUNKSZ: usize = 213;
28
29/// Construct a new pair of linked LocalStream objects.
30///
31/// Any bytes written to one will be readable on the other, and vice
32/// versa.  These streams will behave more or less like a socketpair,
33/// except without actually going through the operating system.
34///
35/// Note that this implementation is intended for testing only, and
36/// isn't optimized.
37pub fn stream_pair() -> (LocalStream, LocalStream) {
38    let (w1, r2) = mpsc_channel(CAPACITY);
39    let (w2, r1) = mpsc_channel(CAPACITY);
40    let s1 = LocalStream {
41        w: w1,
42        r: r1,
43        pending_bytes: Vec::new(),
44        tls_cert: None,
45    };
46    let s2 = LocalStream {
47        w: w2,
48        r: r2,
49        pending_bytes: Vec::new(),
50        tls_cert: None,
51    };
52    (s1, s2)
53}
54
55/// One half of a pair of linked streams returned by [`stream_pair`].
56//
57// Implementation notes: linked streams are made out a pair of mpsc
58// channels.  There's one channel for sending bytes in each direction.
59// Bytes are sent as IoResult<Vec<u8>>: sending an error causes an error
60// to occur on the other side.
61pub struct LocalStream {
62    /// The writing side of the channel that we use to implement this
63    /// stream.
64    ///
65    /// The reading side is held by the other linked stream.
66    w: mpsc::Sender<IoResult<Vec<u8>>>,
67    /// The reading side of the channel that we use to implement this
68    /// stream.
69    ///
70    /// The writing side is held by the other linked stream.
71    r: mpsc::Receiver<IoResult<Vec<u8>>>,
72    /// Bytes that we have read from `r` but not yet delivered.
73    pending_bytes: Vec<u8>,
74    /// Data about the other side of this stream's fake TLS certificate, if any.
75    /// If this is present, I/O operations will fail with an error.
76    ///
77    /// How this is intended to work: things that return `LocalStream`s that could potentially
78    /// be connected to a fake TLS listener should set this field. Then, a fake TLS wrapper
79    /// type would clear this field (after checking its contents are as expected).
80    ///
81    /// FIXME(eta): this is a bit of a layering violation, but it's hard to do otherwise
82    pub(crate) tls_cert: Option<Vec<u8>>,
83}
84
85/// Helper: pull bytes off the front of `pending_bytes` and put them
86/// onto `buf.  Return the number of bytes moved.
87fn drain_helper(buf: &mut [u8], pending_bytes: &mut Vec<u8>) -> usize {
88    let n_to_drain = std::cmp::min(buf.len(), pending_bytes.len());
89    buf[..n_to_drain].copy_from_slice(&pending_bytes[..n_to_drain]);
90    pending_bytes.drain(..n_to_drain);
91    n_to_drain
92}
93
94impl AsyncRead for LocalStream {
95    fn poll_read(
96        mut self: Pin<&mut Self>,
97        cx: &mut Context<'_>,
98        buf: &mut [u8],
99    ) -> Poll<IoResult<usize>> {
100        if buf.is_empty() {
101            return Poll::Ready(Ok(0));
102        }
103        if self.tls_cert.is_some() {
104            return Poll::Ready(Err(std::io::Error::other(
105                "attempted to treat a TLS stream as non-TLS!",
106            )));
107        }
108        if !self.pending_bytes.is_empty() {
109            return Poll::Ready(Ok(drain_helper(buf, &mut self.pending_bytes)));
110        }
111
112        match futures::ready!(Pin::new(&mut self.r).poll_next(cx)) {
113            Some(Err(e)) => Poll::Ready(Err(e)),
114            Some(Ok(bytes)) => {
115                self.pending_bytes = bytes;
116                let n = drain_helper(buf, &mut self.pending_bytes);
117                Poll::Ready(Ok(n))
118            }
119            None => Poll::Ready(Ok(0)), // This is an EOF
120        }
121    }
122}
123
124impl AsyncWrite for LocalStream {
125    fn poll_write(
126        mut self: Pin<&mut Self>,
127        cx: &mut Context<'_>,
128        buf: &[u8],
129    ) -> Poll<IoResult<usize>> {
130        if self.tls_cert.is_some() {
131            return Poll::Ready(Err(IoError::other(
132                "attempted to treat a TLS stream as non-TLS!",
133            )));
134        }
135
136        match futures::ready!(Pin::new(&mut self.w).poll_ready(cx)) {
137            Ok(()) => (),
138            Err(e) => return Poll::Ready(Err(IoError::new(ErrorKind::BrokenPipe, e))),
139        }
140
141        let buf = if buf.len() > CHUNKSZ {
142            &buf[..CHUNKSZ]
143        } else {
144            buf
145        };
146        let len = buf.len();
147        match Pin::new(&mut self.w).start_send(Ok(buf.to_vec())) {
148            Ok(()) => Poll::Ready(Ok(len)),
149            Err(e) => Poll::Ready(Err(IoError::new(ErrorKind::BrokenPipe, e))),
150        }
151    }
152    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
153        Pin::new(&mut self.w)
154            .poll_flush(cx)
155            .map_err(|e| IoError::new(ErrorKind::BrokenPipe, e))
156    }
157    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
158        Pin::new(&mut self.w).poll_close(cx).map_err(IoError::other)
159    }
160}
161
162impl StreamOps for LocalStream {
163    fn set_tcp_notsent_lowat(&self, _notsent_lowat: u32) -> IoResult<()> {
164        Err(
165            UnsupportedStreamOp::new("set_tcp_notsent_lowat", "unsupported on local streams")
166                .into(),
167        )
168    }
169}
170
171/// An error generated by [`LocalStream::send_err`].
172#[derive(Debug, Clone, Eq, PartialEq)]
173#[non_exhaustive]
174pub struct SyntheticError;
175impl std::error::Error for SyntheticError {}
176impl std::fmt::Display for SyntheticError {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        write!(f, "Synthetic error")
179    }
180}
181
182impl LocalStream {
183    /// Send an error to the other linked local stream.
184    ///
185    /// When the other stream reads this message, it will generate a
186    /// [`std::io::Error`] with the provided `ErrorKind`.
187    pub async fn send_err(&mut self, kind: ErrorKind) {
188        let _ignore = self.w.send(Err(IoError::new(kind, SyntheticError))).await;
189    }
190}
191
192#[cfg(all(test, not(miri)))] // These tests are very slow under miri
193mod test {
194    // @@ begin test lint list maintained by maint/add_warning @@
195    #![allow(clippy::bool_assert_comparison)]
196    #![allow(clippy::clone_on_copy)]
197    #![allow(clippy::dbg_macro)]
198    #![allow(clippy::mixed_attributes_style)]
199    #![allow(clippy::print_stderr)]
200    #![allow(clippy::print_stdout)]
201    #![allow(clippy::single_char_pattern)]
202    #![allow(clippy::unwrap_used)]
203    #![allow(clippy::unchecked_duration_subtraction)]
204    #![allow(clippy::useless_vec)]
205    #![allow(clippy::needless_pass_by_value)]
206    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
207    use super::*;
208
209    use futures::io::{AsyncReadExt, AsyncWriteExt};
210    use futures_await_test::async_test;
211    use rand::Rng;
212    use tor_basic_utils::test_rng::testing_rng;
213
214    #[async_test]
215    async fn basic_rw() {
216        let (mut s1, mut s2) = stream_pair();
217        let mut text1 = vec![0_u8; 9999];
218        testing_rng().fill(&mut text1[..]);
219
220        let (v1, v2): (IoResult<()>, IoResult<()>) = futures::join!(
221            async {
222                for _ in 0_u8..10 {
223                    s1.write_all(&text1[..]).await?;
224                }
225                s1.close().await?;
226                Ok(())
227            },
228            async {
229                let mut text2: Vec<u8> = Vec::new();
230                let mut buf = [0_u8; 33];
231                loop {
232                    let n = s2.read(&mut buf[..]).await?;
233                    if n == 0 {
234                        break;
235                    }
236                    text2.extend(&buf[..n]);
237                }
238                for ch in text2[..].chunks(text1.len()) {
239                    assert_eq!(ch, &text1[..]);
240                }
241                Ok(())
242            }
243        );
244
245        v1.unwrap();
246        v2.unwrap();
247    }
248
249    #[async_test]
250    async fn send_error() {
251        let (mut s1, mut s2) = stream_pair();
252
253        let (v1, v2): (IoResult<()>, IoResult<()>) = futures::join!(
254            async {
255                s1.write_all(b"hello world").await?;
256                s1.send_err(ErrorKind::PermissionDenied).await;
257                Ok(())
258            },
259            async {
260                let mut buf = [0_u8; 33];
261                loop {
262                    let n = s2.read(&mut buf[..]).await?;
263                    if n == 0 {
264                        break;
265                    }
266                }
267                Ok(())
268            }
269        );
270
271        v1.unwrap();
272        let e = v2.err().unwrap();
273        assert_eq!(e.kind(), ErrorKind::PermissionDenied);
274        let synth = e.into_inner().unwrap();
275        assert_eq!(synth.to_string(), "Synthetic error");
276    }
277
278    #[async_test]
279    async fn drop_reader() {
280        let (mut s1, s2) = stream_pair();
281
282        let (v1, v2): (IoResult<()>, IoResult<()>) = futures::join!(
283            async {
284                for _ in 0_u16..1000 {
285                    s1.write_all(&[9_u8; 9999]).await?;
286                }
287                Ok(())
288            },
289            async {
290                drop(s2);
291                Ok(())
292            }
293        );
294
295        v2.unwrap();
296        let e = v1.err().unwrap();
297        assert_eq!(e.kind(), ErrorKind::BrokenPipe);
298    }
299}