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_duration_subtraction)]
204 #![allow(clippy::useless_vec)]
205 #![allow(clippy::needless_pass_by_value)]
206 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}