diff --git a/src/lib.rs b/src/lib.rs index 8a96122..7888392 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -33,6 +33,7 @@ pub mod stratum_v2_session; pub mod stratum_wire; pub mod stratum_work; pub mod tuning; +pub mod ui; pub mod web; #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/src/main.rs b/src/main.rs index 06ea365..e10b061 100644 --- a/src/main.rs +++ b/src/main.rs @@ -38,10 +38,7 @@ fn sim_mine(mut args: impl Iterator) -> Result<(), Box .ok() .map(|bind| bind.parse()) .transpose()?; - let web = std::env::var("ALKANE_WEB_LISTEN") - .ok() - .map(|bind| bind.parse()) - .transpose()?; + let web = web_listen()?; let servers = app::start(Arc::clone(&status), api, web)?; let (api_address, web_address) = servers.addresses(); if let Some(address) = api_address { @@ -212,10 +209,7 @@ fn boot_hal(mut args: impl Iterator) -> Result<(), Box .ok() .map(|bind| bind.parse()) .transpose()?; - let web = std::env::var("ALKANE_WEB_LISTEN") - .ok() - .map(|bind| bind.parse()) - .transpose()?; + let web = web_listen()?; let servers = app::start(Arc::clone(&status), api, web)?; let config = app::BootConfig { @@ -303,6 +297,44 @@ fn boot_hal(mut args: impl Iterator) -> Result<(), Box Ok(()) } +/// Where the UI listens. The miner serves it on port 80 of its own address; +/// if that is not permitted (a non-root development run), fall back to 8080 +/// rather than refusing to start. +fn web_listen() -> Result, Box> { + if let Ok(bind) = std::env::var("ALKANE_WEB_LISTEN") { + return Ok(Some(bind.parse()?)); + } + let port = if std::net::TcpListener::bind("0.0.0.0:80").is_ok() { + 80 + } else { + 8080 + }; + Ok(Some(std::net::SocketAddr::from(([0, 0, 0, 0], port)))) +} + +/// Serve the UI and the API without a mining backend. A board whose HAL +/// backend is not written yet still has to be reachable and observable; every +/// page says "not identified" rather than claiming hardware it cannot see. +fn serve_only() -> Result<(), Box> { + let status = Arc::new(MiningStatus::new()); + let api = std::env::var("ALKANE_API_LISTEN") + .ok() + .map(|bind| bind.parse()) + .transpose()?; + let api = api.or(Some("0.0.0.0:4028".parse()?)); + let servers = app::start(Arc::clone(&status), api, web_listen()?)?; + let (api_address, web_address) = servers.addresses(); + if let Some(address) = api_address { + println!("management API on {address}"); + } + if let Some(address) = web_address { + println!("web UI on http://{address}"); + } + loop { + std::thread::sleep(Duration::from_secs(3600)); + } +} + fn main() { let mut args = std::env::args().skip(1); match args.next().as_deref() { @@ -316,6 +348,12 @@ fn main() { } } Some("--version") => println!("alkane-os {}", env!("CARGO_PKG_VERSION")), + Some("--serve") => { + if let Err(error) = serve_only() { + eprintln!("serve failed: {error}"); + std::process::exit(1); + } + } Some("--boot") => { if let Err(error) = boot_hal(args) { eprintln!("boot failed: {error}"); diff --git a/src/ui.rs b/src/ui.rs new file mode 100644 index 0000000..69497d8 --- /dev/null +++ b/src/ui.rs @@ -0,0 +1,497 @@ +// SPDX-License-Identifier: MIT +//! On-box web UI: navigation, pages, and the editable dashboard document. +//! +//! The shape follows the Warden/FLARE console: a fixed sidebar of groups and +//! items, hash-routed pages, and dashboards that are a JSON document an operator +//! edits in place. The document is stored on the box, has a default template per +//! deck, and is capped server-side so a bad save cannot grow without bound. +//! +//! The JSON API remains the interface of record: every value the pages show is +//! also available at an `/api/...` route, and the page never becomes the only +//! way to see or change the machine. + +use serde_json::{json, Value}; + +/// Blocks a dashboard may hold. Docker rows count too, so a tidy layout cannot +/// cost an operator a widget. +pub const BLOCK_CAP: usize = 32; +/// Characters allowed in a dashboard name. +pub const NAME_MAX: usize = 120; + +/// One navigable destination. +pub struct Item { + pub path: &'static str, + pub label: &'static str, +} + +/// A sidebar group. +pub struct Group { + pub label: &'static str, + pub items: &'static [Item], +} + +const DASHBOARD: [Item; 1] = [Item { + path: "/", + label: "Dashboard", +}]; +const MINING: [Item; 4] = [ + Item { + path: "/mining", + label: "Overview", + }, + Item { + path: "/mining/hashboards", + label: "Hashboards", + }, + Item { + path: "/mining/power", + label: "Power Supply", + }, + Item { + path: "/mining/fans", + label: "Fans", + }, +]; +const SETTINGS: [Item; 8] = [ + Item { + path: "/settings/system", + label: "System", + }, + Item { + path: "/settings/drivers", + label: "Drivers", + }, + Item { + path: "/settings/security", + label: "Security", + }, + Item { + path: "/settings/services", + label: "Services", + }, + Item { + path: "/settings/monitor", + label: "Monitor", + }, + Item { + path: "/settings/logs", + label: "Logs", + }, + Item { + path: "/settings/files", + label: "Files", + }, + Item { + path: "/settings/terminal", + label: "Terminal", + }, +]; + +pub const NAV: [Group; 3] = [ + Group { + label: "Overview", + items: &DASHBOARD, + }, + Group { + label: "Mining", + items: &MINING, + }, + Group { + label: "Settings", + items: &SETTINGS, + }, +]; + +/// The dashboard a deck starts with. Every deck has one, so a fresh box is never +/// an empty page. +pub fn default_deck(deck: &str) -> Value { + match deck { + "overview" => json!({ + "version": 1, + "name": "Mining overview", + "blocks": [ + {"id": "status", "kind": "status", "span": 1, "title": "State", "source": "status"}, + {"id": "accepted", "kind": "metric", "span": 1, "title": "Accepted", "source": "accepted", "unit": "shares"}, + {"id": "rejected", "kind": "metric", "span": 1, "title": "Rejected", "source": "rejected", "unit": "shares"}, + {"id": "elapsed", "kind": "metric", "span": 1, "title": "Uptime", "source": "elapsed", "unit": "s"}, + {"id": "chains", "kind": "metric", "span": 1, "title": "Active chains", "source": "active_chains", "unit": ""}, + {"id": "frequency", "kind": "metric", "span": 1, "title": "Frequency", "source": "frequency", "unit": "MHz"}, + {"id": "voltage", "kind": "metric", "span": 1, "title": "Voltage", "source": "voltage", "unit": "mV"}, + {"id": "target", "kind": "metric", "span": 1, "title": "Target", "source": "target", "unit": ""}, + {"id": "chains_table", "kind": "table", "span": 4, "title": "Hashboards", "source": "chains"} + ] + }), + _ => json!({ + "version": 1, + "name": "Dashboard", + "blocks": [ + {"id": "status", "kind": "status", "span": 2, "title": "Miner", "source": "status"}, + {"id": "accepted", "kind": "metric", "span": 1, "title": "Accepted", "source": "accepted", "unit": "shares"}, + {"id": "rejected", "kind": "metric", "span": 1, "title": "Rejected", "source": "rejected", "unit": "shares"}, + {"id": "hardware", "kind": "kv", "span": 2, "title": "Hardware", "source": "hardware"}, + {"id": "fans", "kind": "table", "span": 2, "title": "Fan map", "source": "fans"} + ] + }), + } +} + +/// Validate a dashboard document the client wants to store. +/// +/// Returns the parsed document, or a sentence naming the rule that failed. The +/// rules are the same ones the page enforces, so a save that the UI allowed is +/// never rejected here for a reason the operator cannot see. +pub fn validate_deck(text: &str) -> Result { + let doc: Value = + serde_json::from_str(text).map_err(|_| "document is not valid JSON".to_string())?; + let object = doc.as_object().ok_or("document must be an object")?; + let version = object + .get("version") + .and_then(Value::as_u64) + .ok_or("version must be a number")?; + if version != 1 { + return Err(format!("unsupported version {version}")); + } + if let Some(name) = object.get("name") { + let name = name.as_str().ok_or("name must be a string")?; + if name.chars().count() > NAME_MAX { + return Err(format!("name is longer than {NAME_MAX} characters")); + } + } + let blocks = object + .get("blocks") + .and_then(Value::as_array) + .ok_or("blocks must be a list")?; + if blocks.len() > BLOCK_CAP { + return Err(format!("more than {BLOCK_CAP} blocks")); + } + for block in blocks { + let block = block.as_object().ok_or("each block must be an object")?; + let id = block + .get("id") + .and_then(Value::as_str) + .ok_or("block id must be a string")?; + if id.is_empty() || id.len() > 64 { + return Err("block id must be 1..=64 characters".to_string()); + } + let kind = block + .get("kind") + .and_then(Value::as_str) + .ok_or("block kind must be a string")?; + if !["metric", "status", "kv", "table", "text"].contains(&kind) { + return Err(format!("unknown block kind {kind}")); + } + let span = block.get("span").and_then(Value::as_u64).unwrap_or(1); + if !(1..=4).contains(&span) { + return Err("block span must be 1..=4".to_string()); + } + } + Ok(doc) +} + +/// Render one page inside the shell. +pub fn page(active: &str, title: &str, body: &str) -> String { + format!( + "\n\ +\ +{title} - Alkane\ +

