oxedyne/fe2o3/fe2o3_net/src/lineio.rs
10.0 KiB, 15 runs
created by r537758799:77722, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! The bytes under a line protocol client, apart from the client. |
| 2 | //! |
| 3 | //! IMAP and SMTP clients speak in lines, raw byte runs of a known length, writes and one TLS |
| 4 | //! upgrade. [`LineIo`] is that and nothing more, so a client written against it runs over a |
| 5 | //! socket here ([`TcpLineIo`], under `async`) and over bytes a browser carries through a tunnel, |
| 6 | //! where there is no socket and no tokio. The client keeps the protocol; the I/O keeps the stream, |
| 7 | //! its buffer, the certificate check and the clock. |
| 8 | //! |
| 9 | //! What a client relies on of every implementation: |
| 10 | //! - each call is held to the I/O's own per-step deadline, and one that passes fails tagged |
| 11 | //! `Timeout`; |
| 12 | //! - a connection that went away fails tagged `Interrupted`, which is what a client's retry of a |
| 13 | //! dropped connection keys on; |
| 14 | //! - [`LineIo::read_line`] answers an empty line at the end of the stream, so the client names |
| 15 | //! the close once, whatever carries it; |
| 16 | //! - [`LineIo::starttls`] refuses when the peer has sent anything not yet read, because bytes |
| 17 | //! pipelined behind the server's go-ahead arrived unprotected (RFC 2595 §3.1); |
| 18 | //! - [`LineIo::now`] never goes back, so a client can hold a whole answer of many lines to one |
| 19 | //! deadline, giving each read the time left; past it a read takes only what has come. |
| 20 | |
| 21 | use oxedyne_fe2o3_core::prelude::*; |
| 22 | |
| 23 | use std::time::Duration; |
| 24 | |
| 25 | |
| 26 | /// `async fn` without a `Send` bound, as `fe2o3_mail`'s `MailSession`: a browser's tunnel is |
| 27 | /// single-threaded, and a concrete socket's futures stay `Send` where its caller needs them so. |
| 28 | #[allow(async_fn_in_trait)] |
| 29 | pub trait LineIo: Sized { |
| 30 | /// Written and flushed. |
| 31 | async fn write_all(&mut self, bytes: &[u8]) -> Outcome<()>; |
| 32 | /// One line with its LF, returned only at the LF, at `max` bytes, or at the end of the stream |
| 33 | /// (then empty, or the bytes before it): never part of a line because no more has come yet. |
| 34 | /// The caller refuses a line cut short. |
| 35 | async fn read_line(&mut self, max: usize) -> Outcome<Vec<u8>>; |
| 36 | /// Exactly `n` bytes, the caller having bounded `n`. |
| 37 | async fn read_exact(&mut self, n: usize) -> Outcome<Vec<u8>>; |
| 38 | /// TLS over the stream from here on, the certificate validated for `host`. |
| 39 | async fn starttls(&mut self, host: &str) -> Outcome<()>; |
| 40 | /// A fresh connection to the same end, protected as this one was before its first byte. |
| 41 | async fn redial(&self) -> Outcome<Self>; |
| 42 | /// Ends the stream; nothing waits on the answer. |
| 43 | async fn shutdown(&mut self); |
| 44 | /// The deadline of each step from here on. |
| 45 | fn set_timeout(&mut self, step: Duration); |
| 46 | /// Time since an origin of the I/O's own, by a monotonic clock: natively the process's, in |
| 47 | /// a browser `performance.now()`, which `std` cannot reach there. |
| 48 | fn now(&self) -> Duration { |
| 49 | #[cfg(not(target_arch = "wasm32"))] |
| 50 | { |
| 51 | static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); |
| 52 | ORIGIN.get_or_init(std::time::Instant::now).elapsed() |
| 53 | } |
| 54 | #[cfg(target_arch = "wasm32")] |
| 55 | { |
| 56 | Duration::try_from_secs_f64(oxedyne_fe2o3_core::wasm::mono_ms() / 1000.0) |
| 57 | .unwrap_or(Duration::ZERO) |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | |
| 63 | #[cfg(feature = "async")] |
| 64 | pub use native::{ |
| 65 | Dial, |
| 66 | TcpLineIo, |
| 67 | }; |
| 68 | |
| 69 | #[cfg(feature = "async")] |
| 70 | mod native { |
| 71 | use super::LineIo; |
| 72 | |
| 73 | use crate::tls::{ |
| 74 | self, |
| 75 | ClientStream, |
| 76 | }; |
| 77 | |
| 78 | use oxedyne_fe2o3_core::prelude::*; |
| 79 | |
| 80 | use std::{ |
| 81 | sync::Arc, |
| 82 | time::Duration, |
| 83 | }; |
| 84 | |
| 85 | use tokio::{ |
| 86 | io::{ |
| 87 | AsyncBufReadExt, |
| 88 | AsyncReadExt, |
| 89 | AsyncWriteExt, |
| 90 | BufReader, |
| 91 | }, |
| 92 | net::TcpStream, |
| 93 | time::timeout, |
| 94 | }; |
| 95 | use tokio_rustls::rustls::ClientConfig; |
| 96 | |
| 97 | |
| 98 | /// Where a [`TcpLineIo`] connects, and how. |
| 99 | #[derive(Clone)] |
| 100 | pub struct Dial { |
| 101 | pub addr: String, // `host:port`, or a pinned address |
| 102 | pub host: String, // the name a certificate is validated against |
| 103 | pub implicit: bool, // TLS from the first byte |
| 104 | pub peer: String, // named in errors: "IMAP server mail.example.com" |
| 105 | pub tls: Arc<ClientConfig>, |
| 106 | pub timeout: Duration, // per step |
| 107 | } |
| 108 | |
| 109 | /// The tokio socket. Buffered, because a literal is read to the byte. |
| 110 | pub struct TcpLineIo { |
| 111 | // An `Option` only so that the upgrade can move the socket out, wrap it and put it back; |
| 112 | // `None` is a failed upgrade and a dead connection. |
| 113 | stream: Option<BufReader<ClientStream>>, |
| 114 | at: Dial, |
| 115 | redial: bool, // false for a stream handed in, which this process may not dial again |
| 116 | } |
| 117 | |
| 118 | impl TcpLineIo { |
| 119 | |
| 120 | pub async fn dial(at: Dial) -> Outcome<Self> { |
| 121 | let plain = match timeout(at.timeout, TcpStream::connect(&at.addr)).await { |
| 122 | Ok(Ok(s)) => s, |
| 123 | Ok(Err(e)) => return Err(tls::dial_fault(e, |
| 124 | fmt!("Connecting to {} at {}", at.peer, at.addr))), |
| 125 | Err(_) => return Err(err!( |
| 126 | "Timeout connecting to {} at {}.", at.peer, at.addr; |
| 127 | IO, Network, Timeout)), |
| 128 | }; |
| 129 | let mut io = res!(Self::over(plain, at).await); |
| 130 | io.redial = true; |
| 131 | Ok(io) |
| 132 | } |
| 133 | |
| 134 | /// A stream someone else connected; [`LineIo::redial`] refuses. |
| 135 | pub async fn over(plain: TcpStream, at: Dial) -> Outcome<Self> { |
| 136 | let stream = if at.implicit { |
| 137 | res!(tls::upgrade(plain, &at.host, at.tls.clone(), at.timeout).await) |
| 138 | } else { |
| 139 | ClientStream::Plain(plain) |
| 140 | }; |
| 141 | Ok(Self { stream: Some(BufReader::new(stream)), at, redial: false }) |
| 142 | } |
| 143 | |
| 144 | fn stream_mut(&mut self) -> Outcome<&mut BufReader<ClientStream>> { |
| 145 | match self.stream.as_mut() { |
| 146 | Some(s) => Ok(s), |
| 147 | None => Err(err!( |
| 148 | "The connection to {} was dropped by a failed TLS upgrade.", self.at.peer; |
| 149 | IO, Network, Missing)), |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | impl LineIo for TcpLineIo { |
| 155 | |
| 156 | async fn write_all(&mut self, bytes: &[u8]) -> Outcome<()> { |
| 157 | let peer = self.at.peer.clone(); |
| 158 | let deadline = self.at.timeout; |
| 159 | let w = res!(self.stream_mut()).get_mut(); |
| 160 | match timeout(deadline, w.write_all(bytes)).await { |
| 161 | Ok(Ok(())) => (), |
| 162 | Ok(Err(e)) => return Err(tls::wire_fault(e, fmt!("Writing to {}", peer), true)), |
| 163 | Err(_) => return Err(err!( |
| 164 | "Timeout writing to {}.", peer; IO, Network, Timeout)), |
| 165 | } |
| 166 | match timeout(deadline, w.flush()).await { |
| 167 | Ok(Ok(())) => Ok(()), |
| 168 | Ok(Err(e)) => Err(tls::wire_fault(e, fmt!("Flushing to {}", peer), true)), |
| 169 | Err(_) => Err(err!( |
| 170 | "Timeout flushing to {}.", peer; IO, Network, Timeout)), |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | async fn read_line(&mut self, max: usize) -> Outcome<Vec<u8>> { |
| 175 | let mut buf: Vec<u8> = Vec::with_capacity(256); |
| 176 | let peer = self.at.peer.clone(); |
| 177 | let deadline = self.at.timeout; |
| 178 | let mut rd = res!(self.stream_mut()).take(max as u64); |
| 179 | match timeout(deadline, rd.read_until(b'\n', &mut buf)).await { |
| 180 | Ok(Ok(_)) => Ok(buf), |
| 181 | Ok(Err(e)) => Err(tls::wire_fault(e, fmt!("Reading from {}", peer), false)), |
| 182 | Err(_) => Err(err!( |
| 183 | "Timeout reading from {}.", peer; IO, Network, Timeout)), |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | async fn read_exact(&mut self, n: usize) -> Outcome<Vec<u8>> { |
| 188 | let mut buf = vec![0u8; n]; |
| 189 | let peer = self.at.peer.clone(); |
| 190 | let deadline = self.at.timeout; |
| 191 | let rd = res!(self.stream_mut()); |
| 192 | match timeout(deadline, rd.read_exact(&mut buf)).await { |
| 193 | Ok(Ok(_)) => Ok(buf), |
| 194 | Ok(Err(e)) => Err(tls::wire_fault(e, |
| 195 | fmt!("Reading a {}-byte literal from {}", n, peer), false)), |
| 196 | Err(_) => Err(err!( |
| 197 | "Timeout reading a {}-byte literal from {}.", n, peer; |
| 198 | IO, Network, Timeout)), |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | async fn starttls(&mut self, host: &str) -> Outcome<()> { |
| 203 | let buffered = match self.stream.take() { |
| 204 | Some(s) => s, |
| 205 | None => return Err(err!( |
| 206 | "The connection to {} was dropped by a failed TLS upgrade.", self.at.peer; |
| 207 | IO, Network, Missing)), |
| 208 | }; |
| 209 | // Refused rather than discarded: the downgrade attack is the discarding. |
| 210 | if !buffered.buffer().is_empty() { |
| 211 | return Err(err!( |
| 212 | "{} sent data after its STARTTLS response, before the handshake. \ |
| 213 | Refusing to continue.", self.at.peer; |
| 214 | IO, Network, Security)); |
| 215 | } |
| 216 | let plain = match buffered.into_inner().into_plain() { |
| 217 | Some(s) => s, |
| 218 | None => return Err(err!( |
| 219 | "STARTTLS issued on an already-protected connection to {}.", self.at.peer; |
| 220 | Invalid, Bug)), |
| 221 | }; |
| 222 | let up = res!(tls::upgrade(plain, host, self.at.tls.clone(), self.at.timeout).await); |
| 223 | self.stream = Some(BufReader::new(up)); |
| 224 | Ok(()) |
| 225 | } |
| 226 | |
| 227 | async fn redial(&self) -> Outcome<Self> { |
| 228 | if !self.redial { |
| 229 | return Err(err!( |
| 230 | "The stream to {} was handed in, and this process does not dial.", self.at.peer; |
| 231 | IO, Network, Missing)); |
| 232 | } |
| 233 | Self::dial(self.at.clone()).await |
| 234 | } |
| 235 | |
| 236 | async fn shutdown(&mut self) { |
| 237 | let deadline = self.at.timeout; |
| 238 | if let Some(s) = self.stream.as_mut() { |
| 239 | let _ = timeout(deadline, s.get_mut().shutdown()).await; |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | fn set_timeout(&mut self, step: Duration) { |
| 244 | self.at.timeout = step; |
| 245 | } |
| 246 | } |
| 247 | } |