use std::{io, net::SocketAddr, sync::Arc};
use quinn::{Connection, Endpoint, ServerConfig};
use rustls::{server::ServerConfig as TlsServerConfig, version::TLS13, Certificate, PrivateKey};
use crate::{error::ProtoError, udp::UdpSocket};
use super::{
quic_config,
quic_stream::{self, QuicStream},
};
pub struct QuicServer {
endpoint: Endpoint,
}
impl QuicServer {
pub async fn new(
name_server: SocketAddr,
cert: Vec<Certificate>,
key: PrivateKey,
) -> 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<Certificate>,
key: PrivateKey,
) -> Result<Self, ProtoError> {
let mut config = TlsServerConfig::builder()
.with_safe_default_cipher_suites()
.with_safe_default_kx_groups()
.with_protocol_versions(&[&TLS13])
.expect("TLS1.3 not supported")
.with_no_client_auth()
.with_single_cert(cert, key)?;
config.alpn_protocols = vec![quic_stream::DOQ_ALPN.to_vec()];
let mut server_config = ServerConfig::with_crypto(Arc::new(config));
server_config.transport = Arc::new(quic_config::transport());
let socket = socket.into_std()?;
let endpoint_config = quic_config::endpoint();
let endpoint = Endpoint::new(
endpoint_config,
Some(server_config),
socket,
Arc::new(quinn::TokioRuntime),
)?;
Ok(Self { endpoint })
}
pub async fn next(&mut self) -> Result<Option<(QuicStreams, 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((QuicStreams { connection }, remote_addr)))
}
pub fn local_addr(&self) -> Result<SocketAddr, io::Error> {
self.endpoint.local_addr()
}
}
pub struct QuicStreams {
connection: Connection,
}
impl QuicStreams {
pub async fn next(&mut self) -> Option<Result<QuicStream, ProtoError>> {
match self.connection.accept_bi().await {
Ok((send_stream, receive_stream)) => {
Some(Ok(QuicStream::new(send_stream, receive_stream)))
}
Err(e) => Some(Err(e.into())),
}
}
}