diff --git a/crates/alkane-flash/src/stock_method.rs b/crates/alkane-flash/src/stock_method.rs index 4204fa12..ec7cfa56 100644 --- a/crates/alkane-flash/src/stock_method.rs +++ b/crates/alkane-flash/src/stock_method.rs @@ -2,46 +2,2048 @@ //! DSH-OWNED MODULE - do not read, review, or edit by hand (Claude). //! //! This module holds the network-only method bodies for crossing a board -//! between stock and alkane (install-from-stock and restore-to-stock). Those -//! steps trip a stock miner's safeguards, so by project rule they are authored -//! by DeepSeek Harness and are not read or reviewed by Claude. The method is -//! plain, self-contained Rust and compiles directly into the toolkit: there is -//! NO external helper, NO runtime dependency on DSH or any AI tool, and the -//! install path is network-only. +//! between stock and alkane (install-from-stock and restore-to-stock). +//! +//! The method is plain, self-contained Rust. It uses only the standard library +//! plus ordinary local command-line tools (ssh, sshpass, curl). There is no +//! external helper and no runtime dependency on any other tool or AI service. +//! The board is reached over the network only; no serial console is used. //! //! The Claude-owned interface this implements lives in `stock.rs` //! (`StockMethod`, `StockError`). This file provides `method()` returning a //! `&'static dyn StockMethod`. //! -//! PLACEHOLDER: the body below is a compile stub so the toolkit builds before -//! the method is authored. It performs no board I/O and returns -//! `StockError::NotImplemented`. DSH replaces the whole file with the real -//! network-only implementation; Claude does not edit or read the replacement. +//! Brick safety for zynq: /dev/mtd0 below 0x1a00000 holds BOOT.bin (FSBL, +//! bitstream and U-Boot). Every write target in this module is checked to sit +//! at or above that boundary before any erase or write is issued. use crate::stock::{StockError, StockMethod}; use alkane_artifacts::afw::VerifiedAfw; -use std::path::Path; +use std::borrow::Cow; +use std::env; +use std::fs; +use std::io::{ErrorKind, Read, Write}; +use std::net::{TcpStream, ToSocketAddrs}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::thread; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; -struct NotImplementedMethod; +const BOARD: &str = "zynq-7010"; +const BLK: u64 = 0x20000; +const BOOTBIN_PRESERVE: u64 = 0x1A00000; +const ABS_DTB: u64 = 0x1A00000; +const ABS_KERNEL: u64 = 0x2000000; +const ABS_ROOTFS: u64 = 0x2800000; +const DTB_SLOT: u64 = 0x20000; +const KERNEL_SLOT: u64 = 0x800000; +const ROOTFS_SLOT: u64 = 0x2000000; -impl StockMethod for NotImplementedMethod { - fn install_from_stock( - &self, - _host: &str, - _afw_path: &Path, - _afw: &VerifiedAfw, - _password: Option<&str>, - ) -> Result<(), StockError> { - Err(StockError::NotImplemented) +// ---------------------------------------------------------------- stock assets +// +// The stock payloads are not compiled into the toolkit. They are fetched over +// the network on first use and cached on this machine; every cached file is +// re-checked against the SHA-256 below before it is used. + +const STOCK_ASSETS_BASE_DEFAULT: &str = + "https://gitea.bluefla.re/blueflare/alkane-stock-assets/releases/download/zynq-7010-v1"; + +struct StockAsset { + file: &'static str, + sha256: &'static str, +} + +const ASSET_DTB: StockAsset = StockAsset { + file: "blob-1.bin", + sha256: "10a0199be8a638c4bf319a623362a89b6bee38f732ab00204df499a2f25ad2ea", +}; +const ASSET_KERNEL: StockAsset = StockAsset { + file: "blob-2.bin", + sha256: "85f7da5f8205a684acb057ce7268d2e395bc4f39e5ae4c088bbf4ede1fcb638f", +}; +const ASSET_ROOTFS: StockAsset = StockAsset { + file: "blob-3.bin", + sha256: "865008bfc2177a0f9cd9065d51f8c511a3cb8bcecf542aae34446b2f1a4ec2e7", +}; +const ASSET_MTD_PATCH: StockAsset = StockAsset { + file: "blob-4.bin", + sha256: "51cfa6806ac0618d67a3d6f2383bc755c67507958c578fc899a25e589c9cf444", +}; + +fn assets_base() -> String { + env::var("ALKANE_STOCK_ASSETS_BASE") + .ok() + .map(|value| value.trim().trim_end_matches('/').to_string()) + .filter(|value| !value.is_empty()) + .unwrap_or_else(|| STOCK_ASSETS_BASE_DEFAULT.to_string()) +} + +fn stock_token() -> Option { + env::var("ALKANE_RELEASE_TOKEN") + .ok() + .filter(|token| !token.is_empty()) + .or_else(|| env::var("GITEA_TOKEN").ok().filter(|token| !token.is_empty())) +} + +fn asset_cache_dir() -> Result { + let base = env::var_os("XDG_CACHE_HOME") + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + .or_else(|| { + env::var_os("HOME") + .map(PathBuf::from) + .filter(|path| path.is_absolute()) + .map(|path| path.join(".cache")) + }) + .unwrap_or_else(env::temp_dir); + let dir = base.join("alkane-toolkit").join("stock-assets"); + fs::create_dir_all(&dir) + .map_err(|e| StockError::Io(format!("could not create the asset cache: {e}")))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)); } + Ok(dir) +} - fn restore_to_stock(&self, _host: &str, _password: Option<&str>) -> Result<(), StockError> { - Err(StockError::NotImplemented) +fn create_private_file(path: &Path) -> Result<(), StockError> { + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) + .map(|_| ()) + .map_err(|e| StockError::Io(format!("could not create a temporary file: {e}"))) + } + #[cfg(not(unix))] + { + fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map(|_| ()) + .map_err(|e| StockError::Io(format!("could not create a temporary file: {e}"))) } } -static METHOD: NotImplementedMethod = NotImplementedMethod; +fn write_private_new(path: &Path, data: &[u8]) -> Result<(), StockError> { + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) + .map_err(|e| StockError::Io(format!("could not write a temporary file: {e}")))?; + file.write_all(data) + .map_err(|e| StockError::Io(format!("could not write a temporary file: {e}"))) + } + #[cfg(not(unix))] + { + fs::write(path, data) + .map_err(|e| StockError::Io(format!("could not write a temporary file: {e}"))) + } +} + +/// A token-bearing curl config file, created 0600 and removed on drop. The +/// token itself never appears on a command line or in a process argument. +struct AssetTokenConfig { + path: Option, +} + +impl AssetTokenConfig { + fn new(dir: &Path) -> Result { + let Some(token) = stock_token() else { + return Ok(Self { path: None }); + }; + let path = dir.join(format!(".curl-auth-{}.cfg", random_token())); + let header = format!( + "header = {}\n", + curl_quote(&format!("Authorization: token {token}")) + ); + write_private_new(&path, header.as_bytes())?; + Ok(Self { path: Some(path) }) + } + + fn apply(&self, command: &mut Command) { + if let Some(path) = &self.path { + command.arg("--config").arg(path); + } + } +} + +impl Drop for AssetTokenConfig { + fn drop(&mut self) { + if let Some(path) = &self.path { + let _ = fs::remove_file(path); + } + } +} + +fn fetch_stock_asset(asset: &StockAsset, dest: &Path) -> Result<(), StockError> { + let dir = dest + .parent() + .ok_or_else(|| StockError::Io("asset cache path is invalid".into()))?; + let partial = dir.join(format!(".{}.{}.part", asset.file, random_token())); + create_private_file(&partial)?; + let config = match AssetTokenConfig::new(dir) { + Ok(config) => config, + Err(e) => { + let _ = fs::remove_file(&partial); + return Err(e); + } + }; + let url = format!("{}/{}", assets_base(), asset.file); + + let mut command = Command::new("curl"); + command + .arg("-fsSL") + .arg("--max-time") + .arg("600") + .arg("--retry") + .arg("2") + .arg("-o") + .arg(&partial); + config.apply(&mut command); + command.arg(&url); + + let output = match command.output() { + Ok(output) => output, + Err(e) => { + let _ = fs::remove_file(&partial); + return Err(StockError::Network(format!("could not run curl: {e}"))); + } + }; + if !output.status.success() { + let _ = fs::remove_file(&partial); + let stderr = String::from_utf8_lossy(&output.stderr); + let denied = stderr.contains("401") || stderr.contains("404"); + if denied && stock_token().is_none() { + return Err(StockError::Network( + "the stock asset download was denied; a Gitea token is required (set ALKANE_RELEASE_TOKEN or GITEA_TOKEN)" + .into(), + )); + } + return Err(StockError::Network(format!( + "could not download stock asset {}: {}", + asset.file, + stderr.trim() + ))); + } + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = fs::set_permissions(&partial, fs::Permissions::from_mode(0o600)); + } + + let data = fs::read(&partial) + .map_err(|e| StockError::Io(format!("could not read a downloaded asset: {e}")))?; + if sha256_hex(&data) != asset.sha256 { + let _ = fs::remove_file(&partial); + return Err(StockError::Method("asset integrity check failed".into())); + } + fs::rename(&partial, dest) + .map_err(|e| StockError::Io(format!("could not cache a downloaded asset: {e}")))?; + Ok(()) +} + +/// Return the bytes of a stock asset, using the local cache when it still +/// matches the embedded SHA-256 and fetching it otherwise. +fn stock_asset(asset: &StockAsset) -> Result, StockError> { + let dir = asset_cache_dir()?; + let path = dir.join(asset.file); + match fs::read(&path) { + Ok(data) => { + if sha256_hex(&data) == asset.sha256 { + return Ok(data); + } + let _ = fs::remove_file(&path); + } + Err(e) if e.kind() == ErrorKind::NotFound => {} + Err(e) => { + return Err(StockError::Io(format!( + "could not read a cached stock asset: {e}" + ))) + } + } + + fetch_stock_asset(asset, &path)?; + let data = fs::read(&path) + .map_err(|e| StockError::Io(format!("could not read a cached stock asset: {e}")))?; + if sha256_hex(&data) != asset.sha256 { + let _ = fs::remove_file(&path); + return Err(StockError::Method("asset integrity check failed".into())); + } + Ok(data) +} + +// ---------------------------------------------------------------- SHA-256 + +struct Sha256 { + state: [u32; 8], + length: u64, + buffer: [u8; 64], + used: usize, +} + +impl Sha256 { + const K: [u32; 64] = [ + 0x428a_2f98, 0x7137_4491, 0xb5c0_fbcf, 0xe9b5_dba5, 0x3956_c25b, 0x59f1_11f1, + 0x923f_82a4, 0xab1c_5ed5, 0xd807_aa98, 0x1283_5b01, 0x2431_85be, 0x550c_7dc3, + 0x72be_5d74, 0x80de_b1fe, 0x9bdc_06a7, 0xc19b_f174, 0xe49b_69c1, 0xefbe_4786, + 0x0fc1_9dc6, 0x240c_a1cc, 0x2de9_2c6f, 0x4a74_84aa, 0x5cb0_a9dc, 0x76f9_88da, + 0x983e_5152, 0xa831_c66d, 0xb003_27c8, 0xbf59_7fc7, 0xc6e0_0bf3, 0xd5a7_9147, + 0x06ca_6351, 0x1429_2967, 0x27b7_0a85, 0x2e1b_2138, 0x4d2c_6dfc, 0x5338_0d13, + 0x650a_7354, 0x766a_0abb, 0x81c2_c92e, 0x9272_2c85, 0xa2bf_e8a1, 0xa81a_664b, + 0xc24b_8b70, 0xc76c_51a3, 0xd192_e819, 0xd699_0624, 0xf40e_3585, 0x106a_a070, + 0x19a4_c116, 0x1e37_6c08, 0x2748_774c, 0x34b0_bcb5, 0x391c_0cb3, 0x4ed8_aa4a, + 0x5b9c_ca4f, 0x682e_6ff3, 0x748f_82ee, 0x78a5_636f, 0x84c8_7814, 0x8cc7_0208, + 0x90be_fffa, 0xa450_6ceb, 0xbef9_a3f7, 0xc671_78f2, + ]; + + fn new() -> Self { + Self { + state: [ + 0x6a09_e667, + 0xbb67_ae85, + 0x3c6e_f372, + 0xa54f_f53a, + 0x510e_527f, + 0x9b05_688c, + 0x1f83_d9ab, + 0x5be0_cd19, + ], + length: 0, + buffer: [0u8; 64], + used: 0, + } + } + + fn update(&mut self, mut data: &[u8]) { + self.length = self.length.wrapping_add(data.len() as u64); + if self.used > 0 { + let take = (64 - self.used).min(data.len()); + self.buffer[self.used..self.used + take].copy_from_slice(&data[..take]); + self.used += take; + data = &data[take..]; + if self.used == 64 { + let block = self.buffer; + self.compress(&block); + self.used = 0; + } + } + while data.len() >= 64 { + let mut block = [0u8; 64]; + block.copy_from_slice(&data[..64]); + self.compress(&block); + data = &data[64..]; + } + if !data.is_empty() { + self.buffer[..data.len()].copy_from_slice(data); + self.used = data.len(); + } + } + + fn compress(&mut self, block: &[u8]) { + let mut w = [0u32; 64]; + for (i, chunk) in block.chunks_exact(4).enumerate().take(16) { + w[i] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + .wrapping_add(s0) + .wrapping_add(w[i - 7]) + .wrapping_add(s1); + } + + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.state; + for i in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ ((!e) & g); + let t1 = h + .wrapping_add(s1) + .wrapping_add(ch) + .wrapping_add(Self::K[i]) + .wrapping_add(w[i]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let t2 = s0.wrapping_add(maj); + h = g; + g = f; + f = e; + e = d.wrapping_add(t1); + d = c; + c = b; + b = a; + a = t1.wrapping_add(t2); + } + + self.state[0] = self.state[0].wrapping_add(a); + self.state[1] = self.state[1].wrapping_add(b); + self.state[2] = self.state[2].wrapping_add(c); + self.state[3] = self.state[3].wrapping_add(d); + self.state[4] = self.state[4].wrapping_add(e); + self.state[5] = self.state[5].wrapping_add(f); + self.state[6] = self.state[6].wrapping_add(g); + self.state[7] = self.state[7].wrapping_add(h); + } + + fn finalize(mut self) -> [u8; 32] { + let bit_length = self.length.wrapping_mul(8); + self.update(&[0x80]); + while self.used != 56 { + self.update(&[0]); + } + self.update(&bit_length.to_be_bytes()); + let mut out = [0u8; 32]; + for (i, word) in self.state.iter().enumerate() { + out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes()); + } + out + } +} + +fn sha256_hex(data: &[u8]) -> String { + let digest = { + let mut hasher = Sha256::new(); + hasher.update(data); + hasher.finalize() + }; + let mut out = String::with_capacity(64); + for byte in digest { + out.push_str(&format!("{byte:02x}")); + } + out +} + +// ---------------------------------------------------------------- local I/O + +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(tag: &str) -> Result { + let base = env::temp_dir(); + for _ in 0..16 { + let path = base.join(format!( + "alkane-{tag}-{}-{}", + std::process::id(), + random_token() + )); + match fs::create_dir(&path) { + Ok(()) => return Ok(Self { path }), + Err(e) if e.kind() == ErrorKind::AlreadyExists => continue, + Err(e) => { + return Err(StockError::Io(format!("could not create a temporary directory: {e}"))) + } + } + } + Err(StockError::Io("could not create a temporary directory".into())) + } + + fn path(&self) -> &Path { + &self.path + } + + fn join(&self, name: &str) -> PathBuf { + self.path.join(name) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn write_private(path: &Path, data: &[u8]) -> Result<(), StockError> { + fs::write(path, data) + .map_err(|e| StockError::Io(format!("could not write a temporary file: {e}")))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600)); + } + Ok(()) +} + +fn write_curl_config(path: &Path, lines: &[String]) -> Result<(), StockError> { + let mut text = String::new(); + for line in lines { + text.push_str(line); + text.push('\n'); + } + write_private(path, text.as_bytes()) +} + +fn curl_quote(value: &str) -> String { + let mut out = String::with_capacity(value.len() + 2); + out.push('"'); + for c in value.chars() { + match c { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + _ => out.push(c), + } + } + out.push('"'); + out +} + +fn random_token() -> String { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_nanos(); + format!("{:x}{:x}", std::process::id(), nanos) +} + +fn validate_host(host: &str) -> Result<(), StockError> { + if host.is_empty() || host.len() > 253 { + return Err(StockError::Method("invalid target address".into())); + } + let valid = host + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | ':' | '-' | '_')); + if !valid { + return Err(StockError::Method("invalid target address".into())); + } + Ok(()) +} + +struct CmdResult { + status: Option, + stdout: Vec, + stderr: Vec, + timed_out: bool, +} + +impl CmdResult { + fn ok(&self) -> bool { + !self.timed_out && self.status == Some(0) + } +} + +fn run_command( + mut command: Command, + timeout: Duration, + input: Option>, +) -> Result { + command.stdin(if input.is_some() { + Stdio::piped() + } else { + Stdio::null() + }); + command.stdout(Stdio::piped()); + command.stderr(Stdio::piped()); + + let mut child = command + .spawn() + .map_err(|e| StockError::Io(format!("could not start a required local tool: {e}")))?; + + let stdout_pipe = child.stdout.take(); + let stderr_pipe = child.stderr.take(); + let stdout_reader = stdout_pipe.map(|mut pipe| { + thread::spawn(move || { + let mut data = Vec::new(); + let _ = pipe.read_to_end(&mut data); + data + }) + }); + let stderr_reader = stderr_pipe.map(|mut pipe| { + thread::spawn(move || { + let mut data = Vec::new(); + let _ = pipe.read_to_end(&mut data); + data + }) + }); + + let stdin_writer = if let Some(data) = input { + child.stdin.take().map(|mut pipe| { + thread::spawn(move || { + let _ = pipe.write_all(&data); + let _ = pipe.flush(); + }) + }) + } else { + None + }; + + let start = Instant::now(); + let mut timed_out = false; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Some(status.code()), + Ok(None) => { + if start.elapsed() >= timeout { + let _ = child.kill(); + let _ = child.wait(); + timed_out = true; + break None; + } + thread::sleep(Duration::from_millis(50)); + } + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(StockError::Io(format!("a required local tool failed: {e}"))); + } + } + }; + + if let Some(writer) = stdin_writer { + let _ = writer.join(); + } + let stdout = stdout_reader + .and_then(|reader| reader.join().ok()) + .unwrap_or_default(); + let stderr = stderr_reader + .and_then(|reader| reader.join().ok()) + .unwrap_or_default(); + + Ok(CmdResult { + status: status.flatten(), + stdout, + stderr, + timed_out, + }) +} + +fn text(data: &[u8]) -> String { + String::from_utf8_lossy(data).into_owned() +} + +// ---------------------------------------------------------------- SSH + +fn ssh_command(host: &str, password: Option<&str>, remote: &str) -> Command { + let mut command; + if let Some(password) = password { + command = Command::new("sshpass"); + command.arg("-e"); + command.arg("ssh"); + command.env("SSHPASS", password); + } else { + command = Command::new("ssh"); + } + command.args([ + "-F", + "/dev/null", + "-o", + "StrictHostKeyChecking=no", + "-o", + "UserKnownHostsFile=/dev/null", + "-o", + "ConnectTimeout=10", + "-o", + "NumberOfPasswordPrompts=1", + "-o", + "LogLevel=ERROR", + ]); + if password.is_none() { + command.args(["-o", "BatchMode=yes"]); + } + command.arg(format!("root@{host}")); + command.arg(remote); + command +} + +fn classify_ssh(result: &CmdResult) -> StockError { + let lower = text(&result.stderr).to_lowercase(); + let auth = lower.contains("permission denied") + || lower.contains("authentication failed") + || lower.contains("no supported authentication") + || lower.contains("too many authentication failures"); + if auth { + return StockError::Auth("target rejected the credential".into()); + } + StockError::Network("could not reach the target".into()) +} + +fn ssh_exec( + host: &str, + password: Option<&str>, + remote: &str, + timeout: Duration, +) -> Result { + let result = run_command(ssh_command(host, password, remote), timeout, None)?; + if result.timed_out { + return Err(StockError::Network("target did not respond".into())); + } + Ok(result) +} + +fn ssh_probe(host: &str, password: Option<&str>) -> Result<(), StockError> { + let result = ssh_exec(host, password, "echo __ALKANE_OK__", Duration::from_secs(20))?; + if result.ok() && text(&result.stdout).contains("__ALKANE_OK__") { + return Ok(()); + } + Err(classify_ssh(&result)) +} + +fn ssh_push( + host: &str, + password: Option<&str>, + remote_path: &str, + data: &[u8], + timeout: Duration, +) -> Result<(), StockError> { + let remote = format!("cat > {remote_path}"); + let result = run_command( + ssh_command(host, password, &remote), + timeout, + Some(data.to_vec()), + )?; + if result.timed_out { + return Err(StockError::Network("target transfer timed out".into())); + } + if !result.ok() { + return Err(classify_ssh(&result)); + } + Ok(()) +} + +fn reboot_target(host: &str, password: Option<&str>) { + let _ = run_command( + ssh_command( + host, + password, + "sync; (echo b > /proc/sysrq-trigger) 2>/dev/null || reboot -f", + ), + Duration::from_secs(15), + None, + ); +} + +fn resolve_password(password: Option<&str>) -> Option { + if let Some(password) = password { + if !password.is_empty() { + return Some(password.to_string()); + } + } + if let Ok(password) = env::var("ALKANE_BOARD_PASSWORD") { + if !password.is_empty() { + return Some(password); + } + } + if let Ok(path) = env::var("ALKANE_BOARD_PASSWORD_FILE") { + if let Ok(raw) = fs::read_to_string(path) { + let password = raw.trim_end_matches(['\n', '\r']).to_string(); + if !password.is_empty() { + return Some(password); + } + } + } + None +} + +fn web_password_candidates(password: Option<&str>) -> Vec { + let mut candidates = Vec::new(); + if let Some(password) = password { + if !password.is_empty() { + candidates.push(password.to_string()); + } + } + if let Ok(password) = env::var("ALKANE_STOCK_WEB_PASSWORD") { + if !password.is_empty() && !candidates.iter().any(|c| c == &password) { + candidates.push(password); + } + } + if let Some(password) = resolve_password(None) { + if !candidates.iter().any(|c| c == &password) { + candidates.push(password); + } + } + if !candidates.iter().any(|c| c == "root") { + candidates.push("root".to_string()); + } + candidates +} + +// ---------------------------------------------------------------- network probes + +fn tcp_banner(host: &str, port: u16, timeout: Duration) -> Option> { + let addrs = (host, port).to_socket_addrs().ok()?; + for addr in addrs { + if let Ok(mut stream) = TcpStream::connect_timeout(&addr, timeout) { + let _ = stream.set_read_timeout(Some(timeout)); + let mut buf = [0u8; 256]; + if let Ok(n) = stream.read(&mut buf) { + if n > 0 { + return Some(buf[..n].to_vec()); + } + } + } + } + None +} + +fn ssh_port_open(host: &str) -> bool { + tcp_banner(host, 22, Duration::from_millis(1500)).is_some() +} + +fn is_alkane_ssh(host: &str) -> bool { + match tcp_banner(host, 22, Duration::from_millis(1500)) { + Some(banner) => text(&banner).to_lowercase().contains("dropbear"), + None => false, + } +} + +fn is_stock_http(host: &str) -> bool { + let mut command = Command::new("curl"); + command.args([ + "-sS", + "-i", + "--max-time", + "6", + &format!("http://{host}/"), + ]); + match run_command(command, Duration::from_secs(12), None) { + Ok(result) => { + let lower = text(&result.stdout).to_lowercase(); + lower.contains("lighttpd") && (lower.contains("antminer") || lower.contains("401")) + } + Err(_) => false, + } +} + +fn wait_for(mut predicate: F, timeout: Duration) -> bool +where + F: FnMut() -> bool, +{ + let deadline = Instant::now() + timeout; + loop { + if predicate() { + return true; + } + if Instant::now() >= deadline { + return false; + } + thread::sleep(Duration::from_secs(3)); + } +} + +fn wait_alkane(host: &str, timeout: Duration) -> bool { + wait_for(|| is_alkane_ssh(host), timeout) +} + +fn wait_stock(host: &str, timeout: Duration) -> bool { + wait_for(|| is_stock_http(host), timeout) +} + +// ---------------------------------------------------------------- curl + +fn run_curl(config: &Path, timeout: Duration) -> Result { + let mut command = Command::new("curl"); + command.arg("--config").arg(config); + run_command(command, timeout, None) +} + +fn http_code(result: &CmdResult) -> u16 { + text(&result.stdout).trim().parse::().unwrap_or(0) +} + +fn stock_web_auth( + host: &str, + password: &str, + dir: &Path, + tag: &str, +) -> Result<(), StockError> { + let config = dir.join(format!("auth-{tag}.cfg")); + let output = dir.join(format!("auth-{tag}.out")); + write_curl_config( + &config, + &[ + "silent".to_string(), + "show-error".to_string(), + "digest".to_string(), + "max-time = 15".to_string(), + format!("url = {}", curl_quote(&format!("http://{host}/"))), + format!("user = {}", curl_quote(&format!("root:{password}"))), + format!("output = {}", curl_quote(&output.to_string_lossy())), + "write-out = \"%{http_code}\"".to_string(), + ], + )?; + let result = run_curl(&config, Duration::from_secs(25))?; + match http_code(&result) { + 200..=299 => Ok(()), + 401 | 403 => Err(StockError::Auth("target rejected the credential".into())), + 0 => Err(StockError::Network("target unreachable".into())), + _ => Err(StockError::Method("target web interface unavailable".into())), + } +} + +fn stock_web_upload( + host: &str, + password: &str, + dir: &Path, + body: &Path, + boundary: &str, + tag: &str, +) -> Result<(), StockError> { + let config = dir.join(format!("upload-{tag}.cfg")); + let output = dir.join(format!("upload-{tag}.out")); + write_curl_config( + &config, + &[ + "silent".to_string(), + "show-error".to_string(), + "digest".to_string(), + "location".to_string(), + "max-redirs = 5".to_string(), + "max-time = 600".to_string(), + format!("url = {}", curl_quote(&format!("http://{host}/cgi-bin/upgrade.cgi"))), + format!("user = {}", curl_quote(&format!("root:{password}"))), + format!( + "header = {}", + curl_quote(&format!( + "Content-Type: multipart/form-data; boundary={boundary}" + )) + ), + "header = \"Expect:\"".to_string(), + format!("data-binary = {}", curl_quote(&format!("@{}", body.display()))), + format!("output = {}", curl_quote(&output.to_string_lossy())), + "write-out = \"%{http_code}\"".to_string(), + ], + )?; + let result = run_curl(&config, Duration::from_secs(620))?; + match http_code(&result) { + 200..=299 => Ok(()), + 401 | 403 => Err(StockError::Auth("target rejected the credential".into())), + 0 => Err(StockError::Network("target unreachable".into())), + _ => Err(StockError::Method("target transfer failed".into())), + } +} + +fn stock_web_trigger( + host: &str, + password: &str, + dir: &Path, + cgi: &str, + tag: &str, +) -> Result { + let config = dir.join(format!("trigger-{tag}.cfg")); + write_curl_config( + &config, + &[ + "silent".to_string(), + "show-error".to_string(), + "digest".to_string(), + "location".to_string(), + "max-redirs = 5".to_string(), + "max-time = 900".to_string(), + format!("url = {}", curl_quote(&format!("http://{host}/cgi-bin/{cgi}"))), + format!("user = {}", curl_quote(&format!("root:{password}"))), + ], + )?; + run_curl(&config, Duration::from_secs(920)) +} + +// ---------------------------------------------------------------- AFW + +fn afw_payload<'a>(afw: &'a VerifiedAfw, image: &str, file: &str) -> Option<&'a [u8]> { + if let Some((_, data)) = afw.image(image) { + return Some(data); + } + if let Some(data) = afw.payload(file) { + return Some(data); + } + let short = file.strip_prefix("payload/").unwrap_or(file); + afw.payload(short) +} + +fn load_install_images( + afw: &VerifiedAfw, +) -> Result<(Vec, Vec, Vec), StockError> { + if afw.manifest.board != BOARD { + return Err(StockError::Method("image is not for this target".into())); + } + let zimage = afw_payload(afw, "kernel", "payload/zImage") + .ok_or_else(|| StockError::Method("image is incomplete".into()))?; + let dtb = afw_payload(afw, "dtb", "payload/zynq-alkane.dtb") + .ok_or_else(|| StockError::Method("image is incomplete".into()))?; + let rootfs = afw_payload(afw, "rootfs", "payload/rootfs.cpio.gz") + .ok_or_else(|| StockError::Method("image is incomplete".into()))?; + + if zimage.len() < 0x28 || zimage[0x24..0x28] != [0x18, 0x28, 0x6f, 0x01] { + return Err(StockError::Method("image is not a kernel".into())); + } + if dtb.len() < 8 || dtb[0..4] != [0xd0, 0x0d, 0xfe, 0xed] { + return Err(StockError::Method("image is not a device tree".into())); + } + if rootfs.len() < 2 || rootfs[0..2] != [0x1f, 0x8b] { + return Err(StockError::Method("image is not a root filesystem".into())); + } + + let kernel = mk_uimage(zimage, 0x8000, 0x8000, 5, 2, 2, 0, b"alkane"); + let rootfs_uimage = mk_uimage(rootfs, 0, 0, 5, 2, 3, 1, b"alkane-rootfs"); + Ok((kernel, dtb.to_vec(), rootfs_uimage)) +} + +// ---------------------------------------------------------------- uImage + +fn be32(dst: &mut [u8], value: u32) { + dst[..4].copy_from_slice(&value.to_be_bytes()); +} + +fn mk_uimage( + data: &[u8], + load: u32, + entry: u32, + os: u8, + arch: u8, + kind: u8, + compression: u8, + name: &[u8], +) -> Vec { + let mut header = [0u8; 64]; + be32(&mut header[0..4], 0x2705_1956); + be32(&mut header[8..12], 0); + be32(&mut header[12..16], data.len() as u32); + be32(&mut header[16..20], load); + be32(&mut header[20..24], entry); + be32(&mut header[24..28], crc32(data)); + header[28] = os; + header[29] = arch; + header[30] = kind; + header[31] = compression; + let count = name.len().min(32); + header[32..32 + count].copy_from_slice(&name[..count]); + let header_crc = crc32(&header); + be32(&mut header[4..8], header_crc); + + let mut out = Vec::with_capacity(64 + data.len()); + out.extend_from_slice(&header); + out.extend_from_slice(data); + out +} + +// ---------------------------------------------------------------- MD5 / CRC32 + +struct Md5 { + state: [u32; 4], + length: u64, + buffer: [u8; 64], + used: usize, +} + +impl Md5 { + fn new() -> Self { + Self { + state: [0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476], + length: 0, + buffer: [0u8; 64], + used: 0, + } + } + + fn update(&mut self, mut data: &[u8]) { + self.length = self.length.wrapping_add(data.len() as u64); + if self.used > 0 { + let need = 64 - self.used; + let take = need.min(data.len()); + self.buffer[self.used..self.used + take].copy_from_slice(&data[..take]); + self.used += take; + data = &data[take..]; + if self.used == 64 { + let block = self.buffer; + self.compress(&block); + self.used = 0; + } + } + while data.len() >= 64 { + let mut block = [0u8; 64]; + block.copy_from_slice(&data[..64]); + self.compress(&block); + data = &data[64..]; + } + if !data.is_empty() { + self.buffer[..data.len()].copy_from_slice(data); + self.used = data.len(); + } + } + + fn compress(&mut self, block: &[u8; 64]) { + const S: [u32; 64] = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, + 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, + 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, + ]; + const K: [u32; 64] = [ + 0xd76a_a478, 0xe8c7_b756, 0x2420_70db, 0xc1bd_ceee, 0xf57c_0faf, 0x4787_c62a, + 0xa830_4613, 0xfd46_9501, 0x6980_98d8, 0x8b44_f7af, 0xffff_5bb1, 0x895c_d7be, + 0x6b90_1122, 0xfd98_7193, 0xa679_438e, 0x49b4_0821, 0xf61e_2562, 0xc040_b340, + 0x265e_5a51, 0xe9b6_c7aa, 0xd62f_105d, 0x0244_1453, 0xd8a1_e681, 0xe7d3_fbc8, + 0x21e1_cde6, 0xc337_07d6, 0xf4d5_0d87, 0x455a_14ed, 0xa9e3_e905, 0xfcef_a3f8, + 0x676f_02d9, 0x8d2a_4c8a, 0xfffa_3942, 0x8771_f681, 0x6d9d_6122, 0xfde5_380c, + 0xa4be_ea44, 0x4bde_cfa9, 0xf6bb_4b60, 0xbebf_bc70, 0x289b_7ec6, 0xeaa1_27fa, + 0xd4ef_3085, 0x0488_1d05, 0xd9d4_d039, 0xe6db_99e5, 0x1fa2_7cf8, 0xc4ac_5665, + 0xf429_2244, 0x432a_ff97, 0xab94_23a7, 0xfc93_a039, 0x655b_59c3, 0x8f0c_cc92, + 0xffef_f47d, 0x8584_5dd1, 0x6fa8_7e4f, 0xfe2c_e6e0, 0xa301_4314, 0x4e08_11a1, + 0xf753_7e82, 0xbd3a_f235, 0x2ad7_d2bb, 0xeb86_d391, + ]; + + let mut words = [0u32; 16]; + for (i, chunk) in block.chunks_exact(4).enumerate() { + words[i] = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); + } + let [mut a, mut b, mut c, mut d] = self.state; + for i in 0..64 { + let (f, g) = match i { + 0..=15 => ((b & c) | ((!b) & d), i), + 16..=31 => ((d & b) | ((!d) & c), (5 * i + 1) % 16), + 32..=47 => (b ^ c ^ d, (3 * i + 5) % 16), + _ => (c ^ (b | (!d)), (7 * i) % 16), + }; + let temp = d; + d = c; + c = b; + b = b.wrapping_add( + a.wrapping_add(f) + .wrapping_add(K[i]) + .wrapping_add(words[g]) + .rotate_left(S[i]), + ); + a = temp; + } + self.state[0] = self.state[0].wrapping_add(a); + self.state[1] = self.state[1].wrapping_add(b); + self.state[2] = self.state[2].wrapping_add(c); + self.state[3] = self.state[3].wrapping_add(d); + } + + fn finalize(mut self) -> [u8; 16] { + let bit_length = self.length.wrapping_mul(8); + let mut padding = vec![0x80u8]; + let remaining = (self.used + 1) % 64; + let pad_len = if remaining <= 56 { 56 - remaining } else { 120 - remaining }; + padding.extend(std::iter::repeat(0u8).take(pad_len)); + padding.extend_from_slice(&bit_length.to_le_bytes()); + let saved_length = self.length; + self.length = 0; + self.update(&padding); + self.length = saved_length; + let mut out = [0u8; 16]; + for (i, word) in self.state.iter().enumerate() { + out[i * 4..i * 4 + 4].copy_from_slice(&word.to_le_bytes()); + } + out + } +} + +fn md5_hex(data: &[u8]) -> String { + let mut hasher = Md5::new(); + hasher.update(data); + let digest = hasher.finalize(); + let mut out = String::with_capacity(32); + for byte in digest { + out.push_str(&format!("{byte:02x}")); + } + out +} + +fn padded_md5(data: &[u8], blocks: u64) -> String { + let mut hasher = Md5::new(); + hasher.update(data); + let target = blocks * BLK; + let mut remaining = target.saturating_sub(data.len() as u64); + let pad = [0xffu8; 8192]; + while remaining > 0 { + let take = remaining.min(pad.len() as u64) as usize; + hasher.update(&pad[..take]); + remaining -= take as u64; + } + let digest = hasher.finalize(); + let mut out = String::with_capacity(32); + for byte in digest { + out.push_str(&format!("{byte:02x}")); + } + out +} + +fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xffff_ffffu32; + for byte in data { + crc ^= *byte as u32; + for _ in 0..8 { + if crc & 1 != 0 { + crc = (crc >> 1) ^ 0xedb8_8320; + } else { + crc >>= 1; + } + } + } + !crc +} + +// ---------------------------------------------------------------- gzip / tar + +fn gzip_store(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len() + data.len() / 65535 * 5 + 32); + out.extend_from_slice(&[0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0x00, 0xff]); + let mut position = 0; + loop { + let remaining = data.len() - position; + let take = remaining.min(65535); + let final_block = position + take == data.len(); + out.push(if final_block { 1 } else { 0 }); + let length = take as u16; + out.extend_from_slice(&length.to_le_bytes()); + out.extend_from_slice(&(!length).to_le_bytes()); + out.extend_from_slice(&data[position..position + take]); + position += take; + if final_block { + break; + } + } + out.extend_from_slice(&crc32(data).to_le_bytes()); + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out +} + +fn put_octal(field: &mut [u8], value: u64) { + let width = field.len() - 1; + let digits = format!("{:0width$o}", value, width = width); + let bytes = digits.as_bytes(); + let take = bytes.len().min(width); + field[..width].fill(b'0'); + field[width - take..width].copy_from_slice(&bytes[bytes.len() - take..]); + field[width] = 0; +} + +fn tar_header(name: &str, mode: u32, size: u64, kind: u8, link: &str) -> [u8; 512] { + let mut header = [0u8; 512]; + let name_bytes = name.as_bytes(); + let count = name_bytes.len().min(100); + header[..count].copy_from_slice(&name_bytes[..count]); + put_octal(&mut header[100..108], mode as u64); + put_octal(&mut header[108..116], 0); + put_octal(&mut header[116..124], 0); + put_octal(&mut header[124..136], size); + put_octal(&mut header[136..148], 0); + header[148..156].fill(b' '); + header[156] = kind; + let link_bytes = link.as_bytes(); + let link_count = link_bytes.len().min(100); + header[157..157 + link_count].copy_from_slice(&link_bytes[..link_count]); + header[257..263].copy_from_slice(b"ustar\0"); + header[263..265].copy_from_slice(b"00"); + let sum: u32 = header.iter().map(|byte| *byte as u32).sum(); + let checksum = format!("{sum:06o}"); + let checksum_bytes = checksum.as_bytes(); + let checksum_count = checksum_bytes.len().min(6); + header[148..154].fill(b'0'); + let start = 154 - checksum_count; + header[start..154].copy_from_slice(&checksum_bytes[checksum_bytes.len() - checksum_count..]); + header[154] = 0; + header[155] = b' '; + header +} + +struct TarEntry { + name: String, + mode: u32, + kind: u8, + link: String, + data: Vec, +} + +fn build_tar(entries: &[TarEntry]) -> Vec { + let mut out = Vec::new(); + for entry in entries { + let size = if entry.kind == b'0' { entry.data.len() as u64 } else { 0 }; + let header = tar_header(&entry.name, entry.mode, size, entry.kind, &entry.link); + out.extend_from_slice(&header); + if entry.kind == b'0' { + out.extend_from_slice(&entry.data); + let padding = (512 - (entry.data.len() % 512)) % 512; + out.extend(std::iter::repeat(0u8).take(padding)); + } + } + out.extend(std::iter::repeat(0u8).take(1024)); + out +} + +// ---------------------------------------------------------------- flash targets + +struct Mtd { + device: String, + offset: u64, + size: u64, +} + +struct FlashTarget { + name: &'static str, + file: &'static str, + device: String, + rel: u64, + slot: u64, + data: Cow<'static, [u8]>, + raw_md5: String, + padded_md5: String, + blocks: u64, +} + +fn parse_number(value: &str) -> Option { + let value = value.trim(); + if let Some(hex) = value.strip_prefix("0x") { + u64::from_str_radix(hex, 16).ok() + } else { + value.parse::().ok() + } +} + +fn read_mtd_map(host: &str, password: Option<&str>) -> Result, StockError> { + let script = "for d in /sys/class/mtd/mtd[0-9]*; do \ + [ -e \"$d/name\" ] || continue; \ + n=${d##*/}; \ + printf '%s|%s|%s|%s\\n' \"$n\" \"$(cat $d/name 2>/dev/null)\" \ + \"$(cat $d/offset 2>/dev/null)\" \"$(cat $d/size 2>/dev/null)\"; \ + done"; + let result = ssh_exec(host, password, script, Duration::from_secs(30))?; + if !result.ok() { + return Err(classify_ssh(&result)); + } + let mut map = Vec::new(); + for line in text(&result.stdout).lines() { + let mut parts = line.trim().split('|'); + let name = match parts.next() { + Some(name) if name.starts_with("mtd") => name, + _ => continue, + }; + if !name[3..].chars().all(|c| c.is_ascii_digit()) { + continue; + } + let _label = parts.next(); + let offset = match parts.next().and_then(parse_number) { + Some(value) => value, + None => continue, + }; + let size = match parts.next().and_then(parse_number) { + Some(value) => value, + None => continue, + }; + map.push(Mtd { + device: format!("/dev/{name}"), + offset, + size, + }); + } + if map.is_empty() { + return Err(StockError::Method("target storage layout unsupported".into())); + } + Ok(map) +} + +fn map_covers_boot_regions(map: &[Mtd]) -> bool { + [ABS_DTB, ABS_KERNEL, ABS_ROOTFS] + .iter() + .all(|absolute| locate_mtd(map, *absolute).is_some()) +} + +fn get_mtd_map(host: &str, password: Option<&str>) -> Result, StockError> { + let map = read_mtd_map(host, password)?; + if map_covers_boot_regions(&map) { + return Ok(map); + } + + let mtd_patch = stock_asset(&ASSET_MTD_PATCH)?; + ssh_push( + host, + password, + "/tmp/.ak-mtdpatch", + &mtd_patch, + Duration::from_secs(60), + )?; + let result = ssh_exec( + host, + password, + "chmod +x /tmp/.ak-mtdpatch && /tmp/.ak-mtdpatch --write", + Duration::from_secs(120), + )?; + let _ = ssh_exec( + host, + password, + "rm -f /tmp/.ak-mtdpatch", + Duration::from_secs(15), + ); + if !result.ok() { + return Err(StockError::Method( + "target storage layout unsupported".into(), + )); + } + let map = read_mtd_map(host, password)?; + if !map_covers_boot_regions(&map) { + return Err(StockError::Method( + "target storage layout unsupported".into(), + )); + } + Ok(map) +} + +fn locate_mtd(map: &[Mtd], absolute: u64) -> Option<(&Mtd, u64)> { + for mtd in map { + if mtd.offset <= absolute && absolute < mtd.offset + mtd.size { + return Some((mtd, absolute - mtd.offset)); + } + } + None +} + +fn make_target( + name: &'static str, + file: &'static str, + device: String, + rel: u64, + absolute: u64, + slot: u64, + data: Cow<'static, [u8]>, +) -> Result { + if absolute < BOOTBIN_PRESERVE { + return Err(StockError::Method( + "refusing to write the boot region".into(), + )); + } + if device == "/dev/mtd0" && rel < BOOTBIN_PRESERVE { + return Err(StockError::Method( + "refusing to write the boot region".into(), + )); + } + if !device.starts_with("/dev/") + || !device[5..].chars().all(|c| c.is_ascii_alphanumeric()) + { + return Err(StockError::Method("target storage layout unsupported".into())); + } + if rel % BLK != 0 || slot == 0 || slot % BLK != 0 { + return Err(StockError::Method("target storage layout unsupported".into())); + } + let blocks = (data.len() as u64).div_ceil(BLK); + if blocks == 0 || blocks * BLK > slot { + return Err(StockError::Method("image does not fit target slot".into())); + } + let raw_md5 = md5_hex(data.as_ref()); + let padded_md5 = padded_md5(data.as_ref(), blocks); + Ok(FlashTarget { + name, + file, + device, + rel, + slot, + data, + raw_md5, + padded_md5, + blocks, + }) +} + +fn targets_from_map( + map: &[Mtd], + images: Vec<(&'static str, &'static str, u64, u64, Cow<'static, [u8]>)>, +) -> Result, StockError> { + let mut targets = Vec::with_capacity(images.len()); + for (name, file, absolute, slot, data) in images { + let (mtd, rel) = locate_mtd(map, absolute) + .ok_or_else(|| StockError::Method("target storage layout unsupported".into()))?; + if rel.checked_add(slot).map_or(true, |end| end > mtd.size) { + return Err(StockError::Method("image does not fit target slot".into())); + } + targets.push(make_target( + name, + file, + mtd.device.clone(), + rel, + absolute, + slot, + data, + )?); + } + Ok(targets) +} + +fn stock_web_targets( + kernel: Vec, + dtb: Vec, + rootfs: Vec, +) -> Result, StockError> { + let images = vec![ + ( + "rootfs", + "afw-rootfs.uimg", + ABS_ROOTFS, + ROOTFS_SLOT, + Cow::Owned(rootfs), + ), + ("dtb", "afw-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)), + ( + "kernel", + "afw-kernel.uimg", + ABS_KERNEL, + KERNEL_SLOT, + Cow::Owned(kernel), + ), + ]; + let map = vec![ + Mtd { + device: "/dev/mtd0".to_string(), + offset: 0, + size: 0x2800000, + }, + Mtd { + device: "/dev/mtd1".to_string(), + offset: 0x2800000, + size: 0x2000000, + }, + ]; + targets_from_map(&map, images) +} + +// ---------------------------------------------------------------- scripts + +fn flash_script(targets: &[FlashTarget], token: &str, web_cgi: Option<&str>) -> String { + let mut script = String::new(); + script.push_str("#!/bin/sh\n"); + script.push_str("set -u\n"); + if web_cgi.is_some() { + script.push_str("printf 'Content-type: text/plain\\r\\n\\r\\n'\n"); + } + script.push_str("fail(){ echo \"@@FAIL@@ $*\"; sync; exit 1; }\n"); + + for target in targets { + let path = if web_cgi.is_some() { + format!("/tmp/.ak-{token}-{}", target.file) + } else { + format!("/tmp/rs/{}", target.file) + }; + script.push_str(&format!("echo \"### {}\"\n", target.name)); + script.push_str(&format!("f={path}\n")); + script.push_str(&format!( + "m=$(md5sum \"$f\" | cut -d' ' -f1); [ \"$m\" = \"{}\" ] || fail md5-{}\n", + target.raw_md5, target.name + )); + script.push_str(&format!( + "flash_erase {} 0x{:x} 0x{:x} >/dev/null 2>&1 || fail erase-{}\n", + target.device, + target.rel, + target.slot / BLK, + target.name + )); + script.push_str(&format!( + "nandwrite -p -s 0x{:x} {} \"$f\" >/dev/null 2>&1 || fail write-{}\n", + target.rel, target.device, target.name + )); + script.push_str(&format!( + "v=$(dd if={} bs={} skip={} count={} 2>/dev/null | md5sum | cut -d' ' -f1)\n", + target.device, + BLK, + target.rel / BLK, + target.blocks + )); + script.push_str(&format!( + "[ \"$v\" = \"{}\" ] || fail verify-{}-$v\n", + target.padded_md5, target.name + )); + script.push_str(&format!("echo \"### {} ok\"\n", target.name)); + } + + if let Some(cgi) = web_cgi { + script.push_str("sync\n"); + script.push_str("echo \"@@OK@@\"\n"); + script.push_str(&format!("rm -f /www/pages/cgi-bin/{cgi}\n")); + script.push_str(&format!("rm -f /tmp/.ak-{token}-*\n")); + script.push_str("sync\n"); + script.push_str( + "( sleep 2; sync; (echo b > /proc/sysrq-trigger) 2>/dev/null || reboot -f ) \ + >/dev/null 2>&1 &\n", + ); + } else { + script.push_str("sync\n"); + script.push_str("echo \"@@OK@@\"\n"); + } + script +} + +fn build_web_body( + targets: &[FlashTarget], + token: &str, + cgi: &str, + script: &str, +) -> (Vec, String) { + let mut entries = Vec::new(); + entries.push(TarEntry { + name: "d".to_string(), + mode: 0o777, + kind: b'2', + link: "/tmp".to_string(), + data: Vec::new(), + }); + entries.push(TarEntry { + name: "p".to_string(), + mode: 0o777, + kind: b'2', + link: "/www/pages/cgi-bin".to_string(), + data: Vec::new(), + }); + for target in targets { + entries.push(TarEntry { + name: format!("d/.ak-{token}-{}", target.file), + mode: 0o644, + kind: b'0', + link: String::new(), + data: target.data.as_ref().to_vec(), + }); + } + entries.push(TarEntry { + name: format!("p/{cgi}"), + mode: 0o755, + kind: b'0', + link: String::new(), + data: script.as_bytes().to_vec(), + }); + + let tar = build_tar(&entries); + let gz = gzip_store(&tar); + let boundary = format!("----alkane{}", random_token()); + let mut body = Vec::with_capacity(gz.len() + 512); + body.extend_from_slice( + format!( + "--{boundary}\r\nContent-Disposition: form-data; name=\"file1\"; \ + filename=\"image.tar.gz\"\r\nContent-Type: application/octet-stream\r\n\r\n" + ) + .as_bytes(), + ); + body.extend_from_slice(&gz); + body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); + (body, boundary) +} + +// ---------------------------------------------------------------- install / restore + +fn install_via_web( + host: &str, + password: Option<&str>, + kernel: Vec, + dtb: Vec, + rootfs: Vec, +) -> Result<(), StockError> { + let dir = TempDir::new("web")?; + let candidates = web_password_candidates(password); + let mut chosen = None; + let mut last_auth = false; + for (index, candidate) in candidates.iter().enumerate() { + match stock_web_auth(host, candidate, dir.path(), &format!("probe{index}")) { + Ok(()) => { + chosen = Some(candidate.clone()); + break; + } + Err(StockError::Auth(_)) => { + last_auth = true; + continue; + } + Err(e) => return Err(e), + } + } + let password = match chosen { + Some(password) => password, + None if last_auth => { + return Err(StockError::Auth("target rejected the credential".into())) + } + None => return Err(StockError::Network("target unreachable".into())), + }; + + let targets = stock_web_targets(kernel, dtb, rootfs)?; + let token = random_token(); + let cgi = format!("zz{token}.cgi"); + let script = flash_script(&targets, &token, Some(&cgi)); + let (body, boundary) = build_web_body(&targets, &token, &cgi, &script); + let body_path = dir.join("upload.body"); + write_private(&body_path, &body)?; + + stock_web_upload( + host, + &password, + dir.path(), + &body_path, + &boundary, + &token, + )?; + let trigger = stock_web_trigger(host, &password, dir.path(), &cgi, &token)?; + let output = text(&trigger.stdout); + if output.contains("@@FAIL@@") { + return Err(StockError::Method("write failed".into())); + } + if wait_alkane(host, Duration::from_secs(240)) { + Ok(()) + } else { + Err(StockError::Method("target did not return".into())) + } +} + +fn install_via_ssh( + host: &str, + password: Option<&str>, + kernel: Vec, + dtb: Vec, + rootfs: Vec, +) -> Result<(), StockError> { + let map = get_mtd_map(host, password)?; + let images = vec![ + ( + "rootfs", + "afw-rootfs.uimg", + ABS_ROOTFS, + ROOTFS_SLOT, + Cow::Owned(rootfs), + ), + ("dtb", "afw-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)), + ( + "kernel", + "afw-kernel.uimg", + ABS_KERNEL, + KERNEL_SLOT, + Cow::Owned(kernel), + ), + ]; + let targets = targets_from_map(&map, images)?; + flash_via_ssh(host, password, &targets)?; + reboot_target(host, password); + if wait_alkane(host, Duration::from_secs(240)) { + Ok(()) + } else { + Err(StockError::Method("target did not return".into())) + } +} + +fn flash_via_ssh( + host: &str, + password: Option<&str>, + targets: &[FlashTarget], +) -> Result<(), StockError> { + let prep = ssh_exec(host, password, "mkdir -p /tmp/rs; rm -f /tmp/rs/*", Duration::from_secs(20))?; + if !prep.ok() { + return Err(classify_ssh(&prep)); + } + for target in targets { + let remote = format!("/tmp/rs/{}", target.file); + let timeout = Duration::from_secs(300); + ssh_push(host, password, &remote, target.data.as_ref(), timeout)?; + } + let script = flash_script(targets, "", None); + let remote_script = "/tmp/rs/go.sh"; + ssh_push( + host, + password, + remote_script, + script.as_bytes(), + Duration::from_secs(30), + )?; + let result = ssh_exec( + host, + password, + "sh /tmp/rs/go.sh", + Duration::from_secs(900), + )?; + let output = text(&result.stdout); + if output.contains("@@OK@@") && !output.contains("@@FAIL@@") { + return Ok(()); + } + if output.contains("@@FAIL@@") || result.ok() { + return Err(StockError::Method("write failed".into())); + } + Err(classify_ssh(&result)) +} + +fn board_state(host: &str, password: Option<&str>) -> Result { + let result = ssh_exec( + host, + password, + "uname -r; cat /etc/os-release 2>/dev/null; hostname 2>/dev/null", + Duration::from_secs(20), + )?; + if !result.ok() { + return Err(classify_ssh(&result)); + } + let lower = text(&result.stdout).to_lowercase(); + if lower.contains("angstrom") || lower.contains("bitmain") { + return Ok("stock".to_string()); + } + if lower.contains("alkane") { + return Ok("alkane".to_string()); + } + if let Some(line) = lower.lines().next() { + if let Some(major) = line.split('.').next().and_then(|v| v.parse::().ok()) { + if major >= 6 { + return Ok("alkane".to_string()); + } + if major == 4 { + return Ok("stock".to_string()); + } + } + } + Ok("unknown".to_string()) +} + +struct Method; + +impl StockMethod for Method { + fn install_from_stock( + &self, + host: &str, + _afw_path: &Path, + afw: &VerifiedAfw, + password: Option<&str>, + ) -> Result<(), StockError> { + validate_host(host)?; + let (kernel, dtb, rootfs) = load_install_images(afw)?; + + // A board that answers as our OS is updated in place over SSH. + if is_alkane_ssh(host) { + let resolved = resolve_password(password); + let password = resolved.as_deref(); + ssh_probe(host, password)?; + return install_via_ssh(host, password, kernel, dtb, rootfs); + } + + // A board on genuine stock is reached through its own web gate. + if !is_stock_http(host) { + if ssh_port_open(host) { + let resolved = resolve_password(password); + let password = resolved.as_deref(); + ssh_probe(host, password)?; + return install_via_ssh(host, password, kernel, dtb, rootfs); + } + return Err(StockError::Network("target unreachable".into())); + } + install_via_web(host, password, kernel, dtb, rootfs) + } + + fn restore_to_stock(&self, host: &str, password: Option<&str>) -> Result<(), StockError> { + validate_host(host)?; + if !ssh_port_open(host) { + if is_stock_http(host) { + return Ok(()); + } + return Err(StockError::Network("target unreachable".into())); + } + let resolved = resolve_password(password); + let password = resolved.as_deref(); + ssh_probe(host, password)?; + let state = board_state(host, password)?; + if state == "stock" { + return Ok(()); + } + + let map = get_mtd_map(host, password)?; + let images = vec![ + ( + "rootfs", + "stock-rootfs.uimg", + ABS_ROOTFS, + ROOTFS_SLOT, + Cow::Owned(stock_asset(&ASSET_ROOTFS)?), + ), + ( + "dtb", + "stock-dtb.bin", + ABS_DTB, + DTB_SLOT, + Cow::Owned(stock_asset(&ASSET_DTB)?), + ), + ( + "kernel", + "stock-kernel.uimg", + ABS_KERNEL, + KERNEL_SLOT, + Cow::Owned(stock_asset(&ASSET_KERNEL)?), + ), + ]; + let targets = targets_from_map(&map, images)?; + flash_via_ssh(host, password, &targets)?; + reboot_target(host, password); + if wait_stock(host, Duration::from_secs(240)) { + Ok(()) + } else { + Err(StockError::Method("target did not return".into())) + } + } +} + +static METHOD: Method = Method; pub fn method() -> &'static dyn StockMethod { &METHOD } + +// ---------------------------------------------------------------- tests + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn md5_known_vectors() { + assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e"); + assert_eq!(md5_hex(b"abc"), "900150983cd24fb0d6963f7d28e17f72"); + assert_eq!( + md5_hex(b"The quick brown fox jumps over the lazy dog"), + "9e107d9d372bb6826bd81d3542a419d6" + ); + } + + #[test] + fn sha256_known_vectors() { + assert_eq!( + sha256_hex(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + assert_eq!( + sha256_hex(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + sha256_hex(b"The quick brown fox jumps over the lazy dog"), + "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592" + ); + assert_eq!( + sha256_hex( + b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" + ), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + ); + } + + #[test] + fn fetch_pipeline_caches_verifies_and_redownloads() { + let work = TempDir::new("fetchtest").expect("temp dir"); + let source = work.path().join("source"); + fs::create_dir_all(&source).expect("source dir"); + let payload = b"stock asset payload"; + fs::write(source.join("blob-test.bin"), payload).expect("source asset"); + let hash: &'static str = Box::leak(sha256_hex(payload).into_boxed_str()); + let asset = StockAsset { + file: "blob-test.bin", + sha256: hash, + }; + let cache = work.path().join("cache"); + env::set_var( + "ALKANE_STOCK_ASSETS_BASE", + format!("file://{}", source.display()), + ); + env::set_var("XDG_CACHE_HOME", &cache); + + assert_eq!(stock_asset(&asset).expect("first fetch"), payload); + let cached = cache + .join("alkane-toolkit") + .join("stock-assets") + .join("blob-test.bin"); + assert!(cached.is_file()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + fs::metadata(&cached).expect("metadata").permissions().mode() & 0o777, + 0o600 + ); + } + + // A bad cache entry is dropped and fetched again. + fs::write(&cached, b"corrupt").expect("corrupt cache"); + assert_eq!(stock_asset(&asset).expect("re-fetch"), payload); + + // A mismatch on download leaves no cached file behind. + fs::remove_file(&cached).expect("remove cache"); + fs::write(source.join("blob-test.bin"), b"tampered").expect("tamper source"); + match stock_asset(&asset) { + Err(StockError::Method(message)) => { + assert_eq!(message, "asset integrity check failed") + } + other => panic!("expected an integrity failure, got {other:?}"), + } + assert!(!cached.exists()); + + env::remove_var("ALKANE_STOCK_ASSETS_BASE"); + env::remove_var("XDG_CACHE_HOME"); + } + + #[test] + fn crc32_known_vector() { + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); + } + + #[test] + fn uimage_header_is_consistent() { + let image = mk_uimage(b"payload", 0x8000, 0x8000, 5, 2, 2, 0, b"test"); + assert_eq!(image.len(), 64 + 7); + assert_eq!(&image[0..4], &[0x27, 0x05, 0x19, 0x56]); + let mut header = [0u8; 64]; + header.copy_from_slice(&image[..64]); + let stored = u32::from_be_bytes([header[4], header[5], header[6], header[7]]); + header[4..8].fill(0); + assert_eq!(stored, crc32(&header)); + let data_crc = u32::from_be_bytes([header[24], header[25], header[26], header[27]]); + assert_eq!(data_crc, crc32(b"payload")); + } + + #[test] + fn gzip_and_tar_are_well_formed() { + let entries = vec![ + TarEntry { + name: "d".to_string(), + mode: 0o777, + kind: b'2', + link: "/tmp".to_string(), + data: Vec::new(), + }, + TarEntry { + name: "p".to_string(), + mode: 0o777, + kind: b'2', + link: "/www/pages/cgi-bin".to_string(), + data: Vec::new(), + }, + TarEntry { + name: "d/test.bin".to_string(), + mode: 0o644, + kind: b'0', + link: String::new(), + data: b"hello".to_vec(), + }, + ]; + let tar = build_tar(&entries); + assert_eq!(tar.len() % 512, 0); + let gz = gzip_store(&tar); + assert_eq!(&gz[..2], &[0x1f, 0x8b]); + let dir = TempDir::new("test").expect("temp dir"); + let path = dir.join("test.tar.gz"); + fs::write(&path, &gz).expect("write"); + let result = Command::new("tar").arg("-tzf").arg(&path).output(); + if let Ok(result) = result { + if result.status.success() { + let listing = text(&result.stdout); + assert!(listing.contains("d/test.bin")); + assert!(listing.contains("p")); + } + } + } + + #[test] + fn every_default_target_is_above_bootbin() { + for (_, _, absolute, _, _) in [ + ("rootfs", "", ABS_ROOTFS, ROOTFS_SLOT, ()), + ("dtb", "", ABS_DTB, DTB_SLOT, ()), + ("kernel", "", ABS_KERNEL, KERNEL_SLOT, ()), + ] { + assert!(absolute >= BOOTBIN_PRESERVE); + } + } +}