1use crate::{
2 connection::QuinnConnection,
3 runtime::{SocketTransport, TrilliumRuntime},
4};
5use rustls::{
6 pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject},
7 server::ResolvesServerCert,
8};
9use std::{
10 borrow::Cow,
11 collections::HashMap,
12 io,
13 net::SocketAddr,
14 sync::{Arc, Mutex},
15};
16use trillium_server_common::{Info, QuicConfig as QuicConfigTrait, QuicEndpoint, Server};
17
18pub struct QuicConfig(quinn::ServerConfig);
30
31impl QuicConfig {
32 pub fn from_single_cert(cert_pem: &[u8], key_pem: &[u8]) -> Self {
37 let certs: Vec<_> = CertificateDer::pem_slice_iter(cert_pem)
38 .collect::<Result<_, _>>()
39 .expect("parsing certificate PEM");
40
41 let key = PrivateKeyDer::from_pem_slice(key_pem).expect("parsing private key PEM");
42
43 let mut tls_config =
44 rustls::ServerConfig::builder_with_provider(crate::crypto_provider::crypto_provider())
45 .with_safe_default_protocol_versions()
46 .expect("building TLS config with protocol versions")
47 .with_no_client_auth()
48 .with_single_cert(certs, key)
49 .expect("building TLS config");
50
51 tls_config.alpn_protocols = vec![b"h3".to_vec()];
52
53 let quic_tls = quinn::crypto::rustls::QuicServerConfig::try_from(Arc::new(tls_config))
54 .expect("building QUIC TLS config");
55
56 Self(quinn::ServerConfig::with_crypto(Arc::new(quic_tls)))
57 }
58
59 pub fn from_rustls_server_config(tls_config: rustls::ServerConfig) -> Self {
64 let mut tls_config = tls_config;
65 if !tls_config.alpn_protocols.contains(&b"h3".to_vec()) {
66 tls_config.alpn_protocols.push(b"h3".to_vec());
67 }
68 let quic_tls = quinn::crypto::rustls::QuicServerConfig::try_from(Arc::new(tls_config))
69 .expect("building QUIC TLS config");
70 Self(quinn::ServerConfig::with_crypto(Arc::new(quic_tls)))
71 }
72
73 pub fn from_quinn_server_config(config: quinn::ServerConfig) -> Self {
79 Self(config)
80 }
81
82 #[must_use]
88 pub fn with_transport_config(mut self, transport: Arc<quinn::TransportConfig>) -> Self {
89 self.0.transport_config(transport);
90 self
91 }
92
93 pub fn from_cert_resolver(resolver: Arc<dyn ResolvesServerCert>) -> Self {
105 let tls_config =
106 rustls::ServerConfig::builder_with_provider(crate::crypto_provider::crypto_provider())
107 .with_safe_default_protocol_versions()
108 .expect("building TLS config with protocol versions")
109 .with_no_client_auth()
110 .with_cert_resolver(resolver);
111 Self::from_rustls_server_config(tls_config)
112 }
113}
114
115impl<S> QuicConfigTrait<S> for QuicConfig
116where
117 S: Server,
118 S::Runtime: Unpin,
119 S::UdpTransport: SocketTransport,
120{
121 type Endpoint = QuinnEndpoint;
122
123 fn bind(
124 self,
125 addr: SocketAddr,
126 runtime: S::Runtime,
127 info: &mut Info,
128 ) -> Option<io::Result<Self::Endpoint>> {
129 let socket = match std::net::UdpSocket::bind(addr) {
130 Ok(s) => s,
131 Err(e) => return Some(Err(e)),
132 };
133 Some(<Self as QuicConfigTrait<S>>::bind_with_socket(
134 self, socket, runtime, info,
135 ))
136 }
137
138 fn bind_with_socket(
139 self,
140 socket: std::net::UdpSocket,
141 runtime: S::Runtime,
142 _info: &mut Info,
143 ) -> io::Result<Self::Endpoint> {
144 let quinn_runtime = TrilliumRuntime::<S::Runtime, S::UdpTransport>::new(runtime);
145 quinn::Endpoint::new(
146 quinn::EndpointConfig::default(),
147 Some(self.0),
148 socket,
149 quinn_runtime,
150 )
151 .map(QuinnEndpoint::new)
152 }
153}
154
155pub struct QuinnEndpoint {
157 endpoint: quinn::Endpoint,
158 base_tls: Option<Arc<rustls::ClientConfig>>,
163 alpn_configs: Mutex<HashMap<Vec<Vec<u8>>, quinn::ClientConfig>>,
167}
168
169impl QuinnEndpoint {
170 pub(crate) fn new(endpoint: quinn::Endpoint) -> Self {
173 Self {
174 endpoint,
175 base_tls: None,
176 alpn_configs: Mutex::new(HashMap::new()),
177 }
178 }
179
180 pub(crate) fn new_client(
182 endpoint: quinn::Endpoint,
183 base_tls: Option<Arc<rustls::ClientConfig>>,
184 ) -> Self {
185 Self {
186 endpoint,
187 base_tls,
188 alpn_configs: Mutex::new(HashMap::new()),
189 }
190 }
191
192 fn client_config_for_alpn(
195 &self,
196 alpn: &[Cow<'static, [u8]>],
197 ) -> io::Result<Option<quinn::ClientConfig>> {
198 let Some(base) = &self.base_tls else {
199 return Ok(None);
200 };
201 let key: Vec<Vec<u8>> = alpn.iter().map(|a| a.to_vec()).collect();
202
203 let mut cache = self.alpn_configs.lock().unwrap();
204 if let Some(config) = cache.get(&key) {
205 return Ok(Some(config.clone()));
206 }
207
208 let mut tls = (**base).clone();
209 tls.alpn_protocols = key.clone();
210 let quic_tls = quinn::crypto::rustls::QuicClientConfig::try_from(Arc::new(tls))
211 .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
212 let config = quinn::ClientConfig::new(Arc::new(quic_tls));
213 cache.insert(key, config.clone());
214 Ok(Some(config))
215 }
216}
217
218impl QuicEndpoint for QuinnEndpoint {
219 type Connection = QuinnConnection;
220
221 async fn accept(&self) -> Option<Self::Connection> {
222 loop {
223 let incoming = self.endpoint.accept().await?;
224 match incoming.await {
225 Ok(connection) => return Some(QuinnConnection::new(connection)),
226 Err(e) => log::error!("QUIC accept failed: {e}"),
227 }
228 }
229 }
230
231 async fn connect(&self, addr: SocketAddr, server_name: &str) -> io::Result<Self::Connection> {
232 let connection = self
233 .endpoint
234 .connect(addr, server_name)
235 .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?
236 .await
237 .map_err(|e| io::Error::new(io::ErrorKind::ConnectionRefused, e))?;
238 Ok(QuinnConnection::new(connection))
239 }
240
241 async fn connect_with_alpn(
242 &self,
243 addr: SocketAddr,
244 server_name: &str,
245 alpn: &[Cow<'static, [u8]>],
246 ) -> io::Result<Self::Connection> {
247 let Some(config) = (!alpn.is_empty())
250 .then(|| self.client_config_for_alpn(alpn))
251 .transpose()?
252 .flatten()
253 else {
254 return self.connect(addr, server_name).await;
255 };
256
257 let connection = self
258 .endpoint
259 .connect_with(config, addr, server_name)
260 .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?
261 .await
262 .map_err(|e| io::Error::new(io::ErrorKind::ConnectionRefused, e))?;
263 Ok(QuinnConnection::new(connection))
264 }
265
266 fn local_addr(&self) -> io::Result<SocketAddr> {
267 self.endpoint.local_addr()
268 }
269}