use hyper::server::conn::*;
use hyper_util::rt::TokioTimer;
use std::mem;
use std::process::ExitCode;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpListener;
use tokio::sync::Semaphore;
use tokio::task::{JoinSet, coop};
use tokio::time::timeout;
#[cfg(any(feature = "native-tls", feature = "rustls-23"))]
use hyper_util::rt::TokioExecutor;
use super::cancel::Cancellation;
use super::io::IoWithPermit;
use super::tls::Acceptor;
use crate::app::ServiceAdapter;
use crate::error::ServerError;
#[cfg(any(feature = "native-tls", feature = "rustls-23"))]
use super::tls::{Alpn, NegotiateAlpn};
macro_rules! serve_unless_cancelled {
($cancellation:ident, $connection:ident) => {
tokio::select! {
result = &mut $connection => result?,
_ = $cancellation.wait() => {
let mut $connection = Pin::new(&mut $connection);
$connection.as_mut().graceful_shutdown();
$connection.await?;
}
}
};
}
pub(super) async fn accept<App, TlsAcceptor>(
acceptor: TlsAcceptor,
listener: TcpListener,
service: ServiceAdapter<App>,
) -> ExitCode
where
App: Send + Sync + 'static,
ServerError: From<TlsAcceptor::Error>,
TlsAcceptor: Acceptor,
TlsAcceptor::Stream: Send + Unpin + 'static,
{
#[cfg(not(any(feature = "native-tls", feature = "rustls-23")))]
drop(acceptor);
let semaphore = {
let max_connections = service.config().max_connections();
if max_connections <= 1 {
log!(error(accept = 0), "max_connections must be > 10");
return ExitCode::FAILURE;
}
Arc::new(Semaphore::new(max_connections - 1))
};
let mut connections = JoinSet::new();
let cancellation = wait_for_ctrl_c();
let exit_code = loop {
let (io, _) = tokio::select! {
result = listener.accept() => match result {
Ok(stream) => stream,
Err(error) => {
log!(error(accept = 0), "{}", error);
break cfg_select! {
unix => match error.raw_os_error() {
Some(code @ (12 | 23)) => ExitCode::from(code as u8),
Some(24) => ExitCode::from(24),
_ => ExitCode::FAILURE,
},
_ => ExitCode::FAILURE,
};
}
},
_ = cancellation.wait() => {
break ExitCode::SUCCESS;
}
};
let Ok(permit) = semaphore.clone().try_acquire_owned() else {
continue;
};
let service = service.clone();
let cancellation = cancellation.clone();
#[cfg(any(feature = "native-tls", feature = "rustls-23"))]
connections.spawn({
let handshake = acceptor.accept(io);
async move {
let io = timeout(service.config().tls_handshake_timeout(), handshake).await??;
if *io.preferred_alpn() == Alpn::HTTP_2 {
let io = IoWithPermit::new(io, permit);
let serve = serve_http2_connection(io, service, cancellation);
serve.await
} else {
let io = IoWithPermit::new(io, permit);
let serve = serve_http1_connection(io, service, cancellation);
serve.await
}
}
});
#[cfg(not(any(feature = "native-tls", feature = "rustls-23")))]
connections.spawn(async move {
let io = IoWithPermit::new(io, permit);
let serve = serve_http1_connection(io, service, cancellation);
serve.await
});
if connections.len() >= 999 {
let batch = mem::take(&mut connections);
tokio::spawn(drain_connections(false, batch));
}
};
match timeout(
service.config().shutdown_timeout(),
drain_connections(true, connections),
)
.await
{
Ok(_) => exit_code,
Err(_) => ExitCode::FAILURE,
}
}
async fn drain_connections(immediate: bool, mut connections: JoinSet<Result<(), ServerError>>) {
log!(
info(gc = 0),
"joining {} inflight connections...",
connections.len()
);
while let Some(result) = connections.join_next().await {
#[cfg(not(debug_assertions))]
drop(result);
#[cfg(debug_assertions)]
match result {
Ok(Ok(_)) => {}
Err(error) => {
log!(error(gc = 1), "(connection) -> {}", &error);
}
Ok(Err(error)) => {
log!(error(gc = 1), "(service) -> {}", &error);
}
}
if !immediate {
coop::consume_budget().await;
}
}
}
async fn serve_http1_connection<App, Io>(
io: IoWithPermit<Io>,
service: ServiceAdapter<App>,
cancellation: Cancellation,
) -> Result<(), ServerError>
where
App: Send + Sync + 'static,
Io: AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
let mut connection = http1::Builder::new()
.allow_multiple_spaces_in_request_line_delimiters(false)
.auto_date_header(true)
.half_close(false)
.ignore_invalid_headers(false)
.keep_alive(service.config().keep_alive())
.max_buf_size(service.config().max_buf_size())
.pipeline_flush(false)
.preserve_header_case(false)
.header_read_timeout(Some(service.config().http1_header_read_timeout()))
.timer(TokioTimer::new())
.title_case_headers(false)
.serve_connection(io, service)
.with_upgrades();
serve_unless_cancelled!(cancellation, connection);
Ok(())
}
#[cfg(any(feature = "native-tls", feature = "rustls-23"))]
async fn serve_http2_connection<App, Io>(
io: IoWithPermit<Io>,
service: ServiceAdapter<App>,
cancellation: Cancellation,
) -> Result<(), ServerError>
where
App: Send + Sync + 'static,
Io: AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
let mut connection = http2::Builder::new(TokioExecutor::new())
.adaptive_window(false)
.auto_date_header(true)
.max_header_list_size(16384) .initial_connection_window_size(Some(1048576)) .initial_stream_window_size(Some(65536)) .max_frame_size(Some(16384)) .max_concurrent_streams(service.config().http2_max_concurrent_streams())
.max_send_buf_size(service.config().http2_max_send_buf_size())
.timer(TokioTimer::new())
.serve_connection(io, service);
serve_unless_cancelled!(cancellation, connection);
Ok(())
}
fn wait_for_ctrl_c() -> Cancellation {
let (cancellation, remote) = Cancellation::new();
tokio::spawn(async move {
if tokio::signal::ctrl_c().await.is_err() {
eprintln!("unable to register the 'ctrl-c' signal.");
}
remote.cancel();
});
cancellation
}