1#![forbid(unsafe_code)] use 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
18const CAPACITY: usize = 4;
23
24const CHUNKSZ: usize = 213;
28
29pub 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
55pub struct LocalStream {
62 w: mpsc::Sender<IoResult<Vec<u8>>>,
67 r: mpsc::Receiver<IoResult<Vec<u8>>>,
72 pending_bytes: Vec<u8>,
74 pub(crate) tls_cert: Option<Vec<u8>>,
83}
84
85fn 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)), }
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#[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 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)))] mod test {
194 #![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_time_subtraction)]
204 #![allow(clippy::useless_vec)]
205 #![allow(clippy::needless_pass_by_value)]
206 #![allow(clippy::string_slice)] use super::*;
209
210 use futures::io::{AsyncReadExt, AsyncWriteExt};
211 use futures_await_test::async_test;
212 use rand::RngExt;
213 use tor_basic_utils::test_rng::testing_rng;
214
215 #[async_test]
216 async fn basic_rw() {
217 let (mut s1, mut s2) = stream_pair();
218 let mut text1 = vec![0_u8; 9999];
219 testing_rng().fill(&mut text1[..]);
220
221 let (v1, v2): (IoResult<()>, IoResult<()>) = futures::join!(
222 async {
223 for _ in 0_u8..10 {
224 s1.write_all(&text1[..]).await?;
225 }
226 s1.close().await?;
227 Ok(())
228 },
229 async {
230 let mut text2: Vec<u8> = Vec::new();
231 let mut buf = [0_u8; 33];
232 loop {
233 let n = s2.read(&mut buf[..]).await?;
234 if n == 0 {
235 break;
236 }
237 text2.extend(&buf[..n]);
238 }
239 for ch in text2[..].chunks(text1.len()) {
240 assert_eq!(ch, &text1[..]);
241 }
242 Ok(())
243 }
244 );
245
246 v1.unwrap();
247 v2.unwrap();
248 }
249
250 #[async_test]
251 async fn send_error() {
252 let (mut s1, mut s2) = stream_pair();
253
254 let (v1, v2): (IoResult<()>, IoResult<()>) = futures::join!(
255 async {
256 s1.write_all(b"hello world").await?;
257 s1.send_err(ErrorKind::PermissionDenied).await;
258 Ok(())
259 },
260 async {
261 let mut buf = [0_u8; 33];
262 loop {
263 let n = s2.read(&mut buf[..]).await?;
264 if n == 0 {
265 break;
266 }
267 }
268 Ok(())
269 }
270 );
271
272 v1.unwrap();
273 let e = v2.err().unwrap();
274 assert_eq!(e.kind(), ErrorKind::PermissionDenied);
275 let synth = e.into_inner().unwrap();
276 assert_eq!(synth.to_string(), "Synthetic error");
277 }
278
279 #[async_test]
280 async fn drop_reader() {
281 let (mut s1, s2) = stream_pair();
282
283 let (v1, v2): (IoResult<()>, IoResult<()>) = futures::join!(
284 async {
285 for _ in 0_u16..1000 {
286 s1.write_all(&[9_u8; 9999]).await?;
287 }
288 Ok(())
289 },
290 async {
291 drop(s2);
292 Ok(())
293 }
294 );
295
296 v2.unwrap();
297 let e = v1.err().unwrap();
298 assert_eq!(e.kind(), ErrorKind::BrokenPipe);
299 }
300}