//! The HTTP side: three routes and the page's files, on 127.0.0.1 only. use std::io::Cursor; use std::net::SocketAddr; use std::sync::Arc; use std::thread; use include_dir::{include_dir, Dir}; use sccache_dash_api::Range; use serde_json::Value; use tiny_http::{Header, Request, Response, Server}; use crate::app::App; use crate::pretty; /// The page as `trunk build` wrote it to crates/ui/dist, or a placeholder saying it is not built /// (the build script names the folder in `DASH_SITE`). static SITE: Dir<'_> = include_dir!("$DASH_SITE"); type Reply = Response>>; /// Serves until the process ends. pub fn serve(app: Arc, port: u16) -> Result<(), String> { answer(listen(port)?, app); Ok(()) } /// Binds 127.0.0.1 and nothing else; port 0 picks a free one. pub fn listen(port: u16) -> Result { Server::http(SocketAddr::from(([127, 0, 0, 1], port))) .map_err(|e| format!("cannot listen on 127.0.0.1:{port}: {e}")) } /// The port a listening server answers on. pub fn port_of(server: &Server) -> u16 { server.server_addr().to_ip().map_or(0, |a| a.port()) } /// Answers requests until the process ends. pub fn answer(server: Server, app: Arc) { let port = port_of(&server); for mut request in server.incoming_requests() { let app = Arc::clone(&app); thread::spawn(move || { let response = handle(&app, port, &mut request); let _ = request.respond(response); }); } } fn handle(app: &App, port: u16, req: &mut Request) -> Reply { let url = req.url(); let (path, query) = url.split_once('?').unwrap_or((url, "")); match (req.method().as_str(), path) { ("GET", "/api/view") => match range_of(query) { Some(range) => reply( 200, "application/json", serde_json::to_vec(&app.view(range)).unwrap_or_default(), ) .with_header(header("Cache-Control", "no-store")), None => text(400, "unknown range: use 1h, 24h, 7d, 30d or reset"), }, ("GET" | "HEAD", "/api/export") => export(app), ("POST", "/api/zero") => zero(app, port, req), (_, "/api/zero") => text(405, "use POST"), ("GET" | "HEAD", _) => site_file(path), _ => text(404, "not found"), } } /// `range=24h` in the query string. fn range_of(query: &str) -> Option { let value = query.split('&').find_map(|p| p.strip_prefix("range="))?; serde_json::from_value(Value::String(value.to_owned())).ok() } /// sccache's output exactly as it printed it, as a download. fn export(app: &App) -> Reply { let state = app.lock(); match &state.live { Some(live) => reply(200, "application/json", live.raw_text.clone().into_bytes()) .with_header(header( "Content-Disposition", &format!( "attachment; filename=\"sccache-stats-{}.json\"", pretty::stamp(live.at) ), )), None => text( 502, &format!( "sccache did not answer: {}", state.error.as_deref().unwrap_or("no reading yet") ), ), } } /// Runs `sccache --zero-stats`. Only this machine's own dashboard may ask for that. fn zero(app: &App, port: u16, req: &Request) -> Reply { if !from_own_page(req, port) { return text( 403, "refused: only the dashboard's own page, on this machine, may zero the stats", ); } match app.zero() { Ok(()) => text( 200, "sccache's counters were zeroed; the saved history is kept", ), Err(e) => text(502, &format!("could not zero the stats: {e}")), } } /// Whether a request comes from the dashboard itself: its `Host` is localhost, and when a web /// page sent it (it carries an `Origin`) that page is this server. A page anywhere else must /// not be able to zero the stats, and neither may a host name that merely resolves here. fn from_own_page(req: &Request, port: u16) -> bool { let header = |name: &'static str| { req.headers() .iter() .find(|h| h.field.equiv(name)) .map(|h| h.value.as_str()) }; // `name` or `name:port`, with a port made of digits and nothing else. let host_is_local = |host: &str| { let mut parts = host.splitn(2, ':'); let name = parts.next().unwrap_or_default(); let port = parts.next().unwrap_or(""); (name.eq_ignore_ascii_case("127.0.0.1") || name.eq_ignore_ascii_case("localhost")) && port.bytes().all(|b| b.is_ascii_digit()) }; let own_origins = [ format!("http://127.0.0.1:{port}"), format!("http://localhost:{port}"), ]; header("Host").is_some_and(host_is_local) && header("Origin").is_none_or(|origin| own_origins.iter().any(|own| own == origin)) } /// A file of the page; `/` is its index. fn site_file(path: &str) -> Reply { let name = path.trim_start_matches('/'); let name = if name.is_empty() { "index.html" } else { name }; match SITE.get_file(name) { Some(file) => reply(200, content_type(name), file.contents().to_vec()), None => text(404, "not found"), } } /// Content types by file extension, as the page's own files need them. fn content_type(path: &str) -> &'static str { match path.rsplit_once('.').map(|(_, ext)| ext) { Some("html") => "text/html; charset=utf-8", Some("js" | "mjs") => "text/javascript; charset=utf-8", Some("wasm") => "application/wasm", Some("css") => "text/css; charset=utf-8", Some("json" | "map") => "application/json", Some("svg") => "image/svg+xml", Some("png") => "image/png", Some("jpg" | "jpeg") => "image/jpeg", Some("gif") => "image/gif", Some("webp") => "image/webp", Some("ico") => "image/x-icon", Some("woff") => "font/woff", Some("woff2") => "font/woff2", Some("ttf") => "font/ttf", Some("otf") => "font/otf", Some("txt" | "md") => "text/plain; charset=utf-8", _ => "application/octet-stream", } } fn header(name: &'static str, value: &str) -> Header { Header::from_bytes(name.as_bytes(), value.as_bytes()).expect("a header made of plain ASCII") } fn reply(code: u16, content_type: &str, body: Vec) -> Reply { Response::from_data(body) .with_status_code(code) .with_header(header("Content-Type", content_type)) } fn text(code: u16, body: &str) -> Reply { reply(code, "text/plain; charset=utf-8", body.as_bytes().to_vec()) } #[cfg(test)] mod tests { use super::*; #[test] fn the_page_or_its_placeholder_is_in_the_binary() { assert!( SITE.get_file("index.html").is_some(), "`/` must answer with a page" ); assert!( SITE.get_file("../Cargo.toml").is_none(), "nothing outside the page is served" ); assert!(SITE.get_file("no-such-file").is_none()); } #[test] fn content_types_are_what_browsers_need() { assert_eq!(content_type("index.html"), "text/html; charset=utf-8"); assert_eq!( content_type("app-a1b2c3.js"), "text/javascript; charset=utf-8" ); assert_eq!(content_type("app-a1b2c3.wasm"), "application/wasm"); assert_eq!(content_type("app.css"), "text/css; charset=utf-8"); assert_eq!(content_type("icons/sccache.svg"), "image/svg+xml"); assert_eq!(content_type("data"), "application/octet-stream"); } #[test] fn the_range_comes_from_the_query_string() { for (query, expected) in [ ("range=1h", Some(Range::Hour)), ("range=24h", Some(Range::Day)), ("range=7d", Some(Range::Week)), ("range=30d", Some(Range::Month)), ("range=reset", Some(Range::SinceReset)), ("other=1&range=24h", Some(Range::Day)), ("", None), ("range=all", None), ] { assert_eq!(range_of(query), expected, "{query:?}"); } } }