use std::{
convert::Infallible,
net::IpAddr,
path::{Component, Path, PathBuf},
str::FromStr,
sync::Arc,
time::Duration,
};
use axum::{
Router,
body::{Body, Bytes},
extract::{Path as UrlPath, State},
http::{HeaderName, HeaderValue, Request, StatusCode, Uri, header},
middleware::{self, Next},
response::{
Response,
sse::{Event, KeepAlive, Sse},
},
routing::get,
};
use futures_util::stream::{Stream, unfold};
use tokio::{
net::TcpListener,
sync::broadcast::{self, Sender, error::RecvError},
};
use crate::{ReloadType, base_normalize};
struct AppState {
dir: PathBuf,
tx: Sender<(ReloadType, Vec<PathBuf>)>,
headers: Vec<(HeaderName, HeaderValue)>,
index: String,
base: String,
}
#[derive(Clone, Debug)]
pub struct Config {
pub dir: PathBuf,
pub ip: IpAddr,
pub port: u16,
pub headers: Vec<String>,
pub index: String,
pub base: String,
}
#[derive(Debug)]
pub struct Server {
pub url: String,
listener: TcpListener,
router: Router,
}
impl Server {
pub async fn bind(
tx: Sender<(ReloadType, Vec<PathBuf>)>,
config: Config,
) -> Result<Self, String> {
let (url, listener, router) = bind(tx, config).await?;
Ok(Self {
url,
listener,
router,
})
}
pub async fn new(config: Config) -> Result<Self, String> {
let (tx, _rx) = broadcast::channel(100);
Self::bind(tx, config).await
}
pub async fn run(self) -> Result<(), String> {
serve(self.listener, self.router).await
}
}
pub async fn bind(
tx: Sender<(ReloadType, Vec<PathBuf>)>,
config: Config,
) -> Result<(String, TcpListener, Router), String> {
let headers =
headers_parse(&config.headers).map_err(|err| format!("Invalid --header: {err}"))?;
index_validate(&config.index).map_err(|err| format!("Invalid --index: {err}"))?;
let base = base_normalize(&config.base).map_err(|err| format!("Invalid --base: {err}"))?;
let listener = TcpListener::bind((config.ip, config.port))
.await
.map_err(|err| format!("Failed to bind address: {err}"))?;
let addr = listener
.local_addr()
.map_err(|err| format!("Failed to get bound address: {err}"))?;
let url = if config.ip.is_unspecified() {
format!("http://127.0.0.1:{}{base}", addr.port())
} else {
format!("http://{}:{}{base}", config.ip, addr.port())
};
let app = app_build(AppState {
dir: config.dir,
tx,
headers,
index: config.index,
base,
});
Ok((url, listener, app))
}
pub async fn serve(listener: TcpListener, router: Router) -> Result<(), String> {
axum::serve(listener, router)
.await
.map_err(|err| format!("{err}"))?;
Ok(())
}
fn app_build(state: AppState) -> Router {
let state = Arc::new(state);
let base = state.base.clone();
let mut router = Router::new()
.route(&format!("{base}/livereload"), get(livereload))
.route(&format!("{base}/"), get(root_serve))
.route(&format!("{base}/{{*path}}"), get(files_serve));
if !base.is_empty() {
router = router.route(&base, get(base_redirect));
}
router
.with_state(state.clone())
.layer(middleware::from_fn_with_state(state, headers_middleware))
}
fn headers_parse(raw: &[String]) -> Result<Vec<(HeaderName, HeaderValue)>, String> {
raw.iter()
.map(|item| {
let (name, value) = item
.split_once(':')
.ok_or_else(|| format!("missing ':' separator in `{item}`"))?;
let name = name.trim();
let value = value.trim();
if name.is_empty() {
return Err(format!("empty header name in `{item}`"));
}
let name = HeaderName::from_str(name)
.map_err(|_| format!("invalid header name in `{item}`"))?;
let value = HeaderValue::from_str(value)
.map_err(|_| format!("invalid header value in `{item}`"))?;
Ok((name, value))
})
.collect()
}
fn index_validate(index: &str) -> Result<(), String> {
if index.is_empty() {
return Err("empty index filename".into());
}
if index == "." || index == ".." {
return Err(format!("invalid index filename `{index}`"));
}
if index.starts_with('.') {
return Err(format!("invalid index filename `{index}`"));
}
if index.contains('/') || index.contains('\\') {
return Err(format!("index must be a bare filename, got `{index}`"));
}
Ok(())
}
async fn headers_middleware(
State(state): State<Arc<AppState>>,
request: Request<Body>,
next: Next,
) -> Response {
let mut response = next.run(request).await;
for (name, value) in &state.headers {
response.headers_mut().insert(name.clone(), value.clone());
}
response
}
async fn livereload(
State(state): State<Arc<AppState>>,
) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
let rx = state.tx.subscribe();
Sse::new(unfold(rx, |mut rx| async move {
let reload_type = match rx.recv().await {
Ok((reload_type, _)) => reload_type,
Err(RecvError::Lagged(_)) => ReloadType::Page,
Err(RecvError::Closed) => return None,
};
let message = reload_type.as_str();
Some((Ok(Event::default().event(message).data(message)), rx))
}))
.keep_alive(
KeepAlive::new()
.interval(Duration::from_secs(15))
.text("keep-alive"),
)
}
async fn root_serve(State(state): State<Arc<AppState>>) -> Response {
file_serve(&state.dir, "", &state.index, &state.base).await
}
async fn files_serve(
State(state): State<Arc<AppState>>,
UrlPath(path): UrlPath<String>,
) -> Response {
file_serve(&state.dir, &path, &state.index, &state.base).await
}
async fn base_redirect(State(state): State<Arc<AppState>>, uri: Uri) -> Response {
let location = match uri.query() {
Some(query) => format!("{}/?{query}", state.base),
None => format!("{}/", state.base),
};
Response::builder()
.status(StatusCode::PERMANENT_REDIRECT)
.header(header::LOCATION, location)
.body(Body::empty())
.expect("failed to build response")
}
fn path_validate(path: &str) -> bool {
if path.contains('\\') {
return false;
}
!Path::new(path).components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
})
}
async fn file_serve(dir: &Path, path: &str, index: &str, base: &str) -> Response {
if !path_validate(path) {
return html_not_found_build();
}
let mut file_path = dir.join(path);
let is_dir = tokio::fs::metadata(&file_path)
.await
.is_ok_and(|m| m.is_dir());
if is_dir {
file_path = file_path.join(index);
}
let bytes = match tokio::fs::read(&file_path).await {
Ok(bytes) => bytes,
Err(_) => return html_not_found_build(),
};
let is_html = file_path.extension().and_then(|e| e.to_str()) == Some("html");
if is_html {
match String::from_utf8(bytes) {
Ok(html) => html_response_build(js_script_inject(&html, base)),
Err(err) => html_response_build(err.into_bytes()),
}
} else {
let mime = mime_guess::from_path(&file_path).first_or_octet_stream();
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, mime.as_ref())
.header(header::CACHE_CONTROL, "no-cache")
.body(Body::from(bytes))
.expect("failed to build response")
}
}
fn html_response_build(body: impl Into<Bytes>) -> Response {
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "text/html; charset=utf-8")
.header(header::CACHE_CONTROL, "no-cache")
.body(Body::from(body.into()))
.expect("failed to build response")
}
fn html_not_found_build() -> Response {
Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.expect("failed to build response")
}
fn js_script_inject(html: &str, base: &str) -> String {
let script = r#"<script>
const es = new EventSource('__BASE__/livereload');
let first = true;
es.addEventListener('open', () => {
if (first) {
first = false;
console.log('[webadev] live reload connected');
} else {
// Server restarted: reload to resync
location.reload();
}
});
es.addEventListener('page', () => location.reload());
es.addEventListener('css', () => {
document.querySelectorAll('link[rel="stylesheet"]').forEach(link => {
const url = new URL(link.href, location.href);
url.searchParams.set('t', Date.now());
link.href = url.toString();
});
console.log('[webadev] css hot-reloaded');
});
es.addEventListener('error', () => console.warn('[webadev] live reload connection lost', es.readyState));
</script>"#;
let script = script.replace("__BASE__", base);
if html.contains("</body>") {
html.replace("</body>", &format!("{}\n</body>", script))
} else if html.contains("</html>") {
html.replace("</html>", &format!("{}\n</html>", script))
} else {
format!("{}\n{}", html, script)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::{create_dir_all, write};
use std::net::IpAddr;
use axum::{
body::Body,
http::{HeaderMap, Request, StatusCode},
};
use http_body_util::BodyExt;
use tempfile::tempdir;
use tokio::sync::broadcast;
use tower::ServiceExt;
fn test_app(dir: &Path) -> Router {
test_app_with_index(dir, "index.html")
}
fn test_app_with_index(dir: &Path, index: &str) -> Router {
test_app_with_headers_and_index(dir, &[], index)
}
fn test_app_with_headers(dir: &Path, headers: &[&str]) -> Router {
test_app_with_headers_and_index(dir, headers, "index.html")
}
fn test_app_with_headers_and_index(dir: &Path, headers: &[&str], index: &str) -> Router {
test_app_full(dir, headers, index, "")
}
fn test_app_with_base(dir: &Path, base: &str) -> Router {
test_app_full(dir, &[], "index.html", base)
}
fn test_app_full(dir: &Path, headers: &[&str], index: &str, base: &str) -> Router {
let (tx, _rx) = broadcast::channel(8);
let headers = headers.iter().map(|s| s.to_string()).collect::<Vec<_>>();
app_build(AppState {
dir: dir.to_path_buf(),
tx,
headers: headers_parse(&headers).unwrap(),
index: index.to_string(),
base: base_normalize(base).unwrap(),
})
}
async fn get(app: &Router, uri: &str) -> (StatusCode, Vec<u8>) {
let resp = app
.clone()
.oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
.await
.unwrap();
let status = resp.status();
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
(status, bytes.to_vec())
}
fn html_write(dir: &Path, rel: &str, content: &str) {
let full = dir.join(rel);
create_dir_all(full.parent().unwrap()).unwrap();
write(full, content).unwrap();
}
#[tokio::test]
async fn serves_root_index_with_injected_script() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html><body>hi</body></html>");
let app = test_app(dir.path());
let (status, body) = get(&app, "/").await;
assert_eq!(status, 200);
let html = String::from_utf8(body).unwrap();
assert!(html.contains("hi"));
assert!(html.contains("EventSource"));
assert!(html.contains("EventSource('/livereload')"));
assert!(html.contains("reload"));
}
#[tokio::test]
async fn serves_nested_directory_index() {
let dir = tempdir().unwrap();
html_write(dir.path(), "sub/index.html", "<html>sub</html>");
let app = test_app(dir.path());
let (status, body) = get(&app, "/sub").await;
assert_eq!(status, 200);
assert!(String::from_utf8(body).unwrap().contains("sub"));
}
#[tokio::test]
async fn missing_file_is_404() {
let dir = tempdir().unwrap();
let app = test_app(dir.path());
let (status, _) = get(&app, "/nope.html").await;
assert_eq!(status, 404);
}
#[tokio::test]
async fn path_traversal_is_rejected() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html></html>");
let app = test_app(dir.path());
let (status, _) = get(&app, "/../../etc/passwd").await;
assert_eq!(status, 404);
}
#[tokio::test]
async fn rooted_path_is_rejected() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html></html>");
let outside = tempdir().unwrap();
let secret = outside.path().join("secret.txt");
write(&secret, "secret").unwrap();
let resp = file_serve(dir.path(), secret.to_str().unwrap(), "index.html", "").await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn parent_and_backslash_paths_are_rejected() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html></html>");
for path in [
"../index.html",
"sub/../../index.html",
"sub\\..\\index.html",
] {
let resp = file_serve(dir.path(), path, "index.html", "").await;
assert_eq!(
resp.status(),
StatusCode::NOT_FOUND,
"path `{path}` must be rejected"
);
}
}
#[tokio::test]
async fn encoded_rooted_path_is_rejected() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html></html>");
let app = test_app(dir.path());
for uri in ["/%2Fetc/passwd", "/%2e%2e/etc/passwd"] {
let (status, _) = get(&app, uri).await;
assert_eq!(status, 404, "uri `{uri}` must be rejected");
}
}
#[tokio::test]
async fn css_is_served_without_script() {
let dir = tempdir().unwrap();
html_write(dir.path(), "style.css", "body {}");
let app = test_app(dir.path());
let (status, body) = get(&app, "/style.css").await;
assert_eq!(status, 200);
assert_eq!(String::from_utf8(body).unwrap(), "body {}");
}
#[tokio::test]
async fn non_utf8_html_is_served_raw() {
let dir = tempdir().unwrap();
let raw: Vec<u8> = vec![0xff, 0xfe, 0xfd];
write(dir.path().join("index.html"), &raw).unwrap();
let app = test_app(dir.path());
let (status, body) = get(&app, "/").await;
assert_eq!(status, 200);
assert_eq!(body, raw);
}
#[tokio::test]
async fn serves_under_base_prefix() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html><body>hi</body></html>");
html_write(dir.path(), "sub/index.html", "<html>sub</html>");
let app = test_app_with_base(dir.path(), "/app");
let (status, body) = get(&app, "/app/").await;
assert_eq!(status, 200);
let html = String::from_utf8(body).unwrap();
assert!(html.contains("hi"));
assert!(html.contains("EventSource('/app/livereload')"));
let (status, body) = get(&app, "/app/sub").await;
assert_eq!(status, 200);
assert!(String::from_utf8(body).unwrap().contains("sub"));
}
#[tokio::test]
async fn base_redirects_to_trailing_slash() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html>hi</html>");
let app = test_app_with_base(dir.path(), "/app");
let resp = app
.clone()
.oneshot(Request::builder().uri("/app").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::PERMANENT_REDIRECT);
assert_eq!(resp.headers()["location"], "/app/");
let resp = app
.clone()
.oneshot(
Request::builder()
.uri("/app?x=1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.headers()["location"], "/app/?x=1");
}
#[tokio::test]
async fn base_does_not_serve_outside_prefix() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html>hi</html>");
html_write(dir.path(), "style.css", "body {}");
let app = test_app_with_base(dir.path(), "/app");
for uri in ["/", "/index.html", "/style.css", "/appfoo/", "/app2/"] {
let (status, _) = get(&app, uri).await;
assert_eq!(status, 404, "uri `{uri}` must be outside the base");
}
}
#[tokio::test]
async fn base_rejects_rooted_and_traversal_paths() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html>hi</html>");
let app = test_app_with_base(dir.path(), "/app");
for uri in [
"/app//etc/passwd",
"/app/%2Fetc/passwd",
"/app/%2e%2e/etc/passwd",
] {
let (status, _) = get(&app, uri).await;
assert_eq!(status, 404, "uri `{uri}` must be rejected");
}
}
#[tokio::test]
async fn base_serves_with_custom_headers() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html>hi</html>");
let app = test_app_full(dir.path(), &["X-Custom: yes"], "index.html", "/app");
let headers = headers_get(&app, "/app/").await;
assert_eq!(headers["X-Custom"], "yes");
}
#[tokio::test]
async fn server_url_includes_base() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html>hi</html>");
let (tx, _rx) = broadcast::channel(8);
let mut config = test_config(dir.path());
config.base = "/app".into();
let server = Server::bind(tx, config).await.unwrap();
assert!(server.url.ends_with("/app"), "url: {}", server.url);
}
#[tokio::test]
async fn invalid_base_is_rejected_at_bind() {
let dir = tempdir().unwrap();
let (tx, _rx) = broadcast::channel(8);
let mut config = test_config(dir.path());
config.base = "/{*x}".into();
let err = Server::bind(tx, config).await.unwrap_err();
assert!(err.contains("Invalid --base"), "error: {err}");
}
async fn headers_get(app: &Router, uri: &str) -> HeaderMap {
let resp = app
.clone()
.oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
.await
.unwrap();
resp.into_parts().0.headers
}
#[tokio::test]
async fn custom_header_is_applied_to_html() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html>hi</html>");
let app = test_app_with_headers(dir.path(), &["X-Custom: yes"]);
let headers = headers_get(&app, "/").await;
assert_eq!(headers["X-Custom"], "yes");
}
#[tokio::test]
async fn custom_header_is_applied_to_static_file() {
let dir = tempdir().unwrap();
write(dir.path().join("app.js"), "let x = 1;").unwrap();
let app = test_app_with_headers(dir.path(), &["X-Custom: yes"]);
let headers = headers_get(&app, "/app.js").await;
assert_eq!(headers["X-Custom"], "yes");
}
#[tokio::test]
async fn multiple_custom_headers_are_all_applied() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html>hi</html>");
let app = test_app_with_headers(dir.path(), &["X-A: 1", "X-B: 2"]);
let headers = headers_get(&app, "/").await;
assert_eq!(headers["X-A"], "1");
assert_eq!(headers["X-B"], "2");
}
#[tokio::test]
async fn custom_header_overrides_existing_value() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html>hi</html>");
let app = test_app_with_headers(dir.path(), &["Cache-Control: max-age=60"]);
let headers = headers_get(&app, "/").await;
assert_eq!(headers["Cache-Control"], "max-age=60");
}
#[test]
fn invalid_header_is_rejected() {
assert!(headers_parse(&["Bad\nHeader: x".to_string()]).is_err());
assert!(headers_parse(&["NoSeparator".to_string()]).is_err());
assert!(headers_parse(&[": novalue".to_string()]).is_err());
assert!(headers_parse(&["X-Foo:".to_string()]).is_ok());
}
fn test_config(dir: &Path) -> Config {
Config {
dir: dir.to_path_buf(),
ip: IpAddr::from([127, 0, 0, 1]),
port: 0,
headers: vec![],
index: "index.html".into(),
base: String::new(),
}
}
#[tokio::test]
async fn server_bind_reports_real_port() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.html", "<html>hi</html>");
let (tx, _rx) = broadcast::channel(8);
let server = Server::bind(tx, test_config(dir.path())).await.unwrap();
assert!(server.url.starts_with("http://127.0.0.1:"));
assert!(!server.url.ends_with(":0"));
}
#[tokio::test]
async fn custom_index_is_served_at_root() {
let dir = tempdir().unwrap();
html_write(dir.path(), "about.html", "<html>about</html>");
let app = test_app_with_index(dir.path(), "about.html");
let (status, body) = get(&app, "/").await;
assert_eq!(status, 200);
assert!(String::from_utf8(body).unwrap().contains("about"));
}
#[tokio::test]
async fn custom_index_is_404_when_absent() {
let dir = tempdir().unwrap();
let app = test_app_with_index(dir.path(), "about.html");
let (status, _) = get(&app, "/").await;
assert_eq!(status, 404);
}
#[tokio::test]
async fn custom_index_works_for_subdirectories() {
let dir = tempdir().unwrap();
html_write(dir.path(), "sub/about.html", "<html>sub about</html>");
let app = test_app_with_index(dir.path(), "about.html");
let (status, body) = get(&app, "/sub").await;
assert_eq!(status, 200);
assert!(String::from_utf8(body).unwrap().contains("sub about"));
}
#[tokio::test]
async fn non_html_index_is_served_raw() {
let dir = tempdir().unwrap();
html_write(dir.path(), "index.md", "# readme");
let app = test_app_with_index(dir.path(), "index.md");
let (status, body) = get(&app, "/").await;
assert_eq!(status, 200);
assert_eq!(String::from_utf8(body).unwrap(), "# readme");
}
#[test]
fn invalid_index_is_rejected() {
assert!(index_validate("").is_err());
assert!(index_validate(".").is_err());
assert!(index_validate("..").is_err());
assert!(index_validate("./x").is_err());
assert!(index_validate("../x").is_err());
assert!(index_validate("/etc/passwd").is_err());
assert!(index_validate("a/b").is_err());
assert!(index_validate("a\\b").is_err());
assert!(index_validate(".hidden").is_err());
assert!(index_validate("index.html").is_ok());
assert!(index_validate("about.html").is_ok());
}
}