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

            
8
use crate::util::mpsc_channel;
9
use futures::channel::mpsc;
10
use futures::io::{AsyncRead, AsyncWrite};
11
use futures::sink::{Sink, SinkExt};
12
use futures::stream::Stream;
13
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
14
use std::pin::Pin;
15
use std::task::{Context, Poll};
16
use 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.
22
const 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.
27
const 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.
37
1431
pub fn stream_pair() -> (LocalStream, LocalStream) {
38
1431
    let (w1, r2) = mpsc_channel(CAPACITY);
39
1431
    let (w2, r1) = mpsc_channel(CAPACITY);
40
1431
    let s1 = LocalStream {
41
1431
        w: w1,
42
1431
        r: r1,
43
1431
        pending_bytes: Vec::new(),
44
1431
        tls_cert: None,
45
1431
    };
46
1431
    let s2 = LocalStream {
47
1431
        w: w2,
48
1431
        r: r2,
49
1431
        pending_bytes: Vec::new(),
50
1431
        tls_cert: None,
51
1431
    };
52
1431
    (s1, s2)
53
1431
}
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.
61
pub 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.
87
12828
fn drain_helper(buf: &mut [u8], pending_bytes: &mut Vec<u8>) -> usize {
88
12828
    let n_to_drain = std::cmp::min(buf.len(), pending_bytes.len());
89
12828
    buf[..n_to_drain].copy_from_slice(&pending_bytes[..n_to_drain]);
90
12828
    pending_bytes.drain(..n_to_drain);
91
12828
    n_to_drain
92
12828
}
93

            
94
impl AsyncRead for LocalStream {
95
17401
    fn poll_read(
96
17401
        mut self: Pin<&mut Self>,
97
17401
        cx: &mut Context<'_>,
98
17401
        buf: &mut [u8],
99
17401
    ) -> Poll<IoResult<usize>> {
100
17401
        if buf.is_empty() {
101
            return Poll::Ready(Ok(0));
102
17401
        }
103
17401
        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
17401
        }
108
17401
        if !self.pending_bytes.is_empty() {
109
6762
            return Poll::Ready(Ok(drain_helper(buf, &mut self.pending_bytes)));
110
10639
        }
111

            
112
10639
        match futures::ready!(Pin::new(&mut self.r).poll_next(cx)) {
113
2
            Some(Err(e)) => Poll::Ready(Err(e)),
114
6066
            Some(Ok(bytes)) => {
115
6066
                self.pending_bytes = bytes;
116
6066
                let n = drain_helper(buf, &mut self.pending_bytes);
117
6066
                Poll::Ready(Ok(n))
118
            }
119
756
            None => Poll::Ready(Ok(0)), // This is an EOF
120
        }
121
17401
    }
122
}
123

            
124
impl AsyncWrite for LocalStream {
125
7337
    fn poll_write(
126
7337
        mut self: Pin<&mut Self>,
127
7337
        cx: &mut Context<'_>,
128
7337
        buf: &[u8],
129
7337
    ) -> Poll<IoResult<usize>> {
130
7337
        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
7337
        }
135

            
136
7337
        match futures::ready!(Pin::new(&mut self.w).poll_ready(cx)) {
137
6280
            Ok(()) => (),
138
2
            Err(e) => return Poll::Ready(Err(IoError::new(ErrorKind::BrokenPipe, e))),
139
        }
140

            
141
6280
        let buf = if buf.len() > CHUNKSZ {
142
5316
            &buf[..CHUNKSZ]
143
        } else {
144
964
            buf
145
        };
146
6280
        let len = buf.len();
147
6280
        match Pin::new(&mut self.w).start_send(Ok(buf.to_vec())) {
148
6280
            Ok(()) => Poll::Ready(Ok(len)),
149
            Err(e) => Poll::Ready(Err(IoError::new(ErrorKind::BrokenPipe, e))),
150
        }
151
7337
    }
152
459
    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
153
459
        Pin::new(&mut self.w)
154
459
            .poll_flush(cx)
155
459
            .map_err(|e| IoError::new(ErrorKind::BrokenPipe, e))
156
459
    }
157
756
    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
158
756
        Pin::new(&mut self.w).poll_close(cx).map_err(IoError::other)
159
756
    }
160
}
161

            
162
impl 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]
174
pub struct SyntheticError;
175
impl std::error::Error for SyntheticError {}
176
impl std::fmt::Display for SyntheticError {
177
2
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178
2
        write!(f, "Synthetic error")
179
2
    }
180
}
181

            
182
impl 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
3
    pub async fn send_err(&mut self, kind: ErrorKind) {
188
2
        let _ignore = self.w.send(Err(IoError::new(kind, SyntheticError))).await;
189
2
    }
190
}
191

            
192
#[cfg(all(test, not(miri)))] // These tests are very slow under miri
193
mod 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
}