{title}

connecting
{body}
\ +", + title = escape(title), + nav = sidebar(active), + ) +} + +fn sidebar(active: &str) -> String { + let mut out = String::from("
Alkane
"); + for group in NAV.iter() { + out.push_str(&format!( + "
{}
    ", + escape(group.label) + )); + for item in group.items { + let class = if item.path == active { + " class=\"on\"" + } else { + "" + }; + out.push_str(&format!( + "
  • {}
  • ", + item.path, + escape(item.label) + )); + } + out.push_str("
"); + } + out +} + +/// A dashboard page: the editor chrome plus the document the client loads. +pub fn dashboard_page(deck: &str, editable: bool) -> String { + let deck = escape(deck); + format!( + "
\ +\ +\ +\ +\ +
\ +
", + disabled = if editable { "" } else { " disabled" }, + editable = if editable { "1" } else { "0" }, + ) +} + +/// Escape text for HTML. Every user-visible string goes through this. +pub fn escape(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for ch in text.chars() { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + other => out.push(other), + } + } + out +} + +/// A definition-list page for key/value data (settings pages). +pub fn kv_page(rows: &[(&str, String)]) -> String { + let mut out = String::from(""); + for (key, value) in rows { + out.push_str(&format!( + "", + escape(key), + escape(value) + )); + } + out.push_str("
{}{}
"); + out +} + +/// A table page with a header row. +pub fn table_page(headers: &[&str], rows: &[Vec]) -> String { + let mut out = String::from(""); + for header in headers { + out.push_str(&format!("", escape(header))); + } + out.push_str(""); + for row in rows { + out.push_str(""); + for cell in row { + out.push_str(&format!("", escape(cell))); + } + out.push_str(""); + } + if rows.is_empty() { + out.push_str(&format!( + "", + headers.len().max(1) + )); + } + out.push_str("
{}
{}
nothing to show
"); + out +} + +const CSS: &str = r#" +:root{color-scheme:dark}*{box-sizing:border-box} +body{margin:0;display:grid;grid-template-columns:220px 1fr;min-height:100vh;background:#0d1117;color:#e6edf3;font:14px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif} +.side{background:#11161d;border-right:1px solid #222c37;padding:14px 0;position:sticky;top:0;height:100vh;overflow:auto} +.brand{font-weight:700;font-size:17px;padding:0 16px 12px;letter-spacing:.3px} +.group{padding:14px 16px 4px;font-size:11px;text-transform:uppercase;letter-spacing:.8px;color:#7d8b9a} +.side ul{list-style:none;margin:0;padding:0} +.side a{display:block;padding:7px 16px;color:#c3cfdb;text-decoration:none;border-left:2px solid transparent} +.side a:hover{background:#161d26;color:#fff} +.side a.on{background:#161d26;color:#fff;border-left-color:#3b82f6;font-weight:600} +main{padding:18px 22px;min-width:0} +header{display:flex;align-items:center;gap:12px;margin-bottom:14px} +h1{font-size:19px;margin:0;font-weight:650} +.pill{font-size:11px;padding:3px 9px;border-radius:999px;background:#1c2530;color:#9fb0c0;border:1px solid #263241} +.pill.ok{color:#7ee787;border-color:#1f4d2c;background:#10231a} +.pill.bad{color:#ff9b9b;border-color:#552323;background:#261013} +.bar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:14px} +button{background:#1b2431;color:#dbe6f1;border:1px solid #2a3949;border-radius:7px;padding:7px 11px;font:inherit;cursor:pointer} +button:hover:not(:disabled){background:#233043} +button:disabled{opacity:.4;cursor:default} +select{background:#1b2431;color:#dbe6f1;border:1px solid #2a3949;border-radius:7px;padding:6px 8px;font:inherit} +.grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px} +.card{background:#11161d;border:1px solid #222c37;border-radius:10px;padding:12px 14px;min-height:96px} +.card.drag{outline:1px dashed #3b82f6} +.card h2{font-size:12px;margin:0 0 8px;color:#8fa2b5;font-weight:600;text-transform:uppercase;letter-spacing:.6px} +.card .big{font-size:28px;font-weight:650;letter-spacing:-.5px} +.card .unit{font-size:12px;color:#7d8b9a;margin-left:4px} +table{width:100%;border-collapse:collapse;font-size:13px} +th,td{text-align:left;padding:7px 9px;border-bottom:1px solid #1d2733} +th{color:#8fa2b5;font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.5px} +table.kv th{width:220px} +.muted{color:#7d8b9a} +.span2{grid-column:span 2}.span3{grid-column:span 3}.span4{grid-column:span 4} +pre{background:#0b0f14;border:1px solid #1d2733;border-radius:8px;padding:12px;overflow:auto;max-height:60vh;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace} +input[type=text]{background:#0b0f14;border:1px solid #2a3949;border-radius:7px;color:#e6edf3;padding:8px 10px;font:inherit;min-width:320px} +"#; + +const JS: &str = r#" +(function(){ +"use strict"; +function $(id){return document.getElementById(id)} +function esc(s){return String(s).replace(/[&<>"']/g,function(c){return {'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]})} +function route(){var p=location.hash.slice(1)||"/";return p} +function go(){location.hash=route()} +// Live status pill: the page is a convenience over the JSON API. +function poll(){fetch("/api/summary").then(function(r){return r.json()}).then(function(d){ + var el=$("live"); if(!el)return; var m=(d.miner||d); el.textContent=(m.state||"up"); el.className="pill ok"; +}).catch(function(){var el=$("live"); if(el){el.textContent="offline"; el.className="pill bad"}})} +setInterval(poll,5000); poll(); + +var grid=$("grid"); +if(grid){ + var deck=grid.dataset.deck, editable=grid.dataset.editable==="1", doc=null, dragId=null; + var METRICS={hashrate:["TH/s",1],power_w:["W",1],chains:["",0],chip_temp_c:["C",0],fans:["",0]}; + function render(){ + grid.innerHTML=""; + (doc.blocks||[]).forEach(function(b){ + var card=document.createElement("div"); + card.className="card span"+(b.span||1); + card.draggable=editable; + card.addEventListener("dragstart",function(){dragId=b.id;card.classList.add("drag")}); + card.addEventListener("dragend",function(){card.classList.remove("drag")}); + card.addEventListener("dragover",function(e){e.preventDefault()}); + card.addEventListener("drop",function(e){e.preventDefault(); if(!dragId||dragId===b.id)return; + var from=doc.blocks.findIndex(function(x){return x.id===dragId}); + var to=doc.blocks.findIndex(function(x){return x.id===b.id}); + if(from<0||to<0)return; var moved=doc.blocks.splice(from,1)[0]; doc.blocks.splice(to,0,moved); render(); msg("unsaved changes")}); + var h=document.createElement("h2"); h.textContent=b.title||b.id; card.appendChild(h); + if(b.kind==="metric"||b.kind==="status"){ + var big=document.createElement("div"); big.className="big"; big.textContent="--"; + big.dataset.source=b.source||""; card.appendChild(big); + if(b.unit){var u=document.createElement("span"); u.className="unit"; u.textContent=b.unit; card.appendChild(u)} + } else if(b.kind==="table"){ + var t=document.createElement("table"); + t.dataset[b.source==="fans"?"fans":"table"]=b.source||""; + t.innerHTML="loading"; + card.appendChild(t); + } else { + var p=document.createElement("div"); p.className="muted"; p.dataset.kv=b.source||""; p.textContent="loading"; card.appendChild(p); + } + grid.appendChild(card); + }); + } + function msg(text){var el=$("edit-msg"); if(el)el.textContent=text} + function fill(){ + var hw=null, sm=null; + function paint(){ + if(!hw||!sm)return; + var s=(sm.SUMMARY||[{}])[0]; + var src={ + status:(s.Status||"unknown"), + accepted:(s.Accepted||0), + rejected:(s.Rejected||0), + elapsed:(s.Elapsed||0), + active_chains:(hw.active_chains||[]).length, + frequency:(hw.frequency_mhz||0), + voltage:((hw.operating_point||{}).voltage_mv||0), + target:(hw.target||"-") + }; + document.querySelectorAll("[data-source]").forEach(function(el){ + var v=src[el.dataset.source]; + if(v===undefined||v===null){el.textContent="not reported"; el.classList.add("muted"); return} + el.textContent=String(v); + }); + document.querySelectorAll("[data-table]").forEach(function(t){ + var rows=(hw.chains||[]).map(function(c){return [c.index,c.chip,c.chips_found,JSON.stringify(c.eeprom),c.response_per_mille]}); + if(!rows.length){t.innerHTML="no chains reported";return} + t.innerHTML="#chipchipseepromresponse"+ + rows.map(function(r){return ""+r.map(function(c){return ""+esc(c)+""}).join("")+""}).join("")+""; + }); + document.querySelectorAll("[data-kv]").forEach(function(el){ + var rows=[["profile",hw.profile||"-"],["chip",hw.chip||"-"],["psu",hw.psu||"-"],["target",hw.target||"-"],["stopped",hw.stopped?hw.stopped:"no"]]; + el.innerHTML=rows.map(function(r){return "
"+esc(r[0])+" "+esc(r[1])+"
"}).join(""); + }); + document.querySelectorAll("[data-fans]").forEach(function(t){ + var rows=(hw.fan_zones||[]).map(function(z){return [z.fan,(z.zones||[]).join(", ")]}); + if(!rows.length){t.innerHTML="not mapped yet";return} + t.innerHTML="fanzones"+ + rows.map(function(r){return ""+esc(r[0])+""+esc(r[1])+""}).join("")+""; + }); + } + fetch("/api/hardware").then(function(r){return r.json()}).then(function(h){hw=h;paint()}).catch(function(){msg("hardware unavailable")}); + fetch("/api/summary").then(function(r){return r.json()}).then(function(s){sm=s;paint()}).catch(function(){}); + } + fetch("/api/dashboard?deck="+encodeURIComponent(deck)).then(function(r){return r.json()}).then(function(d){doc=d;render();fill()}); + if(editable){ + $("save").onclick=function(){fetch("/api/dashboard?deck="+encodeURIComponent(deck),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(doc)}).then(function(r){if(r.ok){msg("saved")}else{r.text().then(msg)}})}; + $("reset").onclick=function(){fetch("/api/dashboard?deck="+encodeURIComponent(deck)+"&reset=1",{method:"PUT",headers:{"Content-Type":"application/json"},body:"{}"}).then(function(r){return r.json()}).then(function(d){doc=d;render();fill();msg("template restored")})}; + $("add").onclick=function(){ + if(doc.blocks.length>=32){msg("32 blocks is the limit");return} + var id="block"+(doc.blocks.length+1); + doc.blocks.push({id:id,kind:"metric",span:1,title:"New block",source:"power_w",unit:"W"});render();msg("unsaved changes")}; + } +} +})(); +"#; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_sidebar_item_has_a_page() { + for group in NAV.iter() { + for item in group.items { + assert!(item.path.starts_with('/'), "{} has no path", item.label); + assert!(!item.label.is_empty()); + } + } + assert_eq!(NAV.iter().map(|g| g.items.len()).sum::(), 13); + } + + #[test] + fn default_decks_are_valid() { + for deck in ["dashboard", "overview"] { + let doc = default_deck(deck); + let text = doc.to_string(); + assert!(validate_deck(&text).is_ok(), "{deck} default rejected"); + } + } + + #[test] + fn the_block_cap_is_enforced() { + let mut blocks = Vec::new(); + for i in 0..=BLOCK_CAP { + blocks.push(json!({"id": format!("b{i}"), "kind": "metric", "span": 1})); + } + let doc = json!({"version": 1, "blocks": blocks}); + assert!(validate_deck(&doc.to_string()).is_err()); + } + + #[test] + fn malformed_documents_are_rejected_with_a_reason() { + assert!(validate_deck("not json").is_err()); + assert!(validate_deck("{}").is_err()); + assert!(validate_deck(r#"{"version":2,"blocks":[]}"#).is_err()); + assert!( + validate_deck(r#"{"version":1,"blocks":[{"id":"x","kind":"evil","span":1}]}"#).is_err() + ); + assert!( + validate_deck(r#"{"version":1,"blocks":[{"id":"x","kind":"metric","span":9}]}"#) + .is_err() + ); + } + + #[test] + fn sidebar_marks_the_active_page() { + let html = page("/mining/fans", "Fans", ""); + assert!(html.contains("href=\"#/mining/fans\" class=\"on\"")); + assert!(html.contains("Power Supply")); + } + + #[test] + fn user_text_is_escaped() { + assert_eq!(escape(" - - -"#; +const MAX_HEAD: usize = 8192; +const MAX_BODY: usize = 64 * 1024; +const CLIENT_TIMEOUT: Duration = Duration::from_millis(2000); +const DECK_DIR: &str = "/var/lib/alkane/decks"; +const TOKEN_FILE: &str = "/var/lib/alkane/ui-token"; +const LOG_FILE: &str = "/var/log/messages"; /// Bind and serve until the listener fails. pub fn serve(bind: SocketAddr, status: Arc) -> io::Result<()> { @@ -72,7 +39,6 @@ pub fn serve_listener(listener: TcpListener, status: Arc) -> io::R for stream in listener.incoming() { let Ok(stream) = stream else { continue }; let status = Arc::clone(&status); - // Each connection is short, bounded and closes itself. std::thread::spawn(move || { let _ = handle(stream, &status); }); @@ -80,57 +46,678 @@ pub fn serve_listener(listener: TcpListener, status: Arc) -> io::R Ok(()) } +struct Request { + method: String, + path: String, + query: String, + body: String, +} + +impl Request { + fn param(&self, key: &str) -> Option { + self.query.split('&').find_map(|pair| { + let (k, v) = pair.split_once('=')?; + if k == key { + Some(percent_decode(v)) + } else { + None + } + }) + } + + fn param_or(&self, key: &str, fallback: &str) -> String { + self.param(key).unwrap_or_else(|| fallback.to_string()) + } +} + +fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'%' if i + 2 < bytes.len() => { + let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""); + match u8::from_str_radix(hex, 16) { + Ok(byte) => { + out.push(byte); + i += 3; + } + Err(_) => { + out.push(bytes[i]); + i += 1; + } + } + } + b'+' => { + out.push(b' '); + i += 1; + } + byte => { + out.push(byte); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + /// Handle one HTTP request. pub fn handle(mut stream: TcpStream, status: &MiningStatus) -> io::Result<()> { stream.set_read_timeout(Some(CLIENT_TIMEOUT))?; stream.set_write_timeout(Some(CLIENT_TIMEOUT))?; - let mut request = Vec::new(); - let mut chunk = [0_u8; 512]; - loop { + let mut raw = Vec::new(); + let mut chunk = [0_u8; 1024]; + let mut head_end = None; + while head_end.is_none() { let count = stream.read(&mut chunk)?; if count == 0 { break; } - request.extend_from_slice(&chunk[..count]); - if request.len() > MAX_REQUEST_BYTES { - return respond(&mut stream, 431, "text/plain", b"request too large"); + raw.extend_from_slice(&chunk[..count]); + if raw.len() > MAX_HEAD { + return respond(&mut stream, 431, "text/plain", b"request head too large"); } - if request.windows(4).any(|window| window == b"\r\n\r\n") { + head_end = raw.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4); + } + let Some(head_end) = head_end else { + return respond(&mut stream, 400, "text/plain", b"bad request"); + }; + let head = String::from_utf8_lossy(&raw[..head_end]).into_owned(); + let mut lines = head.lines(); + let mut first = lines.next().unwrap_or("").split_whitespace(); + let method = first.next().unwrap_or("").to_string(); + let target = first.next().unwrap_or("/").to_string(); + let (path, query) = match target.split_once('?') { + Some((p, q)) => (p.to_string(), q.to_string()), + None => (target.clone(), String::new()), + }; + let length = lines + .find_map(|line| { + let (name, value) = line.split_once(':')?; + if name.eq_ignore_ascii_case("content-length") { + value.trim().parse::().ok() + } else { + None + } + }) + .unwrap_or(0); + if length > MAX_BODY { + return respond(&mut stream, 413, "text/plain", b"body too large"); + } + let mut body = raw[head_end..].to_vec(); + while body.len() < length { + let count = stream.read(&mut chunk)?; + if count == 0 { break; } + body.extend_from_slice(&chunk[..count]); } - let head = String::from_utf8_lossy(&request); - let mut parts = head.lines().next().unwrap_or("").split_whitespace(); - let method = parts.next().unwrap_or(""); - let path = parts.next().unwrap_or(""); - if method != "GET" { - return respond(&mut stream, 405, "text/plain", b"method not allowed"); - } - match path { - "/" | "/index.html" => respond( - &mut stream, - 200, - "text/html; charset=utf-8", - PAGE.as_bytes(), + let request = Request { + method, + path, + query, + body: String::from_utf8_lossy(&body).into_owned(), + }; + route(&mut stream, status, &request) +} + +fn route(stream: &mut TcpStream, status: &MiningStatus, request: &Request) -> io::Result<()> { + match (request.method.as_str(), request.path.as_str()) { + ("GET", "/") => html(stream, "Dashboard", &ui::dashboard_page("dashboard", true)), + ("GET", "/mining") => html( + stream, + "Mining overview", + &ui::dashboard_page("overview", true), ), - "/api/hardware" => { - let body = status.hardware_document().to_string(); - respond(&mut stream, 200, "application/json", body.as_bytes()) + ("GET", "/mining/hashboards") => { + let hw = status.hardware_document(); + let rows: Vec> = hw["chains"] + .as_array() + .map(|chains| { + chains + .iter() + .map(|chain| { + vec![ + chain["index"].to_string(), + chain["chip"].as_str().unwrap_or("-").to_string(), + chain["chips_found"].to_string(), + chain["eeprom"].to_string(), + chain["response_per_mille"].to_string(), + ] + }) + .collect() + }) + .unwrap_or_default(); + html( + stream, + "Hashboards", + &ui::table_page( + &["#", "chip", "chips", "eeprom", "response per mille"], + &rows, + ), + ) } - "/api/summary" => { - let body = status.summary_document().to_string(); - respond(&mut stream, 200, "application/json", body.as_bytes()) + ("GET", "/mining/power") => { + let hw = status.hardware_document(); + let point = &hw["operating_point"]; + html( + stream, + "Power supply", + &ui::kv_page(&[ + ( + "supply", + hw["psu"].as_str().unwrap_or("not identified").to_string(), + ), + ( + "voltage range (mV)", + format!( + "{} - {}", + hw["envelope"]["v_min_mv"], hw["envelope"]["v_max_mv"] + ), + ), + ( + "frequency range (MHz)", + format!( + "{} - {}", + hw["envelope"]["f_min_mhz"], hw["envelope"]["f_max_mhz"] + ), + ), + ( + "running at", + format!( + "{} mV / {} MHz", + point["voltage_mv"], point["frequency_mhz"] + ), + ), + ("target", hw["target"].as_str().unwrap_or("-").to_string()), + ]), + ) } - _ => respond(&mut stream, 404, "text/plain", b"not found"), + ("GET", "/mining/fans") => { + let hw = status.hardware_document(); + let rows: Vec> = hw["fan_zones"] + .as_array() + .map(|zones| { + zones + .iter() + .map(|zone| vec![zone["fan"].to_string(), zone["zones"].to_string()]) + .collect() + }) + .unwrap_or_default(); + html( + stream, + "Fans", + &ui::table_page(&["fan", "zones it cools"], &rows), + ) + } + ("GET", "/settings/system") => html(stream, "System", &ui::kv_page(&system_rows())), + ("GET", "/settings/drivers") => html(stream, "Drivers", &ui::kv_page(&driver_rows(status))), + ("GET", "/settings/security") => html(stream, "Security", &ui::kv_page(&security_rows())), + ("GET", "/settings/services") => html( + stream, + "Services", + &ui::table_page(&["service", "running"], &service_rows()), + ), + ("GET", "/settings/monitor") => { + html(stream, "Monitor", &ui::kv_page(&monitor_rows(status))) + } + ("GET", "/settings/logs") => { + let lines = request + .param_or("lines", "200") + .parse::() + .unwrap_or(200) + .min(2000); + let tail = tail_file(Path::new(LOG_FILE), lines); + html( + stream, + "Logs", + &format!( + "

{}

{}
", + ui::escape(LOG_FILE), + ui::escape(&tail) + ), + ) + } + ("GET", "/settings/files") => { + let path = request.param_or("path", "/"); + html(stream, "Files", &files_page(&path)) + } + ("GET", "/settings/terminal") => html(stream, "Terminal", &terminal_page()), + ("POST", "/api/terminal") => { + if !authorised(request) { + return respond(stream, 403, "text/plain", b"terminal requires a token"); + } + let command = request.param_or("cmd", ""); + let output = run_shell(&command); + respond(stream, 200, "text/plain; charset=utf-8", output.as_bytes()) + } + ("GET", "/api/hardware") => json_response(stream, &status.hardware_document()), + ("GET", "/api/summary") => json_response(stream, &status.summary_document()), + ("GET", "/api/dashboard") => { + let deck = request.param_or("deck", "dashboard"); + json_response(stream, &load_deck(&deck)) + } + ("PUT", "/api/dashboard") => { + let deck = request.param_or("deck", "dashboard"); + if request.param("reset").is_some() { + let doc = ui::default_deck(&deck); + let _ = save_deck(&deck, &doc); + return json_response(stream, &doc); + } + match ui::validate_deck(&request.body) { + Ok(doc) => match save_deck(&deck, &doc) { + Ok(()) => json_response(stream, &doc), + Err(error) => respond(stream, 500, "text/plain", error.as_bytes()), + }, + Err(reason) => respond(stream, 400, "text/plain", reason.as_bytes()), + } + } + ("GET", "/api/logs") => { + let lines = request + .param_or("lines", "200") + .parse::() + .unwrap_or(200) + .min(2000); + let tail = tail_file(Path::new(LOG_FILE), lines); + json_response( + stream, + &json!({"file": LOG_FILE, "lines": tail.lines().collect::>()}), + ) + } + ("GET", "/api/files") => { + let path = request.param_or("path", "/"); + json_response(stream, &files_document(&path)) + } + ("GET", "/api/file") => { + let path = request.param_or("path", ""); + match read_text(Path::new(&path)) { + Some(text) => respond(stream, 200, "text/plain; charset=utf-8", text.as_bytes()), + None => respond(stream, 404, "text/plain", b"not a readable text file"), + } + } + _ => respond(stream, 404, "text/plain", b"not found"), + } +} + +fn html(stream: &mut TcpStream, title: &str, body: &str) -> io::Result<()> { + let page = ui::page(path_for(title), title, body); + respond(stream, 200, "text/html; charset=utf-8", page.as_bytes()) +} + +fn path_for(title: &str) -> &'static str { + match title { + "Dashboard" => "/", + "Mining overview" => "/mining", + "Hashboards" => "/mining/hashboards", + "Power supply" => "/mining/power", + "Fans" => "/mining/fans", + "System" => "/settings/system", + "Drivers" => "/settings/drivers", + "Security" => "/settings/security", + "Services" => "/settings/services", + "Monitor" => "/settings/monitor", + "Logs" => "/settings/logs", + "Files" => "/settings/files", + "Terminal" => "/settings/terminal", + _ => "/", + } +} + +fn json_response(stream: &mut TcpStream, value: &Value) -> io::Result<()> { + respond( + stream, + 200, + "application/json", + value.to_string().as_bytes(), + ) +} + +// --- dashboard storage ------------------------------------------------------- + +fn deck_path(deck: &str) -> PathBuf { + let safe: String = deck + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .collect(); + Path::new(DECK_DIR).join(format!("{safe}.json")) +} + +fn load_deck(deck: &str) -> Value { + fs::read_to_string(deck_path(deck)) + .ok() + .and_then(|text| ui::validate_deck(&text).ok()) + .unwrap_or_else(|| ui::default_deck(deck)) +} + +fn save_deck(deck: &str, doc: &Value) -> Result<(), String> { + let path = deck_path(deck); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent) + .map_err(|e| format!("cannot create {}: {e}", parent.display()))?; + } + let text = serde_json::to_string_pretty(doc).map_err(|e| e.to_string())?; + fs::write(&path, text).map_err(|e| format!("cannot write {}: {e}", path.display())) +} + +// --- page data --------------------------------------------------------------- + +fn system_rows() -> Vec<(&'static str, String)> { + vec![ + ( + "hostname", + read_trim("/proc/sys/kernel/hostname").unwrap_or_else(|| "unknown".into()), + ), + ( + "kernel", + read_trim("/proc/sys/kernel/osrelease").unwrap_or_else(|| "unknown".into()), + ), + ( + "machine", + read_trim("/proc/device-tree/model").unwrap_or_else(|| "unknown".into()), + ), + ( + "uptime", + read_trim("/proc/uptime") + .and_then(|s| s.split_whitespace().next().map(|v| v.to_string())) + .map(|s| format!("{s} s")) + .unwrap_or_else(|| "unknown".into()), + ), + ( + "load", + read_trim("/proc/loadavg").unwrap_or_else(|| "unknown".into()), + ), + ( + "memory", + fs::read_to_string("/proc/meminfo") + .ok() + .and_then(|text| { + let total = text + .lines() + .find(|l| l.starts_with("MemTotal:"))? + .split_whitespace() + .nth(1)?; + let free = text + .lines() + .find(|l| l.starts_with("MemAvailable:"))? + .split_whitespace() + .nth(1)?; + Some(format!("{free} kB available of {total} kB")) + }) + .unwrap_or_else(|| "unknown".into()), + ), + ( + "api", + "JSON under /api is the interface of record".to_string(), + ), + ] +} + +fn driver_rows(status: &MiningStatus) -> Vec<(&'static str, String)> { + let hw = status.hardware_document(); + vec![ + ( + "chain driver", + hw["chip"].as_str().unwrap_or("not identified").to_string(), + ), + ( + "board profile", + hw["profile"] + .as_str() + .unwrap_or("not identified") + .to_string(), + ), + ( + "power supply", + hw["psu"].as_str().unwrap_or("not identified").to_string(), + ), + ( + "chains detected", + hw["chains"] + .as_array() + .map(|c| c.len()) + .unwrap_or(0) + .to_string(), + ), + ( + "chains active", + hw["active_chains"] + .as_array() + .map(|c| c.len()) + .unwrap_or(0) + .to_string(), + ), + ( + "stopped", + if hw["stopped"].is_null() { + "no".into() + } else { + hw["stopped"].to_string() + }, + ), + ] +} + +fn security_rows() -> Vec<(&'static str, String)> { + let users = fs::read_to_string("/etc/passwd") + .map(|text| { + text.lines() + .filter_map(|line| line.split(':').next()) + .collect::>() + .join(", ") + }) + .unwrap_or_else(|_| "unreadable".into()); + let keys = fs::read_to_string("/root/.ssh/authorized_keys") + .map(|text| { + text.lines() + .filter(|l| !l.trim().is_empty()) + .count() + .to_string() + }) + .unwrap_or_else(|_| "0".into()); + let dropbear = if running("dropbear") { + "running" + } else { + "not running" + }; + vec![ + ("accounts", users), + ("root ssh keys", keys), + ("dropbear", dropbear.to_string()), + ( + "web files and terminal", + if ui_token().is_some() { + "token configured".into() + } else { + "disabled until a token exists".into() + }, + ), + ] +} + +fn service_rows() -> Vec> { + let mut rows = Vec::new(); + if let Ok(entries) = fs::read_dir("/etc/init.d") { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + if let Some(service) = name.strip_prefix('S') { + let label = service + .trim_start_matches(|c: char| c.is_ascii_digit()) + .to_string(); + rows.push(vec![ + label.clone(), + if running(&label) { "yes" } else { "no" }.to_string(), + ]); + } + } + } + rows.sort(); + rows +} + +fn monitor_rows(status: &MiningStatus) -> Vec<(&'static str, String)> { + let hw = status.hardware_document(); + let point = &hw["operating_point"]; + vec![ + ( + "load", + read_trim("/proc/loadavg").unwrap_or_else(|| "-".into()), + ), + ("frequency", format!("{} MHz", hw["frequency_mhz"])), + ("voltage", format!("{} mV", point["voltage_mv"])), + ("target", hw["target"].as_str().unwrap_or("-").to_string()), + ( + "chains", + format!( + "{} active", + hw["active_chains"].as_array().map(|c| c.len()).unwrap_or(0) + ), + ), + ( + "memory", + read_trim("/proc/meminfo") + .and_then(|t| { + t.lines() + .find(|l| l.starts_with("MemAvailable:")) + .map(|l| l.trim().to_string()) + }) + .unwrap_or_else(|| "-".into()), + ), + ] +} + +fn files_page(path: &str) -> String { + let doc = files_document(path); + let mut rows = Vec::new(); + if let Some(entries) = doc["entries"].as_array() { + for entry in entries { + rows.push(vec![ + entry["name"].as_str().unwrap_or("-").to_string(), + entry["kind"].as_str().unwrap_or("-").to_string(), + entry["size"].to_string(), + ]); + } + } + format!( + "
read-only listing; individual text files are at /api/file?path=
{}", + ui::escape(path), + ui::table_page(&["name", "kind", "size"], &rows) + ) +} + +fn terminal_page() -> String { + if ui_token().is_none() { + return format!( + "

Terminal is disabled until a token exists at {}. Create one with \ + head -c 16 /dev/urandom | od -An -tx1 | tr -d ' \\n' > {}; chmod 600 {}.

", + TOKEN_FILE, TOKEN_FILE, TOKEN_FILE + ); + } + "
\ +commands run as root on this miner
ready
\ +" + .to_string() +} + +fn files_document(path: &str) -> Value { + let root = Path::new(path); + let mut entries = Vec::new(); + if let Ok(listing) = fs::read_dir(root) { + for entry in listing.flatten() { + let meta = entry.metadata().ok(); + entries.push(json!({ + "name": entry.file_name().to_string_lossy(), + "kind": if meta.as_ref().map(|m| m.is_dir()).unwrap_or(false) { "dir" } else { "file" }, + "size": meta.map(|m| m.len()).unwrap_or(0), + })); + } + } + entries.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); + json!({"path": path, "entries": entries}) +} + +fn read_text(path: &Path) -> Option { + let meta = fs::metadata(path).ok()?; + if !meta.is_file() || meta.len() > 256 * 1024 { + return None; + } + String::from_utf8(fs::read(path).ok()?).ok() +} + +fn tail_file(path: &Path, lines: usize) -> String { + let text = match read_text(path) { + Some(text) => text, + None => return String::from("no readable log yet"), + }; + let all: Vec<&str> = text.lines().collect(); + let start = all.len().saturating_sub(lines); + all[start..].join("\n") +} + +fn read_trim(path: &str) -> Option { + fs::read_to_string(path) + .ok() + .map(|text| text.trim().replace('\0', "")) +} + +fn running(name: &str) -> bool { + Command::new("pgrep") + .arg("-x") + .arg(name) + .output() + .map(|out| out.status.success()) + .unwrap_or(false) +} + +fn run_shell(command: &str) -> String { + if command.trim().is_empty() { + return "no command".to_string(); + } + match Command::new("/bin/sh").arg("-c").arg(command).output() { + Ok(out) => { + let mut text = String::from_utf8_lossy(&out.stdout).into_owned(); + text.push_str(&String::from_utf8_lossy(&out.stderr)); + if text.len() > 64 * 1024 { + text.truncate(64 * 1024); + } + text + } + Err(error) => format!("cannot run: {error}"), + } +} + +// --- access control ---------------------------------------------------------- + +fn ui_token() -> Option { + if let Ok(token) = std::env::var("ALKANE_UI_TOKEN") { + if !token.is_empty() { + return Some(token); + } + } + fs::read_to_string(TOKEN_FILE) + .ok() + .map(|t| t.trim().to_string()) + .filter(|t| !t.is_empty()) +} + +fn authorised(request: &Request) -> bool { + match (ui_token(), request.param("token")) { + (Some(expected), Some(given)) => given == expected, + _ => false, } } fn respond(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> io::Result<()> { let reason = match code { 200 => "OK", + 400 => "Bad Request", + 403 => "Forbidden", 404 => "Not Found", - 405 => "Method Not Allowed", + 413 => "Payload Too Large", 431 => "Request Header Fields Too Large", + 500 => "Internal Server Error", _ => "Error", }; let header = format!( @@ -145,104 +732,89 @@ fn respond(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) - #[cfg(test)] mod tests { use super::*; - use crate::detect::{ - ChainReport, ChipModel, EepromState, Envelope, HardwarePlan, OperatingPoint, - }; - use crate::management::HardwareSnapshot; - use std::net::TcpStream as Client; - fn status() -> Arc { - let status = MiningStatus::new(); - status.set_hardware(HardwareSnapshot { - plan: HardwarePlan { - profile: "s19jpro-bm1362-pic".into(), - chip: ChipModel::Bm1362, - chains: vec![ChainReport { - index: 0, - chip: ChipModel::Bm1362, - chips_found: 126, - eeprom: EepromState::Absent, - response_per_mille: Some(950), - }], - envelope: Envelope { - v_min_mv: 1100, - v_max_mv: 1500, - f_min_mhz: 300, - f_max_mhz: 700, - }, - operating_point: OperatingPoint { - voltage_mv: 1200, - frequency_mhz: 500, - confirmed: false, - }, - psu: "APW12".into(), - fan_zones: Vec::new(), - }, - active_chains: vec![0], - stopped: None, - frequency_mhz: 512, - target: "power:3000".into(), - }); - Arc::new(status) - } - - fn request(path: &str) -> String { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let address = listener.local_addr().expect("addr"); - let status = status(); + fn client(request: &str) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let status = Arc::new(MiningStatus::new()); let worker = std::thread::spawn(move || { - let (stream, _) = listener.accept().expect("accept"); - handle(stream, &status).expect("handle"); + let (stream, _) = listener.accept().unwrap(); + handle(stream, &status).unwrap(); }); - let mut client = Client::connect(address).expect("connect"); - client - .write_all(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes()) - .expect("write"); + let mut stream = TcpStream::connect(addr).unwrap(); + stream.write_all(request.as_bytes()).unwrap(); let mut reply = String::new(); - client.read_to_string(&mut reply).expect("read"); - worker.join().expect("join"); + stream.read_to_string(&mut reply).unwrap(); + worker.join().unwrap(); reply } #[test] - fn the_page_is_served_at_root() { - let reply = request("/"); + fn the_dashboard_serves_a_page_with_the_sidebar() { + let reply = client("GET / HTTP/1.1\r\nHost: x\r\n\r\n"); assert!(reply.starts_with("HTTP/1.1 200 OK")); + assert!(reply.contains("Power Supply")); + assert!(reply.contains("Terminal")); assert!(reply.contains("text/html")); - assert!(reply.contains("Alkane miner")); } #[test] - fn the_api_returns_the_hardware_document() { - let reply = request("/api/hardware"); - assert!(reply.starts_with("HTTP/1.1 200 OK")); - assert!(reply.contains("application/json")); - assert!(reply.contains("s19jpro-bm1362-pic")); - assert!(reply.contains("bm1362")); + fn every_page_answers() { + for path in [ + "/mining", + "/mining/hashboards", + "/mining/power", + "/mining/fans", + "/settings/system", + "/settings/drivers", + "/settings/security", + "/settings/services", + "/settings/monitor", + "/settings/logs", + "/settings/files", + "/settings/terminal", + ] { + let reply = client(&format!("GET {path} HTTP/1.1\r\nHost: x\r\n\r\n")); + assert!(reply.starts_with("HTTP/1.1 200 OK"), "{path}: {reply}"); + } } #[test] - fn unknown_paths_are_404() { - let reply = request("/nope"); - assert!(reply.starts_with("HTTP/1.1 404 Not Found")); + fn the_dashboard_api_serves_the_default_template() { + let reply = client("GET /api/dashboard?deck=bogus HTTP/1.1\r\nHost: x\r\n\r\n"); + let body = reply.split("\r\n\r\n").nth(1).unwrap_or(""); + let doc: Value = serde_json::from_str(body).unwrap_or_else(|_| json!({})); + assert_eq!(doc["version"], 1); + assert!(doc["blocks"] + .as_array() + .map(|b| !b.is_empty()) + .unwrap_or(false)); } #[test] - fn only_get_is_accepted() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); - let address = listener.local_addr().expect("addr"); - let status = status(); - let worker = std::thread::spawn(move || { - let (stream, _) = listener.accept().expect("accept"); - handle(stream, &status).expect("handle"); - }); - let mut client = Client::connect(address).expect("connect"); - client - .write_all(b"POST / HTTP/1.1\r\nHost: miner\r\nContent-Length: 0\r\n\r\n") - .expect("write"); - let mut reply = String::new(); - client.read_to_string(&mut reply).expect("read"); - worker.join().expect("join"); - assert!(reply.starts_with("HTTP/1.1 405 Method Not Allowed")); + fn the_dashboard_api_rejects_a_bad_document() { + let body = "not json"; + let reply = client(&format!( + "PUT /api/dashboard?deck=test HTTP/1.1\r\nHost: x\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + )); + assert!(reply.starts_with("HTTP/1.1 400"), "{reply}"); + } + + #[test] + fn the_terminal_is_forbidden_without_a_token() { + std::env::remove_var("ALKANE_UI_TOKEN"); + let reply = + client("POST /api/terminal?cmd=id HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\n\r\n"); + assert!(reply.starts_with("HTTP/1.1 403"), "{reply}"); + } + + #[test] + fn the_api_still_serves_hardware_and_summary() { + for path in ["/api/hardware", "/api/summary"] { + let reply = client(&format!("GET {path} HTTP/1.1\r\nHost: x\r\n\r\n")); + assert!(reply.starts_with("HTTP/1.1 200 OK"), "{path}"); + assert!(reply.contains("application/json")); + } } }