1use std::io;
25use std::net::SocketAddr;
26use std::pin::{pin, Pin};
27use std::sync::Arc;
28use std::task::{ready, Context, Poll};
29
30use bytes::{Buf, Bytes};
31use futures::{Stream, StreamExt};
32use h3::server::RequestStream;
33use quinn::crypto::rustls::QuicServerConfig;
34
35use crate::tls::{TlsConfig, Error};
36use crate::listener::{AsyncCancel, Certificates};
37use crate::shutdown::Shutdown;
38
39pub(crate) type Connection = h3::server::Connection<h3_quinn::Connection, Bytes>;
40
41pub struct QuicRx(pub(crate) RequestStream<h3_quinn::RecvStream, Bytes>);
43
44pub(crate) struct QuicTx {
49 stream: RequestStream<h3_quinn::SendStream<Bytes>, Bytes>,
50 grace: Shutdown,
51 done: bool,
52}
53
54pub(crate) async fn bind(addr: SocketAddr, tls: &TlsConfig) -> Result<quinn::Endpoint, Error> {
56 let mut tls_config = tls.server_config().await?;
57 tls_config.alpn_protocols = vec![b"h3".to_vec()];
58
59 let quic_config = QuicServerConfig::try_from(tls_config)
60 .map_err(|e| Error::Bind(Box::new(e)))?;
61
62 let server_config = quinn::ServerConfig::with_crypto(Arc::new(quic_config));
63 Ok(quinn::Endpoint::server(server_config, addr)?)
64}
65
66pub(crate) fn certificates(conn: &quinn::Connection) -> Option<Certificates<'static>> {
68 #[cfg(feature = "mtls")] {
69 let certs = conn.peer_identity()?;
70 let certs = certs.downcast::<Vec<rustls::pki_types::CertificateDer<'static>>>().ok()?;
71 Some(Certificates::from(*certs))
72 }
73
74 #[cfg(not(feature = "mtls"))] {
75 let _ = conn;
76 None
77 }
78}
79
80pub(crate) fn server_name(conn: &quinn::Connection) -> Option<String> {
82 let data = conn.handshake_data()?;
83 data.downcast::<quinn::crypto::rustls::HandshakeData>().ok()?.server_name
84}
85
86pub(crate) async fn send_response<S>(tx: &mut QuicTx, response: http::Response<S>) -> io::Result<()>
88 where S: Stream<Item = io::Result<Bytes>>
89{
90 let (mut parts, body) = response.into_parts();
91 strip_connection_headers(&mut parts.headers);
92 let stream = &mut tx.stream;
93 stream.send_response(http::Response::from_parts(parts, ())).await.map_err(io::Error::other)?;
94
95 let mut body = pin!(body);
96 while let Some(chunk) = body.next().await {
97 stream.send_data(chunk?).await.map_err(io::Error::other)?;
98 }
99
100 stream.finish().await.map_err(io::Error::other)?;
101 tx.done = true;
102 Ok(())
103}
104
105fn strip_connection_headers(headers: &mut http::HeaderMap) {
108 use http::header::{HeaderName, CONNECTION, TE, TRANSFER_ENCODING, UPGRADE};
109
110 let keep_alive = HeaderName::from_static("keep-alive");
111 let proxy_connection = HeaderName::from_static("proxy-connection");
112 for name in [keep_alive, proxy_connection, TRANSFER_ENCODING, UPGRADE, TE] {
113 headers.remove(name);
114 }
115
116 let names: Vec<_> = headers.get_all(CONNECTION).iter()
118 .filter_map(|names| names.to_str().ok())
119 .flat_map(|names| names.split(','))
120 .map(|name| name.trim().to_string())
121 .collect();
122
123 headers.remove(CONNECTION);
124 for name in names {
125 headers.remove(name);
126 }
127}
128
129impl QuicTx {
130 pub(crate) fn new(
133 stream: RequestStream<h3_quinn::SendStream<Bytes>, Bytes>,
134 grace: Shutdown,
135 ) -> Self {
136 QuicTx { stream, grace, done: false }
137 }
138}
139
140impl Drop for QuicTx {
141 fn drop(&mut self) {
142 if !self.done {
143 let code = match self.grace.notified() {
144 true => h3::error::Code::H3_REQUEST_CANCELLED,
145 false => h3::error::Code::H3_INTERNAL_ERROR,
146 };
147
148 self.stream.stop_stream(code);
149 }
150 }
151}
152
153pub(crate) fn log_error(error: &io::Error) {
158 use h3::error::{Code, ConnectionError, LocalError, StreamError};
159 use h3::quic::ConnectionErrorIncoming;
160
161 fn quinn_routine(error: &quinn::ConnectionError) -> bool {
162 use quinn::ConnectionError::*;
163
164 match error {
165 ApplicationClosed(close) => close.error_code.into_inner() == Code::H3_NO_ERROR.value(),
166 Reset | TimedOut | LocallyClosed => true,
167 _ => false,
168 }
169 }
170
171 fn h3_routine(error: &ConnectionError) -> bool {
173 match error {
174 ConnectionError::Timeout { .. } => true,
175 ConnectionError::Local { error: LocalError::Closing { .. }, .. } => true,
176 ConnectionError::Remote { 0: ConnectionErrorIncoming::Timeout, .. } => true,
177 ConnectionError::Remote { 0: ConnectionErrorIncoming::Undefined(e), .. } => {
178 e.downcast_ref().is_some_and(quinn_routine)
179 }
180 error => error.is_h3_no_error(),
181 }
182 }
183
184 let Some(inner) = error.get_ref() else {
185 return crate::error::log_server_error(error);
186 };
187
188 let routine = if let Some(e) = inner.downcast_ref::<ConnectionError>() {
189 h3_routine(e)
190 } else if let Some(e) = inner.downcast_ref::<StreamError>() {
191 match e {
192 StreamError::RemoteTerminate { .. } | StreamError::RemoteClosing { .. } => true,
193 StreamError::ConnectionError { 0: e, .. } => h3_routine(e),
194 _ => false,
195 }
196 } else if let Some(e) = inner.downcast_ref::<quinn::ConnectionError>() {
197 quinn_routine(e)
198 } else if inner.is::<tokio::time::error::Elapsed>() {
199 false
200 } else {
201 return crate::error::log_server_error(error);
202 };
203
204 match routine {
205 true => debug!(error = %error, "http/3 connection or request closed"),
206 false => warn!(error = %error, "http/3 connection or request failed"),
207 }
208}
209
210impl Stream for QuicRx {
211 type Item = io::Result<Bytes>;
212
213 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
214 match ready!(self.0.poll_recv_data(cx)) {
215 Ok(Some(mut buf)) => Poll::Ready(Some(Ok(buf.copy_to_bytes(buf.remaining())))),
216 Ok(None) => Poll::Ready(None),
217 Err(e) => Poll::Ready(Some(Err(io::Error::other(e)))),
218 }
219 }
220}
221
222impl AsyncCancel for QuicRx {
223 fn poll_cancel(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
224 Poll::Ready(Ok(()))
227 }
228}