Skip to main content

coqui_peer/
drive.rs

1//! Blocking loops that run a [`Handshake`] over a transport.
2
3use core::fmt;
4use core::time::Duration;
5use std::io::{self, Read, Write};
6use std::net::TcpStream;
7use std::time::Instant;
8
9use crate::method::{Established, Framing, Handshake};
10
11/// The longest message [`drive_stream`] frames or accepts, in bytes.
12pub const MAX_MESSAGE: usize = 1 << 20;
13
14const CHUNK: usize = 16 * 1024;
15
16/// The marker inside the `io::Error` a frame function returns for a frame longer than
17/// [`MAX_MESSAGE`], so the drivers can report it as [`DriveError::TooLong`].
18#[derive(Debug)]
19pub(crate) struct FrameTooLong;
20
21impl fmt::Display for FrameTooLong {
22    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23        formatter.write_str("frame is longer than MAX_MESSAGE")
24    }
25}
26
27impl core::error::Error for FrameTooLong {}
28
29/// The four-byte big-endian length that opens a frame of `length` bytes.
30pub(crate) fn frame_header(length: usize, kind: io::ErrorKind) -> io::Result<[u8; 4]> {
31    match u32::try_from(length) {
32        Ok(header) if length <= MAX_MESSAGE => Ok(header.to_be_bytes()),
33        _ => Err(io::Error::new(kind, FrameTooLong)),
34    }
35}
36
37/// The length a frame header declares, refused above [`MAX_MESSAGE`].
38pub(crate) fn frame_length(header: [u8; 4]) -> io::Result<u64> {
39    let length = u32::from_be_bytes(header);
40    frame_header(
41        usize::try_from(length).unwrap_or(usize::MAX),
42        io::ErrorKind::InvalidData,
43    )?;
44    Ok(u64::from(length))
45}
46
47/// A short frame body: the stream ended inside it.
48pub(crate) fn check_whole(message: &[u8], length: u64) -> io::Result<()> {
49    if u64::try_from(message.len()).ok() == Some(length) {
50        Ok(())
51    } else {
52        Err(io::ErrorKind::UnexpectedEof.into())
53    }
54}
55
56/// The driver error for an `io::Error` from the transport or a frame function.
57pub(crate) fn transport_error<E>(error: io::Error) -> DriveError<E> {
58    if error
59        .get_ref()
60        .is_some_and(|inner| inner.is::<FrameTooLong>())
61    {
62        DriveError::TooLong
63    } else {
64        DriveError::Io(error)
65    }
66}
67
68/// Writes `message` as one frame, its length first as four big-endian bytes, and flushes.
69///
70/// This is the framing [`drive_stream`] gives a [`Framing::Message`] handshake, for a method
71/// that sends other messages over the same stream (a pairing exchange, an announcement).
72///
73/// # Errors
74///
75/// `InvalidInput` when `message` is longer than [`MAX_MESSAGE`]; otherwise the stream's error.
76pub fn write_frame<W: Write + ?Sized>(io: &mut W, message: &[u8]) -> io::Result<()> {
77    io.write_all(&frame_header(message.len(), io::ErrorKind::InvalidInput)?)?;
78    io.write_all(message)?;
79    io.flush()
80}
81
82/// Reads one frame written by [`write_frame`]. The buffer grows as bytes arrive, so a declared
83/// length costs nothing until the peer sends it.
84///
85/// # Errors
86///
87/// `InvalidData` when the declared length is above [`MAX_MESSAGE`], `UnexpectedEof` when the
88/// stream ends inside the frame; otherwise the stream's error.
89pub fn read_frame<R: Read + ?Sized>(io: &mut R) -> io::Result<Vec<u8>> {
90    let mut header = [0u8; 4];
91    io.read_exact(&mut header)?;
92    let length = frame_length(header)?;
93    let mut message = Vec::new();
94    io.take(length).read_to_end(&mut message)?;
95    check_whole(&message, length)?;
96    Ok(message)
97}
98
99/// Why driving a handshake failed.
100#[derive(Debug)]
101#[non_exhaustive]
102pub enum DriveError<E> {
103    /// The transport failed or closed before the handshake finished.
104    Io(io::Error),
105    /// The handshake refused the peer or failed.
106    Handshake(E),
107    /// A peer sent a frame longer than [`MAX_MESSAGE`].
108    TooLong,
109    /// The deadline of an `_until` loop passed before the handshake was complete.
110    TimedOut,
111}
112
113impl<E: core::error::Error + 'static> fmt::Display for DriveError<E> {
114    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
115        match self {
116            Self::Io(_) => formatter.write_str("transport failed during the handshake"),
117            Self::Handshake(error) => write!(formatter, "handshake failed: {error}"),
118            Self::TooLong => formatter.write_str("handshake message is too long"),
119            Self::TimedOut => formatter.write_str("handshake did not complete before its deadline"),
120        }
121    }
122}
123
124impl<E: core::error::Error + 'static> core::error::Error for DriveError<E> {
125    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
126        match self {
127            Self::Io(error) => Some(error),
128            Self::Handshake(error) => Some(error),
129            Self::TooLong | Self::TimedOut => None,
130        }
131    }
132}
133
134/// A blocking transport of whole messages: WebSocket messages, datagrams, a shared-memory
135/// queue.
136pub trait MessageTransport {
137    /// Sends one message.
138    ///
139    /// # Errors
140    ///
141    /// When the transport fails.
142    fn send(&mut self, message: &[u8]) -> io::Result<()>;
143
144    /// Receives the next message.
145    ///
146    /// # Errors
147    ///
148    /// When the transport fails or is closed.
149    fn recv(&mut self) -> io::Result<Vec<u8>>;
150}
151
152/// A blocking transport whose reads can be bounded in time, as the `_until` loops need to end
153/// at their deadline.
154///
155/// Implemented for [`TcpStream`] and `&TcpStream` (a socket shared with another thread, which
156/// may shut it down). A transport that cannot time out implements it as a no-op; a loop over
157/// it then checks its deadline only between reads, and a read that never returns holds it
158/// past the deadline.
159pub trait ReadTimeout {
160    /// Sets the timeout of every read from now on; `None` waits forever.
161    ///
162    /// # Errors
163    ///
164    /// When the transport refuses the setting.
165    fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()>;
166}
167
168impl ReadTimeout for TcpStream {
169    fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
170        TcpStream::set_read_timeout(self, timeout)
171    }
172}
173
174impl ReadTimeout for &TcpStream {
175    fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
176        TcpStream::set_read_timeout(self, timeout)
177    }
178}
179
180/// A blocking transport whose writes can be bounded in time, as the `_until` loops need when
181/// the peer stops reading.
182///
183/// Implemented for [`TcpStream`] and `&TcpStream`. A transport that cannot time out
184/// implements it as a no-op; a write the peer never drains then holds the loop past its
185/// deadline.
186pub trait WriteTimeout {
187    /// Sets the timeout of every write from now on; `None` waits forever.
188    ///
189    /// # Errors
190    ///
191    /// When the transport refuses the setting.
192    fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()>;
193}
194
195impl WriteTimeout for TcpStream {
196    fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
197        TcpStream::set_write_timeout(self, timeout)
198    }
199}
200
201impl WriteTimeout for &TcpStream {
202    fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
203        TcpStream::set_write_timeout(self, timeout)
204    }
205}
206
207/// A transport whose every read and write waits at most what is left until `until`.
208struct Bounded<'a, T: ?Sized> {
209    io: &'a mut T,
210    until: Instant,
211}
212
213impl<T: ?Sized> Bounded<'_, T> {
214    /// What is left until the deadline; `TimedOut` once it has passed.
215    fn left(&self) -> io::Result<Duration> {
216        self.until
217            .checked_duration_since(Instant::now())
218            .filter(|left| !left.is_zero())
219            .ok_or_else(|| io::ErrorKind::TimedOut.into())
220    }
221}
222
223impl<T: ReadTimeout + ?Sized> Bounded<'_, T> {
224    fn arm_read(&self) -> io::Result<()> {
225        self.io.set_read_timeout(Some(self.left()?))
226    }
227}
228
229impl<T: WriteTimeout + ?Sized> Bounded<'_, T> {
230    fn arm_write(&self) -> io::Result<()> {
231        self.io.set_write_timeout(Some(self.left()?))
232    }
233}
234
235impl<T: Read + ReadTimeout + ?Sized> Read for Bounded<'_, T> {
236    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
237        self.arm_read()?;
238        self.io.read(buffer)
239    }
240}
241
242impl<T: Write + WriteTimeout + ?Sized> Write for Bounded<'_, T> {
243    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
244        self.arm_write()?;
245        self.io.write(buffer)
246    }
247
248    fn flush(&mut self) -> io::Result<()> {
249        self.arm_write()?;
250        self.io.flush()
251    }
252}
253
254impl<T: MessageTransport + ReadTimeout + WriteTimeout + ?Sized> MessageTransport
255    for Bounded<'_, T>
256{
257    fn send(&mut self, message: &[u8]) -> io::Result<()> {
258        self.arm_write()?;
259        self.io.send(message)
260    }
261
262    fn recv(&mut self) -> io::Result<Vec<u8>> {
263        self.arm_read()?;
264        self.io.recv()
265    }
266}
267
268/// A transport failure once `until` has passed is the deadline's, and so is a timeout the
269/// armed bound produced: an operating system may end a timed read or write a little early.
270fn past<E>(until: Instant, error: DriveError<E>) -> DriveError<E> {
271    match error {
272        DriveError::Io(error)
273            if Instant::now() >= until
274                || matches!(
275                    error.kind(),
276                    io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
277                ) =>
278        {
279            DriveError::TimedOut
280        }
281        other => other,
282    }
283}
284
285/// Runs `handshake` to completion over a blocking byte stream.
286///
287/// A [`Framing::Stream`] handshake exchanges its bytes as they are; a [`Framing::Message`]
288/// handshake has each message prefixed with its length, four big-endian bytes. Nothing is
289/// read once the handshake is complete.
290///
291/// # Errors
292///
293/// [`DriveError`] when the stream fails or closes, or the handshake refuses the peer.
294pub fn drive_stream<H, T>(
295    handshake: H,
296    io: &mut T,
297) -> Result<Established<H::Output>, DriveError<H::Error>>
298where
299    H: Handshake,
300    T: Read + Write,
301{
302    complete_stream(handshake, io)?
303        .finish()
304        .map_err(DriveError::Handshake)
305}
306
307/// [`drive_stream`] without the final [`finish`](Handshake::finish): returns the handshake
308/// once it [`is_complete`](Handshake::is_complete), with everything it queued sent.
309///
310/// For a method whose own way of finishing differs from [`Handshake::finish`], such as a TLS
311/// server that does not authenticate its client at that layer and so has no verified peer to
312/// name. The caller finishes it with the method's own call.
313///
314/// # Errors
315///
316/// As [`drive_stream`].
317pub fn complete_stream<H, T>(mut handshake: H, io: &mut T) -> Result<H, DriveError<H::Error>>
318where
319    H: Handshake,
320    T: Read + Write,
321{
322    let framed = handshake.framing() == Framing::Message;
323    let mut buffer = vec![0u8; CHUNK];
324    loop {
325        send_all(&mut handshake, io, framed)?;
326        if handshake.is_complete() {
327            return Ok(handshake);
328        }
329        let received = if framed {
330            let message = read_frame(io).map_err(transport_error)?;
331            handshake.receive(&message)
332        } else {
333            let read = io.read(&mut buffer).map_err(DriveError::Io)?;
334            if read == 0 {
335                return Err(DriveError::Io(io::ErrorKind::UnexpectedEof.into()));
336            }
337            handshake.receive(&buffer[..read])
338        };
339        if let Err(error) = received {
340            // A method may have queued a refusal to tell the peer (a TLS alert).
341            let _ = send_all(&mut handshake, io, framed);
342            return Err(DriveError::Handshake(error));
343        }
344    }
345}
346
347/// [`drive_stream`] that ends at `deadline`: every read and write waits at most what is left
348/// until it, through [`ReadTimeout`] and [`WriteTimeout`], and both timeouts are cleared
349/// before it returns.
350///
351/// # Errors
352///
353/// [`DriveError::TimedOut`] when `deadline` passes first; otherwise as [`drive_stream`].
354pub fn drive_stream_until<H, T>(
355    handshake: H,
356    io: &mut T,
357    deadline: Instant,
358) -> Result<Established<H::Output>, DriveError<H::Error>>
359where
360    H: Handshake,
361    T: Read + Write + ReadTimeout + WriteTimeout,
362{
363    complete_stream_until(handshake, io, deadline)?
364        .finish()
365        .map_err(DriveError::Handshake)
366}
367
368/// [`complete_stream`] that ends at `deadline`, as [`drive_stream_until`] does.
369///
370/// # Errors
371///
372/// As [`drive_stream_until`].
373pub fn complete_stream_until<H, T>(
374    handshake: H,
375    io: &mut T,
376    deadline: Instant,
377) -> Result<H, DriveError<H::Error>>
378where
379    H: Handshake,
380    T: Read + Write + ReadTimeout + WriteTimeout,
381{
382    let result = complete_stream(
383        handshake,
384        &mut Bounded {
385            io: &mut *io,
386            until: deadline,
387        },
388    )
389    .map_err(|error| past(deadline, error));
390    let _ = io.set_read_timeout(None);
391    let _ = io.set_write_timeout(None);
392    result
393}
394
395/// Sends everything the handshake has queued, framed when it is message-oriented.
396fn send_all<H, T>(handshake: &mut H, io: &mut T, framed: bool) -> Result<(), DriveError<H::Error>>
397where
398    H: Handshake,
399    T: Write,
400{
401    while let Some(out) = handshake.transmit().map_err(DriveError::Handshake)? {
402        if framed {
403            write_frame(io, &out).map_err(transport_error)?;
404        } else {
405            io.write_all(&out).map_err(DriveError::Io)?;
406        }
407    }
408    io.flush().map_err(DriveError::Io)
409}
410
411/// Runs `handshake` to completion over a blocking message transport. Each message the
412/// handshake sends is one transport message, and each received one is handed over whole,
413/// for either [`Framing`].
414///
415/// Use a transport that delivers messages reliably and in order; a handshake does not
416/// recover from a lost datagram.
417///
418/// # Errors
419///
420/// [`DriveError`] when the transport fails or the handshake refuses the peer.
421pub fn drive_messages<H, T>(
422    handshake: H,
423    transport: &mut T,
424) -> Result<Established<H::Output>, DriveError<H::Error>>
425where
426    H: Handshake,
427    T: MessageTransport,
428{
429    complete_messages(handshake, transport)?
430        .finish()
431        .map_err(DriveError::Handshake)
432}
433
434/// [`drive_messages`] without the final [`finish`](Handshake::finish), as
435/// [`complete_stream`] is to [`drive_stream`].
436///
437/// # Errors
438///
439/// As [`drive_messages`].
440pub fn complete_messages<H, T>(
441    mut handshake: H,
442    transport: &mut T,
443) -> Result<H, DriveError<H::Error>>
444where
445    H: Handshake,
446    T: MessageTransport,
447{
448    loop {
449        while let Some(out) = handshake.transmit().map_err(DriveError::Handshake)? {
450            transport.send(&out).map_err(DriveError::Io)?;
451        }
452        if handshake.is_complete() {
453            return Ok(handshake);
454        }
455        let message = transport.recv().map_err(DriveError::Io)?;
456        handshake.receive(&message).map_err(DriveError::Handshake)?;
457    }
458}
459
460/// [`drive_messages`] that ends at `deadline`: every receive and send waits at most what is
461/// left until it, through [`ReadTimeout`] and [`WriteTimeout`], and both timeouts are cleared
462/// before it returns.
463///
464/// # Errors
465///
466/// [`DriveError::TimedOut`] when `deadline` passes first; otherwise as [`drive_messages`].
467pub fn drive_messages_until<H, T>(
468    handshake: H,
469    transport: &mut T,
470    deadline: Instant,
471) -> Result<Established<H::Output>, DriveError<H::Error>>
472where
473    H: Handshake,
474    T: MessageTransport + ReadTimeout + WriteTimeout,
475{
476    complete_messages_until(handshake, transport, deadline)?
477        .finish()
478        .map_err(DriveError::Handshake)
479}
480
481/// [`complete_messages`] that ends at `deadline`, as [`drive_messages_until`] does.
482///
483/// # Errors
484///
485/// As [`drive_messages_until`].
486pub fn complete_messages_until<H, T>(
487    handshake: H,
488    transport: &mut T,
489    deadline: Instant,
490) -> Result<H, DriveError<H::Error>>
491where
492    H: Handshake,
493    T: MessageTransport + ReadTimeout + WriteTimeout,
494{
495    let result = complete_messages(
496        handshake,
497        &mut Bounded {
498            io: &mut *transport,
499            until: deadline,
500        },
501    )
502    .map_err(|error| past(deadline, error));
503    let _ = transport.set_read_timeout(None);
504    let _ = transport.set_write_timeout(None);
505    result
506}