Skip to main content

coqui_peer/
transport.rs

1//! `coqui-transport` over `coqui-peer`'s own wire: the frame the drivers speak as a codec, and a
2//! channel as a [`MessageTransport`].
3
4use alloc::vec::Vec;
5use core::fmt;
6use core::time::Duration;
7use std::io;
8use std::sync::{Mutex, PoisonError};
9
10use coqui_transport::frame::{Codec, FrameError, LengthDecoder, LengthPrefix};
11use coqui_transport::{Channel, Failure};
12
13use crate::drive::{FrameTooLong, MAX_MESSAGE};
14use crate::{MessageTransport, ReadTimeout, WriteTimeout};
15
16/// The frame of [`write_frame`](crate::write_frame) and [`read_frame`](crate::read_frame): the
17/// message's length as four big-endian bytes, then the message; an empty message is a message.
18///
19/// It is [`LengthPrefix::u32_be`] by another name, so a `StreamChannel` on `PeerFrame` and a
20/// handshake driven by [`drive_stream`](crate::drive_stream) read each other's bytes. The bound on a
21/// message is the channel's (1 MiB by default, the number [`MAX_MESSAGE`] is), not this type's.
22#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
23pub struct PeerFrame;
24
25impl PeerFrame {
26    /// The codec this is, for a place that wants a [`LengthPrefix`].
27    pub const fn prefix() -> LengthPrefix {
28        LengthPrefix::u32_be()
29    }
30}
31
32impl Codec for PeerFrame {
33    type Decoder = LengthDecoder;
34
35    fn encode(&self, message: &[u8], maximum: usize) -> Result<Vec<u8>, FrameError> {
36        Self::prefix().encode(message, maximum)
37    }
38
39    fn decoder(&self, maximum: usize) -> LengthDecoder {
40        Self::prefix().decoder(maximum)
41    }
42}
43
44/// A [`Channel`] as a [`MessageTransport`], so a handshake can be driven over anything that
45/// carries messages.
46///
47/// A message over [`MAX_MESSAGE`] is refused either way (`InvalidInput` going out, `InvalidData`
48/// coming in), and so is a [`Failure::Protocol`]; the message drivers report both as
49/// [`DriveError::Io`](crate::DriveError::Io). The read and write timeouts the `_until` drivers
50/// set bound `receive` and `send_timeout`; a channel that ended in order is `UnexpectedEof`. Nothing here authenticates the peer: the handshake does.
51pub struct ChannelTransport<C> {
52    channel: C,
53    read: Mutex<Option<Duration>>,
54    write: Mutex<Option<Duration>>,
55}
56
57impl<C: Channel> ChannelTransport<C> {
58    /// A transport over `channel`, with no timeouts.
59    pub const fn new(channel: C) -> Self {
60        Self {
61            channel,
62            read: Mutex::new(None),
63            write: Mutex::new(None),
64        }
65    }
66
67    /// The channel, for closing it or asking its capabilities.
68    pub const fn channel(&self) -> &C {
69        &self.channel
70    }
71
72    /// The channel.
73    pub fn into_inner(self) -> C {
74        self.channel
75    }
76}
77
78impl<C> fmt::Debug for ChannelTransport<C> {
79    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
80        formatter
81            .debug_struct("ChannelTransport")
82            .finish_non_exhaustive()
83    }
84}
85
86fn current(timeout: &Mutex<Option<Duration>>) -> Option<Duration> {
87    *timeout.lock().unwrap_or_else(PoisonError::into_inner)
88}
89
90fn set(timeout: &Mutex<Option<Duration>>, value: Option<Duration>) {
91    *timeout.lock().unwrap_or_else(PoisonError::into_inner) = value;
92}
93
94/// The `io::Error` of a channel failure, keeping the failure as its source.
95fn failure(error: Failure, size: io::ErrorKind) -> io::Error {
96    match error {
97        Failure::Protocol => io::Error::new(size, FrameTooLong),
98        Failure::Timeout | Failure::NoProgress => io::Error::new(io::ErrorKind::TimedOut, error),
99        Failure::PathLost => io::Error::new(io::ErrorKind::ConnectionReset, error),
100        Failure::Unsupported => io::Error::new(io::ErrorKind::Unsupported, error),
101        Failure::Certificate | Failure::PeerProof | Failure::Permission => {
102            io::Error::new(io::ErrorKind::PermissionDenied, error)
103        }
104        _ => io::Error::other(error),
105    }
106}
107
108impl<C: Channel> MessageTransport for ChannelTransport<C> {
109    fn send(&mut self, message: &[u8]) -> io::Result<()> {
110        if message.len() > MAX_MESSAGE {
111            return Err(io::Error::new(io::ErrorKind::InvalidInput, FrameTooLong));
112        }
113        self.channel
114            .send_timeout(message, current(&self.write))
115            .map_err(|error| failure(error, io::ErrorKind::InvalidInput))
116    }
117
118    fn recv(&mut self) -> io::Result<Vec<u8>> {
119        let message = self
120            .channel
121            .receive(current(&self.read))
122            .map_err(|error| failure(error, io::ErrorKind::InvalidData))?
123            .ok_or(io::ErrorKind::UnexpectedEof)?;
124        if message.len() > MAX_MESSAGE {
125            return Err(io::Error::new(io::ErrorKind::InvalidData, FrameTooLong));
126        }
127        Ok(message)
128    }
129}
130
131impl<C> ReadTimeout for ChannelTransport<C> {
132    fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
133        set(&self.read, timeout);
134        Ok(())
135    }
136}
137
138impl<C> WriteTimeout for ChannelTransport<C> {
139    fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
140        set(&self.write, timeout);
141        Ok(())
142    }
143}