diff --git a/src/lib.rs b/src/lib.rs index 2cd4609..fb91ca7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,6 +27,7 @@ pub mod stratum_v2_session; pub mod stratum_wire; pub mod stratum_work; pub mod tuning; +pub mod web; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Vendor { diff --git a/src/management.rs b/src/management.rs index 9563ea4..ba404a0 100644 --- a/src/management.rs +++ b/src/management.rs @@ -60,6 +60,16 @@ impl MiningStatus { } } + /// The `hardware` document, for the on-box UI and local clients. + pub fn hardware_document(&self) -> Value { + hardware_json(self.hardware()) + } + + /// The `summary` document, for the on-box UI and local clients. + pub fn summary_document(&self) -> Value { + self.response("summary") + } + fn hardware(&self) -> Option { self.hardware.lock().ok().and_then(|slot| slot.clone()) } diff --git a/src/web.rs b/src/web.rs new file mode 100644 index 0000000..7e9ac54 --- /dev/null +++ b/src/web.rs @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: MIT +//! On-box web UI. +//! +//! A small HTTP surface served by the miner itself: a single page that polls the JSON API, plus +//! the API routes it uses. The API stays the interface of record; the page is a convenience, so a +//! client that only speaks JSON loses nothing. +//! +//! No framework and no dependency: the request parser is bounded, only `GET` is accepted, and every +//! response closes the connection. + +use crate::management::MiningStatus; +use std::io::{self, Read, Write}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::sync::Arc; +use std::time::Duration; + +const MAX_REQUEST_BYTES: usize = 2048; +const CLIENT_TIMEOUT: Duration = Duration::from_millis(500); + +const PAGE: &str = r#" + + + +Alkane miner + + + +

Alkane miner

+
loading
+ + + +"#; + +/// Bind and serve until the listener fails. +pub fn serve(bind: SocketAddr, status: Arc) -> io::Result<()> { + let listener = TcpListener::bind(bind)?; + serve_listener(listener, status) +} + +/// Serve on an already-bound listener. +pub fn serve_listener(listener: TcpListener, status: Arc) -> io::Result<()> { + 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); + }); + } + Ok(()) +} + +/// 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 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"); + } + if request.windows(4).any(|window| window == b"\r\n\r\n") { + break; + } + } + 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(), + ), + "/api/hardware" => { + let body = status.hardware_document().to_string(); + respond(&mut stream, 200, "application/json", body.as_bytes()) + } + "/api/summary" => { + let body = status.summary_document().to_string(); + respond(&mut stream, 200, "application/json", body.as_bytes()) + } + _ => respond(&mut stream, 404, "text/plain", b"not found"), + } +} + +fn respond(stream: &mut TcpStream, code: u16, content_type: &str, body: &[u8]) -> io::Result<()> { + let reason = match code { + 200 => "OK", + 404 => "Not Found", + 405 => "Method Not Allowed", + 431 => "Request Header Fields Too Large", + _ => "Error", + }; + let header = format!( + "HTTP/1.1 {code} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n", + body.len() + ); + stream.write_all(header.as_bytes())?; + stream.write_all(body)?; + stream.flush() +} + +#[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(); + 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(format!("GET {path} HTTP/1.1\r\nHost: miner\r\n\r\n").as_bytes()) + .expect("write"); + let mut reply = String::new(); + client.read_to_string(&mut reply).expect("read"); + worker.join().expect("join"); + reply + } + + #[test] + fn the_page_is_served_at_root() { + let reply = request("/"); + assert!(reply.starts_with("HTTP/1.1 200 OK")); + 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")); + } + + #[test] + fn unknown_paths_are_404() { + let reply = request("/nope"); + assert!(reply.starts_with("HTTP/1.1 404 Not Found")); + } + + #[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")); + } +}