use crate::guard::{
may_be_served, refuse_hidden_files, refuse_index_pages_outside, refuse_paths_outside,
};
use crate::list::serve_file_list;
use crate::version::{Version, answer_by_version, identity};
use axum::Router;
use axum::extract::Request;
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use http::uri::PathAndQuery;
use http::{HeaderName, HeaderValue, StatusCode, Uri, header};
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::AsyncReadExt;
use tokio::sync::Mutex;
use tower_http::compression::CompressionLayer;
use tower_http::services::ServeDir;
use tower_http::set_header::SetResponseHeaderLayer;
use tower_livereload::LiveReloadLayer;
pub(crate) const INDEX_FILE: &str = "index.html";
#[derive(Clone, Copy)]
pub(crate) enum Caching {
Off,
Checked,
AssetsForAYear,
}
const ASSETS: &str = "/assets/";
const KEEP_FOR_A_YEAR: &str = "public, max-age=31536000, immutable";
const CHECK_BEFORE_USE: &str = "no-cache";
pub(crate) fn app(
static_dir: &Path,
spa: bool,
list: bool,
caching: Caching,
livereload: Option<LiveReloadLayer>,
no_app_page: bool,
) -> Router {
let mut app = Router::new()
.fallback_service(ServeDir::new(static_dir))
.layer(middleware::from_fn(drop_file_service_tags));
let checks_versions = !matches!(caching, Caching::Off);
if checks_versions {
let root = static_dir.to_path_buf();
app = app.layer(middleware::from_fn(move |request, next| {
answer_by_version(root.clone(), request, next)
}));
}
let root = static_dir.to_path_buf();
app = app.layer(middleware::from_fn(move |request, next| {
refuse_index_pages_outside(root.clone(), request, next)
}));
if spa {
let root = static_dir.to_path_buf();
let index = static_dir.join(INDEX_FILE);
let missing = Arc::new(Mutex::new(no_app_page));
app = app.layer(middleware::from_fn(move |request, next| {
serve_app_shell(
root.clone(),
index.clone(),
Arc::clone(&missing),
checks_versions,
request,
next,
)
}));
}
if list {
let root = static_dir.to_path_buf();
app = app.layer(middleware::from_fn(move |request, next| {
serve_file_list(root.clone(), request, next)
}));
}
if let Some(livereload) = livereload {
app = app.layer(livereload);
}
let root = static_dir.to_path_buf();
let mut app = app
.layer(CompressionLayer::new())
.layer(middleware::from_fn(refuse_hidden_files))
.layer(middleware::from_fn(move |request, next| {
refuse_paths_outside(root.clone(), request, next)
}));
app = match caching {
Caching::Off => app
.layer(middleware::from_fn(always_answer_in_full))
.layer(set_header(header::CACHE_CONTROL, "no-store")),
Caching::Checked => app.layer(set_header(header::CACHE_CONTROL, CHECK_BEFORE_USE)),
Caching::AssetsForAYear => app.layer(middleware::from_fn(keep_assets)),
};
app.layer(set_header(header::X_CONTENT_TYPE_OPTIONS, "nosniff"))
.layer(set_header(header::X_FRAME_OPTIONS, "SAMEORIGIN"))
.layer(set_header(
header::REFERRER_POLICY,
"strict-origin-when-cross-origin",
))
.layer(middleware::from_fn(collapse_leading_slashes))
}
async fn collapse_leading_slashes(mut request: Request, next: Next) -> Response {
let path = request.uri().path();
let rest = path.trim_start_matches(['/', '\\']);
if path.len() - rest.len() > 1 {
let collapsed = match request.uri().query() {
Some(query) => format!("/{rest}?{query}"),
None => format!("/{rest}"),
};
let Ok(path_and_query) = PathAndQuery::try_from(collapsed) else {
return StatusCode::BAD_REQUEST.into_response();
};
let mut parts = request.uri().clone().into_parts();
parts.path_and_query = Some(path_and_query);
let Ok(uri) = Uri::from_parts(parts) else {
return StatusCode::BAD_REQUEST.into_response();
};
*request.uri_mut() = uri;
}
next.run(request).await
}
async fn serve_app_shell(
root: PathBuf,
index: PathBuf,
missing: Arc<Mutex<bool>>,
checks_versions: bool,
request: Request,
next: Next,
) -> Response {
let if_none_match = request.headers().get(header::IF_NONE_MATCH).cloned();
let wants_page = request
.headers()
.get(header::ACCEPT)
.and_then(|accept| accept.to_str().ok())
.is_some_and(|accept| accept.contains("text/html"));
let could_be_a_route = !request.uri().path().starts_with(ASSETS);
let response = next.run(request).await;
if response.status() != StatusCode::NOT_FOUND || !wants_page || !could_be_a_route {
let mut missing = missing.lock().await;
if *missing && is_there(&root, &index).await {
*missing = false;
}
return response;
}
let mut missing = missing.lock().await;
let page = if may_be_served(&root, &index) {
read_page(&index).await.map_err(|error| {
if error.kind() == ErrorKind::NotFound {
"is gone"
} else {
"cannot be read"
}
})
} else {
Err("leads to a file that is never served")
};
match page {
Ok((page, version)) => {
*missing = false;
let html = HeaderValue::from_static("text/html; charset=utf-8");
match version.filter(|_| checks_versions) {
Some(version) if if_none_match.is_some_and(|tags| version.is_named_in(&tags)) => {
(StatusCode::NOT_MODIFIED, [(header::ETAG, version.tag())]).into_response()
}
Some(version) => (
[(header::CONTENT_TYPE, html), (header::ETAG, version.tag())],
page,
)
.into_response(),
None => ([(header::CONTENT_TYPE, html)], page).into_response(),
}
}
Err(reason) => {
if !std::mem::replace(&mut *missing, true) {
eprintln!(" {INDEX_FILE} {reason}, so the app will not load");
}
response
}
}
}
async fn always_answer_in_full(mut request: Request, next: Next) -> Response {
let headers = request.headers_mut();
headers.remove(header::IF_MODIFIED_SINCE);
headers.remove(header::IF_NONE_MATCH);
next.run(request).await
}
async fn keep_assets(request: Request, next: Next) -> Response {
let path = request.uri().path();
let asset = path.starts_with(ASSETS) && !path.ends_with('/');
let mut response = next.run(request).await;
let there = response.status().is_success() || response.status() == StatusCode::NOT_MODIFIED;
let keep = asset && there;
response.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static(if keep {
KEEP_FOR_A_YEAR
} else {
CHECK_BEFORE_USE
}),
);
response
}
async fn drop_file_service_tags(request: Request, next: Next) -> Response {
let mut response = next.run(request).await;
response.headers_mut().remove(header::ETAG);
response
}
async fn read_page(index: &Path) -> std::io::Result<(Vec<u8>, Option<Version>)> {
let before = identity(index);
let mut file = tokio::fs::File::open(index).await?;
let metadata = file.metadata().await.ok();
let mut page = Vec::new();
file.read_to_end(&mut page).await?;
let version = metadata
.filter(|_| identity(index) == before)
.and_then(|metadata| Version::of(before, &metadata));
Ok((page, version))
}
async fn is_there(root: &Path, index: &Path) -> bool {
if !may_be_served(root, index) {
return false;
}
let Ok(page) = tokio::fs::File::open(index).await else {
return false;
};
page.metadata().await.is_ok_and(|found| found.is_file())
}
fn set_header(name: HeaderName, value: &'static str) -> SetResponseHeaderLayer<HeaderValue> {
SetResponseHeaderLayer::overriding(name, HeaderValue::from_static(value))
}