hickory_proto/h3/
h3_server.rsuse std::{io, net::SocketAddr, sync::Arc};
use bytes::Bytes;
use h3::server::{Connection, RequestStream};
use h3_quinn::{BidiStream, Endpoint};
use http::Request;
use quinn::crypto::rustls::QuicServerConfig;
use quinn::{EndpointConfig, ServerConfig};
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::ServerConfig as TlsServerConfig;
use rustls::version::TLS13;
use crate::{error::ProtoError, udp::UdpSocket};
use super::ALPN_H3;
pub struct H3Server {
endpoint: Endpoint,
}
impl H3Server {
pub async fn new(
name_server: SocketAddr,
cert: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
) -> Result<Self, ProtoError> {
let socket = <tokio::net::UdpSocket as UdpSocket>::bind(name_server).await?;
Self::with_socket(socket, cert, key)
}
pub fn with_socket(
socket: tokio::net::UdpSocket,
cert: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
) -> Result<Self, ProtoError> {
let mut config = TlsServerConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_protocol_versions(&[&TLS13])
.expect("TLS1.3 not supported")
.with_no_client_auth()
.with_single_cert(cert, key)?;
config.alpn_protocols = vec![ALPN_H3.to_vec()];
let mut server_config =
ServerConfig::with_crypto(Arc::new(QuicServerConfig::try_from(config).unwrap()));
server_config.transport = Arc::new(super::transport());
let socket = socket.into_std()?;
let endpoint = Endpoint::new(
EndpointConfig::default(),
Some(server_config),
socket,
Arc::new(quinn::TokioRuntime),
)?;
Ok(Self { endpoint })
}
pub async fn accept(&mut self) -> Result<Option<(H3Connection, SocketAddr)>, ProtoError> {
let connecting = match self.endpoint.accept().await {
Some(conn) => conn,
None => return Ok(None),
};
let remote_addr = connecting.remote_address();
let connection = connecting.await?;
Ok(Some((
H3Connection {
connection: Connection::new(h3_quinn::Connection::new(connection))
.await
.map_err(|e| ProtoError::from(format!("h3 connection failed: {e}")))?,
},
remote_addr,
)))
}
pub fn local_addr(&self) -> Result<SocketAddr, io::Error> {
self.endpoint.local_addr()
}
}
pub struct H3Connection {
connection: Connection<h3_quinn::Connection, Bytes>,
}
impl H3Connection {
pub async fn accept(
&mut self,
) -> Option<Result<(Request<()>, RequestStream<BidiStream<Bytes>, Bytes>), ProtoError>> {
match self.connection.accept().await {
Ok(Some((request, stream))) => Some(Ok((request, stream))),
Ok(None) => None,
Err(e) => Some(Err(ProtoError::from(format!("h3 request failed: {e}")))),
}
}
pub async fn shutdown(&mut self) -> Result<(), ProtoError> {
self.connection
.shutdown(0)
.await
.map_err(|e| ProtoError::from(format!("h3 connection shutdown failed: {e}")))
}
}