use std::path::{Component, Path, PathBuf};
use std::time::UNIX_EPOCH;
use bytes::Bytes;
use http::{Method, StatusCode, header};
use percent_encoding::percent_decode_str;
use crate::context::Context;
use crate::handler::BoxFuture;
use crate::middleware::{Middleware, Next};
use crate::response::Response;
pub struct Static {
source: Source,
prefix: String,
}
enum Source {
Dir(PathBuf),
Embedded(&'static [EmbeddedFile]),
}
#[derive(Debug)]
pub struct EmbeddedFile {
pub path: &'static str,
pub bytes: &'static [u8],
pub etag: &'static str,
}
impl Static {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self {
source: Source::Dir(root.into()),
prefix: "/".into(),
}
}
pub fn embedded(files: &'static [EmbeddedFile]) -> Self {
Self {
source: Source::Embedded(files),
prefix: "/".into(),
}
}
pub fn at(mut self, prefix: &str) -> Self {
self.prefix = format!("/{}", prefix.trim_matches('/'));
self
}
fn relative(&self, path: &str) -> Option<PathBuf> {
let rest = path.strip_prefix(&self.prefix)?;
if !(self.prefix == "/" || rest.is_empty() || rest.starts_with('/')) {
return None;
}
let decoded = percent_decode_str(rest).decode_utf8().ok()?;
let relative = Path::new(decoded.trim_start_matches('/'));
if relative
.components()
.any(|c| !matches!(c, Component::Normal(_)))
{
return None;
}
Some(relative.to_path_buf())
}
#[cfg(test)]
fn resolve(&self, path: &str) -> Option<PathBuf> {
match &self.source {
Source::Dir(root) => self.relative(path).map(|r| root.join(r)),
Source::Embedded(_) => None,
}
}
}
impl Middleware for Static {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
let relative = matches!(*ctx.method(), Method::GET | Method::HEAD)
.then(|| self.relative(ctx.path()))
.flatten();
let Some(relative) = relative else {
return Box::pin(next.run(ctx));
};
match &self.source {
Source::Dir(root) => {
let file = root.join(relative);
Box::pin(async move {
match serve_file(&file, &ctx).await {
Some(res) => res,
None => next.run(ctx).await,
}
})
}
Source::Embedded(files) => {
let wanted = relative.to_string_lossy().replace('\\', "/");
match files.iter().find(|f| f.path == wanted) {
Some(file) => {
let res = respond(&ctx, file.etag, Path::new(file.path), || {
Bytes::from_static(file.bytes)
});
Box::pin(async move { res })
}
None => Box::pin(next.run(ctx)),
}
}
}
}
}
async fn serve_file(path: &Path, ctx: &Context) -> Option<Response> {
let meta = tokio::fs::metadata(path).await.ok()?;
if !meta.is_file() {
return None;
}
let modified = meta
.modified()
.ok()
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map_or(0, |d| d.as_secs());
let etag = format!("\"{:x}-{:x}\"", meta.len(), modified);
if ctx.header(header::IF_NONE_MATCH) == Some(etag.as_str()) {
return Some(not_modified(&etag));
}
let body = tokio::fs::read(path).await.ok()?;
Some(respond(ctx, &etag, path, || Bytes::from(body)))
}
fn not_modified(etag: &str) -> Response {
Response::new(StatusCode::NOT_MODIFIED).with_header(header::ETAG, etag.to_owned())
}
fn respond(ctx: &Context, etag: &str, path: &Path, body: impl FnOnce() -> Bytes) -> Response {
if ctx.header(header::IF_NONE_MATCH) == Some(etag) {
return not_modified(etag);
}
Response::new(StatusCode::OK)
.with_body_bytes(body())
.with_header(header::CONTENT_TYPE, content_type(path))
.with_header(header::ETAG, etag.to_owned())
.with_header(header::CACHE_CONTROL, "public, max-age=0, must-revalidate")
}
fn content_type(path: &Path) -> &'static str {
let ext = path
.extension()
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase);
match ext.as_deref() {
Some("html" | "htm") => "text/html; charset=utf-8",
Some("css") => "text/css; charset=utf-8",
Some("js" | "mjs") => "text/javascript; charset=utf-8",
Some("json" | "map") => "application/json",
Some("txt") => "text/plain; charset=utf-8",
Some("svg") => "image/svg+xml",
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
Some("avif") => "image/avif",
Some("ico") => "image/x-icon",
Some("woff") => "font/woff",
Some("woff2") => "font/woff2",
Some("wasm") => "application/wasm",
Some("pdf") => "application/pdf",
Some("xml") => "application/xml",
_ => "application/octet-stream",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolves_only_safe_paths_under_prefix() {
let root = Static::new("public");
assert_eq!(
root.resolve("/app.css"),
Some(PathBuf::from("public/app.css"))
);
assert_eq!(root.resolve("/../secret"), None);
assert_eq!(root.resolve("/a/%2e%2e/%2e%2e/secret"), None);
assert_eq!(root.resolve("/a/..%2f..%2fsecret"), None);
let assets = Static::new("public").at("/assets/");
assert_eq!(
assets.resolve("/assets/js/app.js"),
Some(PathBuf::from("public/js/app.js"))
);
assert_eq!(assets.resolve("/assetsfoo"), None);
assert_eq!(assets.resolve("/other/app.js"), None);
}
}