Skip to main content

coqui_peer/
asynch.rs

1//! The loops of [`drive_stream`](crate::drive_stream) and
2//! [`drive_messages`](crate::drive_messages) over tokio streams and async message transports.
3
4use core::future::Future;
5use std::io;
6use std::time::Instant;
7
8use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
9
10use crate::drive::{DriveError, check_whole, frame_header, frame_length, transport_error};
11use crate::method::{Established, Framing, Handshake};
12
13const CHUNK: usize = 16 * 1024;
14
15/// An asynchronous transport of whole messages.
16pub trait MessageTransport {
17    /// Sends one message.
18    fn send(&mut self, message: &[u8]) -> impl Future<Output = io::Result<()>> + Send;
19
20    /// Receives the next message.
21    fn recv(&mut self) -> impl Future<Output = io::Result<Vec<u8>>> + Send;
22}
23
24/// [`write_frame`](crate::write_frame) over a tokio stream.
25///
26/// # Errors
27///
28/// `InvalidInput` when `message` is longer than [`MAX_MESSAGE`](crate::MAX_MESSAGE);
29/// otherwise the stream's error.
30pub async fn write_frame<W: AsyncWrite + Unpin + ?Sized>(
31    io: &mut W,
32    message: &[u8],
33) -> io::Result<()> {
34    io.write_all(&frame_header(message.len(), io::ErrorKind::InvalidInput)?)
35        .await?;
36    io.write_all(message).await?;
37    io.flush().await
38}
39
40/// [`read_frame`](crate::read_frame) over a tokio stream: the buffer grows as bytes arrive.
41///
42/// # Errors
43///
44/// `InvalidData` when the declared length is above [`MAX_MESSAGE`](crate::MAX_MESSAGE),
45/// `UnexpectedEof` when the stream ends inside the frame; otherwise the stream's error.
46pub async fn read_frame<R: AsyncRead + Unpin + ?Sized>(io: &mut R) -> io::Result<Vec<u8>> {
47    let mut header = [0u8; 4];
48    io.read_exact(&mut header).await?;
49    let length = frame_length(header)?;
50    let mut message = Vec::new();
51    io.take(length).read_to_end(&mut message).await?;
52    check_whole(&message, length)?;
53    Ok(message)
54}
55
56/// [`drive_stream`](crate::drive_stream) over a tokio stream.
57///
58/// # Errors
59///
60/// [`DriveError`] when the stream fails or closes, or the handshake refuses the peer.
61pub async fn drive_stream<H, T>(
62    handshake: H,
63    io: &mut T,
64) -> Result<Established<H::Output>, DriveError<H::Error>>
65where
66    H: Handshake,
67    T: AsyncRead + AsyncWrite + Unpin,
68{
69    complete_stream(handshake, io)
70        .await?
71        .finish()
72        .map_err(DriveError::Handshake)
73}
74
75/// [`complete_stream`](crate::complete_stream) over a tokio stream: the handshake once
76/// complete, not yet finished.
77///
78/// # Errors
79///
80/// As [`drive_stream`].
81pub async fn complete_stream<H, T>(mut handshake: H, io: &mut T) -> Result<H, DriveError<H::Error>>
82where
83    H: Handshake,
84    T: AsyncRead + AsyncWrite + Unpin,
85{
86    let framed = handshake.framing() == Framing::Message;
87    let mut buffer = vec![0u8; CHUNK];
88    loop {
89        send_all(&mut handshake, io, framed).await?;
90        if handshake.is_complete() {
91            return Ok(handshake);
92        }
93        let received = if framed {
94            let message = read_frame(io).await.map_err(transport_error)?;
95            handshake.receive(&message)
96        } else {
97            let read = io.read(&mut buffer).await.map_err(DriveError::Io)?;
98            if read == 0 {
99                return Err(DriveError::Io(io::ErrorKind::UnexpectedEof.into()));
100            }
101            handshake.receive(&buffer[..read])
102        };
103        if let Err(error) = received {
104            // A method may have queued a refusal to tell the peer (a TLS alert).
105            let _ = send_all(&mut handshake, io, framed).await;
106            return Err(DriveError::Handshake(error));
107        }
108    }
109}
110
111/// Sends everything the handshake has queued, framed when it is message-oriented.
112async fn send_all<H, T>(
113    handshake: &mut H,
114    io: &mut T,
115    framed: bool,
116) -> Result<(), DriveError<H::Error>>
117where
118    H: Handshake,
119    T: AsyncWrite + Unpin,
120{
121    while let Some(out) = handshake.transmit().map_err(DriveError::Handshake)? {
122        if framed {
123            write_frame(io, &out).await.map_err(transport_error)?;
124        } else {
125            io.write_all(&out).await.map_err(DriveError::Io)?;
126        }
127    }
128    io.flush().await.map_err(DriveError::Io)
129}
130
131/// Runs `work` until `deadline`, a passed deadline being [`DriveError::TimedOut`].
132async fn until<T, E>(
133    deadline: Instant,
134    work: impl Future<Output = Result<T, DriveError<E>>>,
135) -> Result<T, DriveError<E>> {
136    tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), work)
137        .await
138        .unwrap_or(Err(DriveError::TimedOut))
139}
140
141/// [`drive_stream`] that ends at `deadline`, through `tokio::time`: the runtime must have its
142/// timer enabled (tokio panics otherwise).
143///
144/// # Errors
145///
146/// [`DriveError::TimedOut`] when `deadline` passes first; otherwise as [`drive_stream`].
147pub async fn drive_stream_until<H, T>(
148    handshake: H,
149    io: &mut T,
150    deadline: Instant,
151) -> Result<Established<H::Output>, DriveError<H::Error>>
152where
153    H: Handshake,
154    T: AsyncRead + AsyncWrite + Unpin,
155{
156    until(deadline, drive_stream(handshake, io)).await
157}
158
159/// [`complete_stream`] that ends at `deadline`, as [`drive_stream_until`] does.
160///
161/// # Errors
162///
163/// As [`drive_stream_until`].
164pub async fn complete_stream_until<H, T>(
165    handshake: H,
166    io: &mut T,
167    deadline: Instant,
168) -> Result<H, DriveError<H::Error>>
169where
170    H: Handshake,
171    T: AsyncRead + AsyncWrite + Unpin,
172{
173    until(deadline, complete_stream(handshake, io)).await
174}
175
176/// [`drive_messages`] that ends at `deadline`, as [`drive_stream_until`] does.
177///
178/// # Errors
179///
180/// [`DriveError::TimedOut`] when `deadline` passes first; otherwise as [`drive_messages`].
181pub async fn drive_messages_until<H, T>(
182    handshake: H,
183    transport: &mut T,
184    deadline: Instant,
185) -> Result<Established<H::Output>, DriveError<H::Error>>
186where
187    H: Handshake,
188    T: MessageTransport,
189{
190    until(deadline, drive_messages(handshake, transport)).await
191}
192
193/// [`complete_messages`] that ends at `deadline`, as [`drive_stream_until`] does.
194///
195/// # Errors
196///
197/// As [`drive_messages_until`].
198pub async fn complete_messages_until<H, T>(
199    handshake: H,
200    transport: &mut T,
201    deadline: Instant,
202) -> Result<H, DriveError<H::Error>>
203where
204    H: Handshake,
205    T: MessageTransport,
206{
207    until(deadline, complete_messages(handshake, transport)).await
208}
209
210/// [`drive_messages`](crate::drive_messages) over an async message transport.
211///
212/// # Errors
213///
214/// [`DriveError`] when the transport fails or the handshake refuses the peer.
215pub async fn drive_messages<H, T>(
216    handshake: H,
217    transport: &mut T,
218) -> Result<Established<H::Output>, DriveError<H::Error>>
219where
220    H: Handshake,
221    T: MessageTransport,
222{
223    complete_messages(handshake, transport)
224        .await?
225        .finish()
226        .map_err(DriveError::Handshake)
227}
228
229/// [`complete_messages`](crate::complete_messages) over an async message transport: the
230/// handshake once complete, not yet finished.
231///
232/// # Errors
233///
234/// As [`drive_messages`].
235pub async fn complete_messages<H, T>(
236    mut handshake: H,
237    transport: &mut T,
238) -> Result<H, DriveError<H::Error>>
239where
240    H: Handshake,
241    T: MessageTransport,
242{
243    loop {
244        while let Some(out) = handshake.transmit().map_err(DriveError::Handshake)? {
245            transport.send(&out).await.map_err(DriveError::Io)?;
246        }
247        if handshake.is_complete() {
248            return Ok(handshake);
249        }
250        let message = transport.recv().await.map_err(DriveError::Io)?;
251        if let Err(error) = handshake.receive(&message) {
252            while let Ok(Some(out)) = handshake.transmit() {
253                if transport.send(&out).await.is_err() {
254                    break;
255                }
256            }
257            return Err(DriveError::Handshake(error));
258        }
259    }
260}