use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::time::Duration;
use futures_lite::future;
use futures_rustls::TlsAcceptor;
use futures_rustls::rustls::ServerConfig;
use hyper::Request;
use hyper::body::Incoming;
use hyper::server::conn::{http1, http2};
use hyper::service::service_fn;
use ostrya::{ArchiveView, Checksum, Repo};
use ostrya_fetch::{FuturesIo, RtExecutor, RtTimer};
use ostrya_rt as rt;
use crate::auth::{FileAuth, Peer};
use crate::endpoint::{EndpointOptions, ReceiveEndpoint};
use crate::error::{Error, Result};
use crate::options::ServeOptions;
use crate::router;
use crate::shutdown::{Shutdown, Trigger};
use crate::stall::Stall;
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_CONCURRENT_STREAMS: u32 = 32;
const MAX_HEADER_LIST_SIZE: u32 = 32 * 1024;
const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
pub struct Server {
listeners: Vec<rt::TcpListener>,
addrs: Vec<SocketAddr>,
view: Arc<ArchiveView>,
repo: Repo,
receive: Option<Arc<ReceiveEndpoint<FileAuth>>>,
tls: Option<Arc<ServerConfig>>,
body_timeout: Duration,
}
fn receive(repo: &Repo, opts: &ServeOptions) -> Result<Option<Arc<ReceiveEndpoint<FileAuth>>>> {
let Some(policy) = &opts.receive else {
return Ok(None);
};
let auth = FileAuth::new(opts, policy.clone())?;
let options = EndpointOptions {
parallel_uploads: opts.parallel_uploads,
session_idle_timeout: opts.session_idle_timeout,
max_sessions: opts.max_sessions,
on_report: opts.on_report.clone(),
};
let endpoint = ReceiveEndpoint::new(repo.clone(), auth, options)?;
Ok(Some(Arc::new(endpoint)))
}
pub async fn bind(repo: Repo, opts: ServeOptions) -> Result<Server> {
if opts.listen.is_empty() {
return Err(Error::Options("no listen address".into()));
}
if opts.body_timeout.is_zero() {
return Err(Error::Options("a body timeout of zero".into()));
}
let receive = receive(&repo, &opts)?;
let tls = match &opts.tls {
Some(tls) => Some(
ostrya_fetch::server_config(
&tls.cert_chain_pem,
&tls.key_pem,
tls.key_passphrase.as_deref(),
tls.client_ca_pem.as_deref(),
)
.await
.map_err(|e| match e {
ostrya_fetch::Error::Fetch(message) => Error::Tls(message),
other => Error::Tls(other.to_string()),
})?,
),
None => None,
};
let mut listeners = Vec::with_capacity(opts.listen.len());
let mut addrs = Vec::with_capacity(opts.listen.len());
for addr in opts.listen {
let bound = |source| Error::Bind { addr, source };
let listener = rt::TcpListener::bind(addr).await.map_err(bound)?;
addrs.push(listener.local_addr().map_err(bound)?);
listeners.push(listener);
}
Ok(Server {
listeners,
addrs,
view: Arc::new(ArchiveView::new(repo.clone())),
repo,
receive,
tls,
body_timeout: opts.body_timeout,
})
}
pub async fn serve(repo: Repo, opts: ServeOptions) -> Result<()> {
bind(repo, opts).await?.run().await
}
impl Server {
pub fn local_addrs(&self) -> &[SocketAddr] {
&self.addrs
}
pub async fn run(self) -> Result<()> {
let shutdown = Arc::new(Shutdown::default());
let _trigger = Trigger(shutdown.clone());
if let Some(endpoint) = &self.receive {
let endpoint = endpoint.clone();
let stop = shutdown.wait();
drop(rt::spawn(async move {
future::or(endpoint.sweep(), stop).await;
endpoint.shutdown();
}));
}
let serving = Arc::new(Serving {
view: self.view,
repo: self.repo,
listings: Arc::new(AtomicUsize::new(0)),
receive: self.receive,
tls: self.tls,
body_timeout: self.body_timeout,
});
for listener in self.listeners {
let accept = accept_loop(listener, serving.clone(), shutdown.clone());
drop(rt::spawn(future::or(accept, shutdown.wait())));
}
std::future::pending().await
}
}
struct Serving {
view: Arc<ArchiveView>,
repo: Repo,
listings: Arc<AtomicUsize>,
receive: Option<Arc<ReceiveEndpoint<FileAuth>>>,
tls: Option<Arc<ServerConfig>>,
body_timeout: Duration,
}
async fn accept_loop(listener: rt::TcpListener, serving: Arc<Serving>, shutdown: Arc<Shutdown>) {
loop {
match listener.accept().await {
Ok((stream, _peer)) => {
let connection = connection(stream, serving.clone());
let stop = shutdown.wait();
drop(rt::spawn(future::or(connection, stop)));
}
Err(_) => rt::Timer::after(ACCEPT_BACKOFF).await,
}
}
}
async fn connection(stream: rt::TcpStream, serving: Arc<Serving>) {
let stall = Stall::new(serving.body_timeout);
future::or(
serve_connection(stream, serving, stall.clone()),
async move { stall.expired().await },
)
.await
}
async fn serve_connection(stream: rt::TcpStream, serving: Arc<Serving>, stall: Arc<Stall>) {
let shared = serving.clone();
let service = move |peer: Peer| {
service_fn(move |mut req: Request<Incoming>| {
let serving = shared.clone();
let stall = stall.clone();
if serving.receive.is_some() {
req.extensions_mut().insert(peer);
}
async move {
let receive = serving.receive.as_deref();
let response = router::handle(
&serving.view,
&serving.repo,
&serving.listings,
receive,
&stall,
req,
)
.await;
Ok::<_, Infallible>(response)
}
})
};
let Some(config) = serving.tls.clone() else {
let peer = Peer {
tls: false,
cert: None,
};
let served = http1::Builder::new()
.timer(RtTimer)
.header_read_timeout(HEADER_READ_TIMEOUT)
.serve_connection(FuturesIo::new(stream), service(peer));
let _ = served.await;
return;
};
let handshake = future::or(
async { Some(TlsAcceptor::from(config).accept(stream).await) },
async {
rt::Timer::after(HANDSHAKE_TIMEOUT).await;
None
},
);
let Some(Ok(stream)) = handshake.await else {
return;
};
let connection = stream.get_ref().1;
let h2 = connection.alpn_protocol() == Some(b"h2".as_slice());
let peer = Peer {
tls: true,
cert: connection
.peer_certificates()
.and_then(|chain| chain.first())
.map(|der| Checksum::sha256(der.as_ref())),
};
let service = service(peer);
let io = FuturesIo::new(stream);
if h2 {
let mut builder = http2::Builder::new(RtExecutor);
builder
.timer(RtTimer)
.max_concurrent_streams(MAX_CONCURRENT_STREAMS)
.max_header_list_size(MAX_HEADER_LIST_SIZE)
.keep_alive_interval(Some(serving.body_timeout / 2))
.keep_alive_timeout(serving.body_timeout);
if let Some((stream, connection)) = serving.receive.as_ref().map(|e| e.h2_windows()) {
builder
.initial_stream_window_size(stream)
.initial_connection_window_size(connection);
}
let served = builder.serve_connection(io, service);
let _ = served.await;
} else {
let served = http1::Builder::new()
.timer(RtTimer)
.header_read_timeout(HEADER_READ_TIMEOUT)
.serve_connection(io, service);
let _ = served.await;
}
}