//! Restore an aftermarket-firmware miner to stock (round 12 #8a). //! //! All three supported aftermarket firmwares ship a free, self-restoring revert //! (the stock image is retained on-device at install time; no image is uploaded): //! - VNish: POST /api/v1/unlock -> bearer -> POST /api/v1/firmware/remove //! - LuxOS: luxminer :4028 {"command":"logon"} -> SessionID -> //! {"command":"uninstallluxos","parameter":""} //! - Braiins: SSH `uninstall.sh` (re-flashes the on-NAND stock backup) //! //! DESTRUCTIVE: this removes the running aftermarket firmware and reboots the //! miner to stock. It is gated behind a typed confirmation in the UI and runs on //! a background thread so the reboot latency never blocks the event loop. The //! flows are documented + live-confirmed in the miner-firmware wiki //! (40-boot-os-and-build/firmware-install-remove-api and siblings). use std::io::{Read, Write}; use std::net::{SocketAddr, TcpStream}; use std::process::Command; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, channel}; use std::time::Duration; use crate::scan::fake_scan_enabled; pub enum RestoreMsg { Started, Result { ip: String, ok: bool, detail: String }, Done, } pub struct RestoreHandle { pub rx: Receiver, // The worker honours cancellation between miners (see `tc` below); a UI stop // control is not wired yet, so the handle-side trigger is kept for when it is. #[allow(dead_code)] cancel: Arc, } impl RestoreHandle { #[allow(dead_code)] pub fn stop(&self) { self.cancel.store(true, Ordering::Relaxed); } } /// One miner to restore: its IP plus the firmware family ("VNish"/"LuxOS"/ /// "Braiins") that selects the revert flow. pub struct RestoreTarget { pub ip: String, pub firmware: String, } /// Start restoring the given miners to stock on a background thread. `vnish_pass` /// is the VNish web password; `ssh_user`/`ssh_pass` drive the Braiins SSH revert. pub fn start_restore( targets: Vec, vnish_pass: String, ssh_user: String, ssh_pass: String, ) -> RestoreHandle { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); if fake_scan_enabled() { // Offline demo: report each target as restored without touching anything. let _ = tx.send(RestoreMsg::Started); for t in targets { let _ = tx.send(RestoreMsg::Result { ip: t.ip, ok: true, detail: "restored to stock (demo)".into(), }); } let _ = tx.send(RestoreMsg::Done); return RestoreHandle { rx, cancel }; } let tc = cancel.clone(); let err_tx = tx.clone(); let spawned = std::thread::Builder::new() .name("restore-stock".into()) .spawn(move || { let _ = tx.send(RestoreMsg::Started); for t in targets { if tc.load(Ordering::Relaxed) { break; } let (ok, detail) = restore_one(&t, &vnish_pass, &ssh_user, &ssh_pass); if tx.send(RestoreMsg::Result { ip: t.ip, ok, detail }).is_err() { return; } } let _ = tx.send(RestoreMsg::Done); }); if spawned.is_err() { // Never leave the restore subsystem wedged (round 18 #12): if the worker // thread can't start, emit a failure + Done so the drain clears the handle. let _ = err_tx.send(RestoreMsg::Result { ip: String::new(), ok: false, detail: "could not start the restore worker thread".into(), }); let _ = err_tx.send(RestoreMsg::Done); } RestoreHandle { rx, cancel } } fn restore_one(t: &RestoreTarget, vnish_pass: &str, ssh_user: &str, ssh_pass: &str) -> (bool, String) { let fw = t.firmware.to_ascii_lowercase(); if fw.contains("vnish") || fw.contains("wildrose") || fw.contains("anthill") { restore_vnish(&t.ip, vnish_pass) } else if fw.contains("lux") { restore_luxos(&t.ip) } else if fw.contains("braiins") || fw.contains("bos") { restore_braiins(&t.ip, ssh_user, ssh_pass) } else { (false, format!("no restore-to-stock path for firmware '{}'", t.firmware)) } } /// VNish: unlock -> bearer -> firmware/remove (self-restores + reboots ~3 s). fn restore_vnish(ip: &str, pass: &str) -> (bool, String) { // serde-encode the body so a password with a quote/backslash can't break the // JSON, and send it via stdin (-d @-) so the password never appears on curl's // argv / the process list (round 18 #12). let body = serde_json::json!({ "pw": pass }).to_string(); let unlock = match curl( &[ "-s", "--connect-timeout", "5", "--max-time", "9", "-X", "POST", "-H", "Content-Type: application/json", "-d", "@-", &format!("http://{ip}/api/v1/unlock"), ], Some(body.as_bytes()), ) { Ok(s) => s, Err(e) => return (false, format!("unlock request failed: {e}")), }; let token = serde_json::from_str::(&unlock) .ok() .and_then(|v| v.get("token").and_then(|t| t.as_str()).map(str::to_string)) .filter(|t| !t.is_empty()); let Some(token) = token else { return (false, "VNish unlock rejected (wrong web password?)".into()); }; match curl( &[ "-s", "--connect-timeout", "5", "--max-time", "12", "-X", "POST", "-H", &format!("Authorization: Bearer {token}"), &format!("http://{ip}/api/v1/firmware/remove"), ], None, ) { // The miner reverts + reboots after ~3 s; the response is {"after":N}. Ok(resp) if resp.contains("after") => (true, "reverting to stock (~3 s)".into()), Ok(resp) => (false, format!("firmware/remove returned: {}", resp.trim())), Err(e) => (false, format!("firmware/remove failed: {e}")), } } /// LuxOS: credential-free luxminer session, then uninstallluxos (reboots to stock). fn restore_luxos(ip: &str) -> (bool, String) { let logon = match lux_rpc(ip, "{\"command\":\"logon\"}") { Ok(s) => s, Err(e) => return (false, format!("logon failed: {e}")), }; let session = serde_json::from_str::(&logon) .ok() .and_then(|v| { v.pointer("/SESSION/0/SessionID") .or_else(|| v.pointer("/Session/0/SessionID")) .and_then(|s| s.as_str()) .map(str::to_string) }); let Some(session) = session.filter(|s| !s.is_empty()) else { return (false, format!("no SessionID in logon response: {}", logon.trim())); }; // serde-encode so the miner-supplied SessionID can't break or inject into the // JSON-RPC command (round 18 #12). let cmd = serde_json::json!({ "command": "uninstallluxos", "parameter": session }).to_string(); match lux_rpc(ip, &cmd) { // Code 350 "Uninstalling LuxOS"; the miner reboots + reverts in background. Ok(resp) if resp.contains("350") || resp.to_lowercase().contains("uninstall") => { (true, "uninstalling LuxOS (reboots to stock)".into()) } // The miner reboots as it reverts, so the reply is often dropped/empty // after the command is accepted. The logon above already proved the miner // was reachable, so an empty reply or a dropped connection here is the // expected reboot, not a failure (round 18 #12). Ok(resp) if resp.trim().is_empty() => { (true, "uninstall accepted (miner rebooting to stock)".into()) } Ok(resp) => (false, format!("uninstallluxos returned: {}", resp.trim())), Err(e) if ["closed", "reset", "timed out", "broken pipe", "eof"] .iter() .any(|m| e.to_lowercase().contains(m)) => { (true, "RPC dropped (miner rebooting to stock)".into()) } Err(e) => (false, format!("uninstallluxos failed: {e}")), } } /// Braiins: SSH `uninstall.sh` (re-flashes the retained on-NAND stock backup). fn restore_braiins(ip: &str, user: &str, pass: &str) -> (bool, String) { if pass.is_empty() { return (false, "Braiins restore needs an SSH password (set the SSH login)".into()); } let target = format!("{user}@{ip}"); // sshpass reads the password from $SSHPASS (-e) rather than argv (-p), so it // never shows up in the process list (round 18 #12). Host-key checking is // deliberately disabled: these are LAN miners whose SSH host key changes on // every reflash, so pinning it would break the very revert this performs. // BatchMode stops any interactive prompt from hanging out the 60 s cap. let mut cmd = Command::new("sshpass"); cmd.env("SSHPASS", pass); cmd.arg("-e").arg("ssh"); cmd.args([ "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-o", "BatchMode=yes", "-o", "ConnectTimeout=8", &target, "uninstall.sh || /sbin/uninstall.sh", ]); match run_with_timeout(cmd, Duration::from_secs(60), None) { Ok(out) => classify_braiins( &String::from_utf8_lossy(&out.stdout), &String::from_utf8_lossy(&out.stderr), out.code, out.timed_out, ), Err(e) => { if e.contains("closed") || e.contains("reset") || e.contains("timed out") { (true, "SSH dropped (miner likely rebooting to stock)".into()) } else { (false, format!("SSH uninstall failed: {e}")) } } } } /// Decide a Braiins `uninstall.sh` outcome from its captured output. The critical /// rule (round 18 #12): an SSH auth/connection failure -- which writes its /// diagnostic to stderr, leaves stdout empty, and exits non-zero -- must be /// reported as a FAILURE, never a false success. A dropped connection or a /// timeout after the command started is the expected signature of the reboot. fn classify_braiins(stdout: &str, stderr: &str, code: Option, timed_out: bool) -> (bool, String) { let err = stderr.to_lowercase(); // ssh's own connection/auth failures (exit 255) never reach the remote command. let conn_fail = [ "permission denied", "connection refused", "could not resolve", "no route to host", "connection timed out", "operation timed out", "host key verification failed", "before authentication", ] .iter() .any(|m| err.contains(m)); if conn_fail { let why = stderr.lines().map(str::trim).rfind(|l| !l.is_empty()); return (false, format!("SSH failed: {}", why.unwrap_or("connection/auth error"))); } let out = stdout.to_lowercase(); if out.contains("not found") || out.contains("no such") || err.contains("not found") { return (false, "uninstall.sh not found on the miner".into()); } match code { Some(0) => (true, "ran uninstall.sh (reverts to stock + reboots)".into()), None => (true, "SSH dropped (miner likely rebooting to stock)".into()), _ if timed_out => (true, "SSH timed out (miner likely rebooting to stock)".into()), Some(c) => (false, format!("uninstall.sh exited {c}: {}", stderr.trim())), } } /// One luxminer :4028 request/response (line-framed, socket closes after reply). fn lux_rpc(ip: &str, payload: &str) -> Result { let addr: SocketAddr = format!("{ip}:4028").parse().map_err(|e| format!("bad addr: {e}"))?; let t = Duration::from_secs(8); let mut s = TcpStream::connect_timeout(&addr, t).map_err(|e| e.to_string())?; s.set_read_timeout(Some(t)).ok(); s.set_write_timeout(Some(t)).ok(); s.write_all(payload.as_bytes()).map_err(|e| e.to_string())?; let mut buf = Vec::new(); let mut chunk = [0u8; 4096]; loop { match s.read(&mut chunk) { Ok(0) => break, Ok(n) => { buf.extend_from_slice(&chunk[..n]); if buf.len() > 1 << 16 { break; } } Err(_) => break, } } Ok(String::from_utf8_lossy(&buf).trim_matches('\u{0}').to_string()) } /// The captured result of a timed subprocess run. struct CmdOutput { /// The process exit code, or `None` if it was killed / dropped / timed out. code: Option, stdout: Vec, stderr: Vec, timed_out: bool, } /// curl with a wall-clock cap. Errors only when the run produced no output and /// timed out (a black-holed host); otherwise returns stdout even on a non-zero /// exit (curl prints useful bodies/status on failures). fn curl(args: &[&str], stdin_data: Option<&[u8]>) -> Result { let mut cmd = Command::new("curl"); cmd.args(args); let out = run_with_timeout(cmd, Duration::from_secs(15), stdin_data)?; if out.timed_out && out.stdout.is_empty() { return Err("timed out".into()); } Ok(String::from_utf8_lossy(&out.stdout).into_owned()) } /// Run a command with a hard wall-clock timeout, capturing stdout, stderr, and /// the exit code. Both pipes are drained on their own threads so a child that /// writes a lot to stderr can never deadlock against a full pipe (round 18 #12). /// `stdin_data`, when set, is written to the child's stdin and the pipe closed /// (used to feed a request body without putting a secret on argv). fn run_with_timeout( mut cmd: Command, timeout: Duration, stdin_data: Option<&[u8]>, ) -> Result { cmd.stdout(std::process::Stdio::piped()); cmd.stderr(std::process::Stdio::piped()); if stdin_data.is_some() { cmd.stdin(std::process::Stdio::piped()); } let mut child = cmd.spawn().map_err(|e| format!("spawn: {e}"))?; if let Some(data) = stdin_data { if let Some(mut si) = child.stdin.take() { let _ = si.write_all(data); } // dropping `si` closes the pipe } let mut stdout = child.stdout.take().ok_or("no stdout")?; let mut stderr = child.stderr.take().ok_or("no stderr")?; let out_reader = std::thread::spawn(move || { let mut b = Vec::new(); let _ = stdout.read_to_end(&mut b); b }); let err_reader = std::thread::spawn(move || { let mut b = Vec::new(); let _ = stderr.read_to_end(&mut b); b }); let start = std::time::Instant::now(); let mut timed_out = false; let status = loop { match child.try_wait().map_err(|e| e.to_string())? { Some(s) => break Some(s), None => { if start.elapsed() >= timeout { let _ = child.kill(); let _ = child.wait(); // reap so we never leave a zombie timed_out = true; break None; } std::thread::sleep(Duration::from_millis(50)); } } }; Ok(CmdOutput { code: status.and_then(|s| s.code()), stdout: out_reader.join().unwrap_or_default(), stderr: err_reader.join().unwrap_or_default(), timed_out, }) } #[cfg(test)] mod tests { use super::*; #[test] fn braiins_auth_or_connection_failure_is_not_a_false_success() { // The critical regression guard (round 18 #12): a wrong password or an // unreachable miner writes to stderr, leaves stdout empty, and exits // non-zero -- it must report failure, never "restored". let (ok, msg) = classify_braiins("", "Permission denied, please try again.", Some(255), false); assert!(!ok, "wrong password must not report success"); assert!(msg.to_lowercase().contains("ssh failed"), "{msg}"); let (ok, _) = classify_braiins("", "ssh: connect to host 10.0.0.9 port 22: Connection refused", Some(255), false); assert!(!ok, "unreachable miner must not report success"); let (ok, _) = classify_braiins("", "ssh: Could not resolve hostname miner: Name or service not known", Some(255), false); assert!(!ok, "unresolvable host must not report success"); // Genuine outcomes. let (ok, _) = classify_braiins("uninstalling...\n", "", Some(0), false); assert!(ok, "clean exit 0 is success"); let (ok, _) = classify_braiins("", "Connection to 10.0.0.5 closed by remote host.", None, false); assert!(ok, "connection dropped mid-command (reboot) is success"); let (ok, _) = classify_braiins("", "", None, true); assert!(ok, "timeout after the command started (reboot) is success"); let (ok, _) = classify_braiins("bash: uninstall.sh: command not found\n", "", Some(127), false); assert!(!ok, "missing uninstall.sh is a failure"); } #[test] fn firmware_selects_the_right_flow() { // The dispatcher only recognises the three revertible aftermarket // families; anything else has no restore path. let mk = |fw: &str| RestoreTarget { ip: "0.0.0.0".into(), firmware: fw.into() }; // Unknown firmware is rejected cleanly (no network attempt in the branch). let (ok, detail) = restore_one(&mk("Stock"), "", "", ""); assert!(!ok); assert!(detail.contains("no restore-to-stock path"), "{detail}"); } }