use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::net::{TcpListener, TcpStream, ToSocketAddrs};
use tokio_rustls::{TlsAcceptor, TlsConnector};
use tracing::{debug, info, instrument};
use crate::config::{ALPN_PROTOCOL, ClientConfig, ServerConfig};
use crate::connection::Connection;
use crate::error::{Error, Result};
use crate::limits::Limits;
pub struct Connecting {
inner: Pin<Box<dyn Future<Output = Result<Connection>> + Send + 'static>>,
}
impl Future for Connecting {
type Output = Result<Connection>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.inner.as_mut().poll(cx)
}
}
pub struct Endpoint {
inner: EndpointInner,
limits: Limits,
handshake_timeout: Duration,
keepalive_interval: Option<Duration>,
idle_timeout: Option<Duration>,
}
enum EndpointInner {
Client {
config: ClientConfig,
},
Server {
listener: TcpListener,
config: ServerConfig,
},
}
impl Endpoint {
const DEFAULT_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
pub fn client(config: ClientConfig) -> Self {
Self {
inner: EndpointInner::Client { config },
limits: Limits::default(),
handshake_timeout: Self::DEFAULT_HANDSHAKE_TIMEOUT,
keepalive_interval: None,
idle_timeout: None,
}
}
pub async fn server(addr: impl ToSocketAddrs, config: ServerConfig) -> Result<Self> {
let listener = TcpListener::bind(addr).await?;
Ok(Self {
inner: EndpointInner::Server { listener, config },
limits: Limits::default(),
handshake_timeout: Self::DEFAULT_HANDSHAKE_TIMEOUT,
keepalive_interval: None,
idle_timeout: None,
})
}
pub fn with_limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
pub fn with_handshake_timeout(mut self, timeout: Duration) -> Self {
self.handshake_timeout = timeout;
self
}
pub fn with_keepalive_interval(mut self, interval: Duration) -> Self {
self.keepalive_interval = Some(interval);
self
}
pub fn with_idle_timeout(mut self, timeout: Duration) -> Self {
self.idle_timeout = Some(timeout);
self
}
pub fn local_addr(&self) -> Result<SocketAddr> {
match &self.inner {
EndpointInner::Server { listener, .. } => Ok(listener.local_addr()?),
EndpointInner::Client { .. } => Err(Error::EndpointRole(
"local_addr is only available on server endpoints",
)),
}
}
#[instrument(skip(self), level = "info")]
pub fn connect(&self, addr: SocketAddr, server_name: &str) -> Result<Connecting> {
let EndpointInner::Client { config } = &self.inner else {
return Err(Error::EndpointRole(
"connect is only available on client endpoints",
));
};
let cfg = config.clone();
let limits = self.limits.clone();
limits.validate()?;
self.validate_connection_policy()?;
let handshake_timeout = self.handshake_timeout;
let keepalive_interval = self.keepalive_interval;
let idle_timeout = self.idle_timeout;
let server_name = ClientConfig::server_name(server_name);
let fut = async move {
let server_name = server_name?;
let tls = tokio::time::timeout(handshake_timeout, async {
let tcp = TcpStream::connect(addr).await?;
tcp.set_nodelay(true)?;
let connector = TlsConnector::from(cfg.inner.clone());
connector
.connect(server_name, tcp)
.await
.map_err(|e| Error::TlsHandshake(e.to_string()))
})
.await
.map_err(|_| Error::Timeout("connection establishment"))??;
if tls.get_ref().1.alpn_protocol() != Some(ALPN_PROTOCOL) {
return Err(Error::TlsHandshake(
"peer did not negotiate the required muxtls/1 ALPN".to_owned(),
));
}
info!(remote = %addr, "client connection established");
let peer_certificates = tls.get_ref().1.peer_certificates().map(<[_]>::to_vec);
Connection::new(
tls,
limits,
true,
peer_certificates,
keepalive_interval,
idle_timeout,
)
};
Ok(Connecting {
inner: Box::pin(fut),
})
}
#[instrument(skip(self), level = "info")]
pub async fn accept(&self) -> Result<Connection> {
let EndpointInner::Server { listener, config } = &self.inner else {
return Err(Error::EndpointRole(
"accept is only available on server endpoints",
));
};
self.limits.validate()?;
self.validate_connection_policy()?;
let (tcp, peer) = listener.accept().await?;
tcp.set_nodelay(true)?;
let acceptor = TlsAcceptor::from(config.inner.clone());
let tls = tokio::time::timeout(self.handshake_timeout, acceptor.accept(tcp))
.await
.map_err(|_| Error::Timeout("TLS handshake"))?
.map_err(|e| Error::TlsHandshake(e.to_string()))?;
if tls.get_ref().1.alpn_protocol() != Some(ALPN_PROTOCOL) {
return Err(Error::TlsHandshake(
"peer did not negotiate the required muxtls/1 ALPN".to_owned(),
));
}
debug!(remote = %peer, "server accepted connection");
let peer_certificates = tls.get_ref().1.peer_certificates().map(<[_]>::to_vec);
Connection::new(
tls,
self.limits.clone(),
false,
peer_certificates,
self.keepalive_interval,
self.idle_timeout,
)
}
fn validate_connection_policy(&self) -> Result<()> {
for (name, value) in [
("handshake timeout", Some(self.handshake_timeout)),
("keepalive interval", self.keepalive_interval),
("idle timeout", self.idle_timeout),
] {
if let Some(value) = value
&& (value.is_zero() || tokio::time::Instant::now().checked_add(value).is_none())
{
return Err(Error::Config(format!(
"{name} must be positive and representable by the monotonic clock"
)));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_timeouts_are_rejected_before_connecting() {
let (_, cert) = crate::ServerConfig::self_signed_for_localhost().unwrap();
let config = ClientConfig::with_custom_roots(vec![cert]).unwrap();
for endpoint in [
Endpoint::client(config.clone()).with_handshake_timeout(Duration::ZERO),
Endpoint::client(config.clone()).with_keepalive_interval(Duration::MAX),
Endpoint::client(config).with_idle_timeout(Duration::ZERO),
] {
assert!(endpoint.validate_connection_policy().is_err());
}
}
}