1use 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
30pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
32
33pub const ACCEPT_RETRY: Duration = Duration::from_millis(100);
35
36pub const MAX_HANDSHAKES: usize = 256;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Protocol {
43 Grpc,
45 Http,
47 Ui,
50}
51
52#[derive(Debug)]
54pub enum Conn {
55 Plain(TcpStream),
57 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#[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
135pub 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 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 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 #[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 None => std::future::pending().await,
244 }
245 }
246
247 fn local_addr(&self) -> io::Result<SocketAddr> {
248 Ok(self.local)
249 }
250}