Skip to main content

schedr_tls/
incoming.rs

1//! Accepted connections, after the TLS handshake when there is TLS: one listener type for the
2//! master's gRPC server (a [`Stream`] for tonic) and a worker's log endpoint (an axum
3//! [`Listener`]).
4//!
5//! Handshakes run beside the accept loop, each with a time limit, so a slow or silent client
6//! holds up no one. A handshake that fails over certificates (e.g. a client without one from
7//! the CA) is logged as a warning; one that just ends (a TCP probe) only at debug level. At
8//! most its `handshakes_at_once` ([`MAX_HANDSHAKES`] by default) run at once; beyond that,
9//! accepting waits.
10
11use std::io;
12use std::net::SocketAddr;
13use std::pin::Pin;
14use std::sync::Arc;
15use std::task::{Context, Poll};
16use std::time::Duration;
17
18use axum::serve::Listener;
19use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
20use tokio::net::{TcpListener, TcpStream};
21use tokio::sync::{Semaphore, mpsc};
22use tokio::task::JoinHandle;
23use tokio_rustls::TlsAcceptor;
24use tokio_rustls::server::TlsStream;
25use tokio_stream::Stream;
26use tonic::transport::server::{Connected, TcpConnectInfo};
27
28use crate::reload::Tls;
29
30/// How long a client has to complete the TLS handshake, unless `handshake_timeout` says.
31pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
32
33/// How long a listener waits after a failed accept, unless `accept_retry` says.
34pub const ACCEPT_RETRY: Duration = Duration::from_millis(100);
35
36/// How many handshakes may run at once; beyond that, accepting waits (a flood of connections
37/// that never finish holds this many sockets, not all of them).
38pub const MAX_HANDSHAKES: usize = 256;
39
40/// Which configuration the handshake uses.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Protocol {
43    /// gRPC (the master).
44    Grpc,
45    /// HTTP/1.1 (a worker's log endpoint).
46    Http,
47    /// HTTP/1.1 for `schedr ui` alone (a webserver's UI port: the client's certificate must
48    /// name `[tls] ui_name`).
49    Ui,
50}
51
52/// An accepted connection.
53#[derive(Debug)]
54pub enum Conn {
55    /// Plain TCP (`mesh` mode, standalone).
56    Plain(TcpStream),
57    /// After a TLS handshake that checked the client's certificate.
58    Tls(Box<TlsStream<TcpStream>>),
59}
60
61impl Conn {
62    fn tcp(&self) -> &TcpStream {
63        match self {
64            Self::Plain(tcp) => tcp,
65            Self::Tls(tls) => tls.get_ref().0,
66        }
67    }
68}
69
70impl AsyncRead for Conn {
71    fn poll_read(
72        self: Pin<&mut Self>,
73        cx: &mut Context<'_>,
74        buf: &mut ReadBuf<'_>,
75    ) -> Poll<io::Result<()>> {
76        match self.get_mut() {
77            Self::Plain(tcp) => Pin::new(tcp).poll_read(cx, buf),
78            Self::Tls(tls) => Pin::new(tls.as_mut()).poll_read(cx, buf),
79        }
80    }
81}
82
83impl AsyncWrite for Conn {
84    fn poll_write(
85        self: Pin<&mut Self>,
86        cx: &mut Context<'_>,
87        buf: &[u8],
88    ) -> Poll<io::Result<usize>> {
89        match self.get_mut() {
90            Self::Plain(tcp) => Pin::new(tcp).poll_write(cx, buf),
91            Self::Tls(tls) => Pin::new(tls.as_mut()).poll_write(cx, buf),
92        }
93    }
94
95    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
96        match self.get_mut() {
97            Self::Plain(tcp) => Pin::new(tcp).poll_flush(cx),
98            Self::Tls(tls) => Pin::new(tls.as_mut()).poll_flush(cx),
99        }
100    }
101
102    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
103        match self.get_mut() {
104            Self::Plain(tcp) => Pin::new(tcp).poll_shutdown(cx),
105            Self::Tls(tls) => Pin::new(tls.as_mut()).poll_shutdown(cx),
106        }
107    }
108}
109
110impl Connected for Conn {
111    type ConnectInfo = TcpConnectInfo;
112
113    fn connect_info(&self) -> TcpConnectInfo {
114        TcpConnectInfo {
115            local_addr: self.tcp().local_addr().ok(),
116            remote_addr: self.tcp().peer_addr().ok(),
117        }
118    }
119}
120
121/// Connections accepted on a listener; the accept loop stops when this is dropped.
122#[derive(Debug)]
123pub struct Incoming {
124    accepted: mpsc::Receiver<(Conn, SocketAddr)>,
125    local: SocketAddr,
126    task: JoinHandle<()>,
127}
128
129impl Drop for Incoming {
130    fn drop(&mut self) {
131        self.task.abort();
132    }
133}
134
135/// Accepts connections on `listener`, with a TLS handshake for `protocol` when `tls` is given.
136///
137/// # Errors
138///
139/// An I/O error if the listener's address can't be read.
140pub fn incoming(
141    listener: TcpListener,
142    tls: Option<Tls>,
143    protocol: Protocol,
144    accept_retry: Duration,
145) -> io::Result<Incoming> {
146    let local = listener.local_addr()?;
147    let (accepted_tx, accepted) = mpsc::channel(64);
148    let task = tokio::spawn(accept_loop(
149        listener,
150        tls,
151        protocol,
152        accept_retry,
153        accepted_tx,
154    ));
155    Ok(Incoming {
156        accepted,
157        local,
158        task,
159    })
160}
161
162async fn accept_loop(
163    listener: TcpListener,
164    tls: Option<Tls>,
165    protocol: Protocol,
166    accept_retry: Duration,
167    accepted: mpsc::Sender<(Conn, SocketAddr)>,
168) {
169    let most = tls.as_ref().map_or(MAX_HANDSHAKES, Tls::handshakes_at_once);
170    let handshakes = Arc::new(Semaphore::new(most));
171    loop {
172        // Never fails: the semaphore isn't closed.
173        let Ok(permit) = handshakes.clone().acquire_owned().await else {
174            return;
175        };
176        let (tcp, peer) = match listener.accept().await {
177            Ok(connection) => connection,
178            Err(error) => {
179                // E.g. too many open files: wait instead of spinning.
180                tracing::warn!(%error, "can't accept a connection");
181                tokio::time::sleep(accept_retry).await;
182                continue;
183            }
184        };
185        let _ = tcp.set_nodelay(true);
186        let Some(tls) = &tls else {
187            if accepted.send((Conn::Plain(tcp), peer)).await.is_err() {
188                return;
189            }
190            continue;
191        };
192        let config = match protocol {
193            Protocol::Grpc => tls.grpc_server(),
194            Protocol::Http => tls.http_server(),
195            Protocol::Ui => tls.ui_server(),
196        };
197        let accepted = accepted.clone();
198        let handshake_timeout = tls.handshake_timeout();
199        tokio::spawn(async move {
200            let _permit = permit;
201            let handshake = TlsAcceptor::from(config).accept(tcp);
202            match tokio::time::timeout(handshake_timeout, handshake).await {
203                Ok(Ok(stream)) => {
204                    let _ = accepted.send((Conn::Tls(Box::new(stream)), peer)).await;
205                }
206                Ok(Err(error)) if error.kind() == io::ErrorKind::InvalidData => {
207                    tracing::warn!(%peer, %error, "TLS handshake refused");
208                }
209                Ok(Err(error)) => tracing::debug!(%peer, %error, "TLS handshake ended"),
210                Err(_) => tracing::debug!(%peer, "TLS handshake timed out"),
211            }
212        });
213    }
214}
215
216impl Incoming {
217    /// The address the listener is bound to.
218    #[must_use]
219    pub const fn local_addr(&self) -> SocketAddr {
220        self.local
221    }
222}
223
224impl Stream for Incoming {
225    type Item = io::Result<Conn>;
226
227    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
228        self.get_mut()
229            .accepted
230            .poll_recv(cx)
231            .map(|accepted| accepted.map(|(conn, _)| Ok(conn)))
232    }
233}
234
235impl Listener for Incoming {
236    type Io = Conn;
237    type Addr = SocketAddr;
238
239    async fn accept(&mut self) -> (Conn, SocketAddr) {
240        match self.accepted.recv().await {
241            Some(accepted) => accepted,
242            // The accept loop never ends while this exists.
243            None => std::future::pending().await,
244        }
245    }
246
247    fn local_addr(&self) -> io::Result<SocketAddr> {
248        Ok(self.local)
249    }
250}