diff --git a/crates/alkane-artifacts/src/fetch.rs b/crates/alkane-artifacts/src/fetch.rs index 3a8c4958..7eef9164 100644 --- a/crates/alkane-artifacts/src/fetch.rs +++ b/crates/alkane-artifacts/src/fetch.rs @@ -48,12 +48,33 @@ pub enum FetchError { } /// Where releases come from. Defaults to the alkane-os repo on the self-hosted -/// Gitea; the base URL and token are read from the environment. +/// Gitea; a full repo URL on any Gitea or GitHub host is also accepted so an +/// operator can flash from their own fork. pub struct ReleaseSource { pub base_url: String, pub owner: String, pub repo: String, pub token: Option, + /// GitHub uses `api.github.com/repos/...` instead of a Gitea + /// `.../api/v1/repos/...` path. + pub github: bool, +} + +/// The default self-hosted Gitea base (honoring `ALKANE_RELEASE_BASE`). +fn default_gitea_base() -> String { + std::env::var("ALKANE_RELEASE_BASE") + .ok() + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "https://gitea.bluefla.re".to_string()) +} + +/// Resolve the token for the default self-hosted Gitea (never sent elsewhere). +fn gitea_token() -> Option { + std::env::var("ALKANE_RELEASE_TOKEN") + .ok() + .or_else(|| std::env::var("GITEA_TOKEN").ok()) + .filter(|t| !t.is_empty()) + .or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty())) } impl ReleaseSource { @@ -63,37 +84,126 @@ impl ReleaseSource { Self::for_repo("blueflare", "alkane-os") } - /// A release source for an arbitrary Gitea `owner`/`repo`. The base URL - /// (`ALKANE_RELEASE_BASE`, else the self-hosted Gitea) and the token - /// (`ALKANE_RELEASE_TOKEN`, else `GITEA_TOKEN`, else the build-time embedded - /// token) are resolved exactly as for `alkane_os`. + /// A release source for an arbitrary Gitea `owner`/`repo` on the default + /// self-hosted Gitea base, with the resolved Gitea token. pub fn for_repo(owner: &str, repo: &str) -> Self { - let base_url = std::env::var("ALKANE_RELEASE_BASE") - .ok() - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| "https://gitea.bluefla.re".to_string()); - let token = std::env::var("ALKANE_RELEASE_TOKEN") - .ok() - .or_else(|| std::env::var("GITEA_TOKEN").ok()) - .filter(|t| !t.is_empty()) - .or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty())); Self { - base_url, + base_url: default_gitea_base(), owner: owner.to_string(), repo: repo.to_string(), + token: gitea_token(), + github: false, + } + } + + /// Parse a full repo URL (or a bare `owner/repo`) into a release source. + /// Supports any Gitea host and GitHub (`github.com`); a bare `owner/repo` + /// uses the default self-hosted Gitea. Accepts optional scheme, a trailing + /// `.git`, and trailing path noise (e.g. `/releases`). + /// + /// The resolved Gitea token is attached ONLY when the host is the default + /// self-hosted Gitea, so the embedded admin token is never sent to GitHub or + /// any other host (those use anonymous access to public releases). + pub fn from_url(input: &str) -> Option { + let s = input.trim().trim_end_matches('/'); + if s.is_empty() { + return None; + } + let no_scheme = s + .strip_prefix("https://") + .or_else(|| s.strip_prefix("http://")) + .unwrap_or(s); + let parts: Vec<&str> = no_scheme.split('/').filter(|p| !p.is_empty()).collect(); + // host present when the first segment looks like a hostname (has a dot). + let (host, owner, repo) = if parts.len() >= 3 && parts[0].contains('.') { + (Some(parts[0]), parts[1], parts[2]) + } else if parts.len() == 2 && !parts[0].contains('.') { + (None, parts[0], parts[1]) + } else { + return None; + }; + let repo = repo.trim_end_matches(".git"); + if owner.is_empty() || repo.is_empty() { + return None; + } + let default_host = default_gitea_base() + .trim_start_matches("https://") + .trim_start_matches("http://") + .trim_end_matches('/') + .to_string(); + let src = match host { + Some("github.com") | Some("www.github.com") => ReleaseSource { + base_url: "https://api.github.com".to_string(), + owner: owner.to_string(), + repo: repo.to_string(), + token: None, // never send the gitea token to github + github: true, + }, + Some(h) if h == default_host => ReleaseSource { + base_url: default_gitea_base(), + owner: owner.to_string(), + repo: repo.to_string(), + token: gitea_token(), + github: false, + }, + Some(h) => ReleaseSource { + base_url: format!("https://{h}"), + owner: owner.to_string(), + repo: repo.to_string(), + token: None, // a different Gitea host: anonymous public access + github: false, + }, + None => Self::for_repo(owner, repo), + }; + Some(src) + } + + /// A minimal source for downloading a release asset by its direct URL. The + /// gitea token is attached ONLY when the asset URL is on the trusted + /// self-hosted Gitea host; GitHub and other hosts get anonymous access, so + /// the embedded admin token is never sent off-host. + pub fn for_asset_url(url: &str) -> ReleaseSource { + let host = url + .trim_start_matches("https://") + .trim_start_matches("http://") + .split('/') + .next() + .unwrap_or(""); + let default_host = default_gitea_base() + .trim_start_matches("https://") + .trim_start_matches("http://") + .trim_end_matches('/') + .to_string(); + let token = if host == default_host { + gitea_token() + } else { + None + }; + ReleaseSource { + base_url: format!("https://{host}"), + owner: String::new(), + repo: String::new(), token, + github: host.eq_ignore_ascii_case("api.github.com") + || host.eq_ignore_ascii_case("github.com"), } } /// The releases list (newest first). Unlike `releases/latest`, this includes /// pre-releases, so an early/bench channel is still found by `--latest`. fn api_list(&self) -> String { - format!( - "{}/api/v1/repos/{}/{}/releases?limit=50", - self.base_url.trim_end_matches('/'), - self.owner, - self.repo - ) + let base = self.base_url.trim_end_matches('/'); + if self.github { + format!( + "{}/repos/{}/{}/releases?per_page=50", + base, self.owner, self.repo + ) + } else { + format!( + "{}/api/v1/repos/{}/{}/releases?limit=50", + base, self.owner, self.repo + ) + } } } @@ -174,7 +284,10 @@ fn write_private(path: &Path, contents: &str) -> Result<(), FetchError> { fn curl_bytes(src: &ReleaseSource, url: &str) -> Result, FetchError> { let config = TokenConfig::new(&src.token)?; let mut cmd = Command::new("curl"); - cmd.arg("-fsSL").arg("--max-time").arg("120"); + // A generic User-Agent (GitHub's API rejects requests without one); never + // carries any operator/host detail. + cmd.arg("-fsSL").arg("-A").arg("alkane-toolkit"); + cmd.arg("--max-time").arg("120"); config.apply(&mut cmd); cmd.arg(url); let out = cmd.output().map_err(|e| FetchError::Curl(e.to_string()))?; @@ -192,6 +305,8 @@ fn curl_download(src: &ReleaseSource, url: &str, dest: &Path) -> Result<(), Fetc let config = TokenConfig::new(&src.token)?; let mut cmd = Command::new("curl"); cmd.arg("-fsSL") + .arg("-A") + .arg("alkane-toolkit") .arg("--max-time") .arg("600") .arg("-o") @@ -380,6 +495,54 @@ pub fn fetch_afw_url( mod tests { use super::*; + #[test] + fn from_url_parses_gitea_github_and_bare() { + std::env::remove_var("ALKANE_RELEASE_BASE"); + // Bare owner/repo -> default gitea. + let g = ReleaseSource::from_url("someone/alkane-os").unwrap(); + assert_eq!( + (g.owner.as_str(), g.repo.as_str()), + ("someone", "alkane-os") + ); + assert!( + !g.github + && g.api_list() + .contains("gitea.bluefla.re/api/v1/repos/someone/alkane-os") + ); + + // Full gitea URL on the default host keeps the token path + gitea API. + let gh = ReleaseSource::from_url("https://gitea.bluefla.re/blueflare/alkane-os").unwrap(); + assert!(!gh.github && gh.api_list().contains("/api/v1/repos/blueflare/alkane-os")); + + // GitHub URL -> api.github.com, github path, and NEVER a token. + let h = ReleaseSource::from_url("https://github.com/acme/alkane-os.git/releases").unwrap(); + assert!(h.github); + assert!( + h.token.is_none(), + "must not attach the gitea token to github" + ); + assert_eq!( + h.api_list(), + "https://api.github.com/repos/acme/alkane-os/releases?per_page=50" + ); + + // Another gitea host -> no token (not the trusted host), gitea path. + let other = ReleaseSource::from_url("https://git.example.org/u/r").unwrap(); + assert!(!other.github && other.token.is_none()); + assert!(other + .api_list() + .starts_with("https://git.example.org/api/v1/repos/u/r")); + + // Asset download token only for the trusted host. + assert!(ReleaseSource::for_asset_url( + "https://github.com/acme/r/releases/download/v1/x.afw" + ) + .token + .is_none()); + assert!(ReleaseSource::from_url("").is_none()); + assert!(ReleaseSource::from_url("justonepart").is_none()); + } + #[test] fn source_defaults_to_alkane_os_on_gitea() { std::env::remove_var("ALKANE_RELEASE_BASE"); diff --git a/crates/alkane-cli/src/main.rs b/crates/alkane-cli/src/main.rs index 513c1e21..33b17bc0 100644 --- a/crates/alkane-cli/src/main.rs +++ b/crates/alkane-cli/src/main.rs @@ -1388,9 +1388,118 @@ fn run_restore_onboard(args: &[String]) -> Result<(), Box Ok(()) } +/// Build a bootable SD installation-media card image (and optionally write it to +/// a device). Zynq-7010 only for now. +/// +/// afw make-media --kind stock --stock-package --out card.img +/// afw make-media --kind alkane --mode simpleboot|installer --afw --out card.img +/// [--allow-unsigned] [--write /dev/sdX --confirm WRITE] +fn run_make_media(args: &[String]) -> Result<(), Box> { + use alkane_flash::sd_media; + let opts = parse_args( + args, + &[ + "kind", + "mode", + "afw", + "stock-package", + "board", + "out", + "write", + "confirm", + "expect-board", + ], + &["allow-unsigned"], + )?; + let kind = opts + .value("kind") + .ok_or("usage: alkane-cli afw make-media --kind ... --out ")?; + let board = opts.value("board").unwrap_or("zynq-7010"); + if board != "zynq-7010" { + return Err(format!("make-media supports --board zynq-7010 only (got {board})").into()); + } + let out = opts + .value("out") + .map(PathBuf::from) + .or_else(|| opts.positionals.first().map(PathBuf::from)) + .ok_or("make-media: --out required")?; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as u32) + .unwrap_or(0); + + match kind { + "stock" => { + let pkg = opts + .value("stock-package") + .ok_or("make-media --kind stock needs --stock-package ")?; + let pkg_path = Path::new(pkg); + // Unpack a .zip to an ephemeral dir; use a directory as-is. + let staged; + let dir: PathBuf = if pkg_path.is_dir() { + pkg_path.to_path_buf() + } else if pkg_path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("zip")) + { + staged = + std::env::temp_dir().join(format!("alkane-media-pkg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&staged); + std::fs::create_dir_all(&staged)?; + let status = std::process::Command::new("unzip") + .args(["-o", "-q"]) + .arg(pkg_path) + .arg("-d") + .arg(&staged) + .status()?; + if !status.success() { + return Err(format!("unzip {pkg} failed").into()); + } + staged + } else { + return Err( + format!("--stock-package must be a directory or a .zip (got {pkg})").into(), + ); + }; + sd_media::build_stock_recovery_card(&dir, &out)?; + } + "alkane" => { + let afw_path = opts + .value("afw") + .ok_or("make-media --kind alkane needs --afw ")?; + let verified = load_afw(afw_path, &opts)?; + match opts.value("mode").unwrap_or("simpleboot") { + "simpleboot" | "simple-boot" => { + sd_media::build_zynq_simpleboot_card(&verified, &out, now)? + } + "installer" => sd_media::build_zynq_installer_card(&verified, &out, now)?, + other => { + return Err(format!("--mode must be simpleboot|installer (got {other})").into()) + } + } + } + other => return Err(format!("--kind must be stock|alkane (got {other})").into()), + } + println!("wrote card image: {}", out.display()); + + if let Some(dev) = opts.value("write") { + if opts.value("confirm") != Some("WRITE") { + return Err(format!( + "refusing to write to {dev} without --confirm WRITE (card image is at {})", + out.display() + ) + .into()); + } + eprintln!("writing {} to {dev} ...", out.display()); + sd_media::write_image_to_device(&out, Path::new(dev))?; + println!("written to {dev}; sync complete"); + } + Ok(()) +} + fn run_afw(args: &[String]) -> Result<(), Box> { let subcommand = args.first().ok_or( - "usage: alkane-cli afw ", + "usage: alkane-cli afw ", )?; let rest = &args[1..]; match subcommand.as_str() { @@ -1413,6 +1522,7 @@ fn run_afw(args: &[String]) -> Result<(), Box> { "nand-restore-stock" => run_nand_restore_stock(rest), "nand-backup-check" => run_nand_backup_check(rest), "nand-restore-onboard" => run_nand_restore_onboard(rest), + "make-media" => run_make_media(rest), other => Err(format!("unknown afw subcommand {other}").into()), } } diff --git a/crates/alkane-flash/src/lib.rs b/crates/alkane-flash/src/lib.rs index a5bb293a..a479dc8b 100644 --- a/crates/alkane-flash/src/lib.rs +++ b/crates/alkane-flash/src/lib.rs @@ -16,6 +16,7 @@ pub mod boards; pub mod install; pub mod md5; pub mod preflight; +pub mod sd_media; pub mod stock; pub mod stock_firmware; pub mod uimage; diff --git a/crates/alkane-flash/src/sd_media.rs b/crates/alkane-flash/src/sd_media.rs new file mode 100644 index 00000000..ce84e603 --- /dev/null +++ b/crates/alkane-flash/src/sd_media.rs @@ -0,0 +1,968 @@ +// SPDX-License-Identifier: MIT +//! Build bootable SD / removable-media card *images* for control boards that +//! boot from a card, and (separately, guarded) write a finished image to a +//! physical device. +//! +//! Everything here is **network-free and root-free up to the final device +//! write**: a card image is assembled as an ordinary file using `sfdisk` +//! (partition table), `mkfs.vfat` (FAT32 filesystem) and `mtools` +//! (`mcopy`/`mmd`, which populate a FAT image with no loopback mount and no +//! root). The resulting `.img` is byte-for-byte what lands on the card, so it +//! is fully inspectable and unit-testable without hardware. Only +//! [`write_image_to_device`] touches a real block device, and it is deliberately +//! kept apart so a caller confirms the target first. +//! +//! The card layout this produces is the one proven on a bench Antminer S17 +//! (2026-11-17): a single MBR primary FAT32 partition (type 0x0c) starting at +//! LBA 2048. On the Zynq boards the stock U-Boot card-detects such a card and +//! side-loads the flasher-OS trio (`uImage` / `devicetree.dtb` / +//! `uramdisk.image.gz`) from its root -- no boot-mode strap and no `uEnv.txt` +//! required (see `alkane-sdk-construction: zynq-s17-recovery.md`). + +use crate::uimage::{self, Kind}; +use alkane_artifacts::afw::VerifiedAfw; +use std::fmt; +use std::fs; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Partition starts at LBA 2048 (1 MiB) -- the conventional alignment, and what +/// the proven S17 card used. +const PART_LBA: u64 = 2048; + +/// Zynq-7010 absolute NAND boot-slot offsets the installer writes (mirror of +/// `zynq_nand`; BOOT.bin at 0x0..0x1a00000 is never touched). +const ZYNQ_OFF_DTB: u64 = 0x1a00000; +const ZYNQ_OFF_KERNEL: u64 = 0x2000000; +const ZYNQ_OFF_ROOTFS: u64 = 0x2800000; +const SECTOR: u64 = 512; +const PART_OFFSET_BYTES: u64 = PART_LBA * SECTOR; + +#[derive(Debug)] +pub enum MediaError { + /// A required external tool (`sfdisk` / `mkfs.vfat` / an mtools binary) was + /// not found on the system. + MissingTool(String), + /// A source file or directory the card needs is absent. + MissingSource(String), + /// A vendor package did not contain a recognisable card layout. + BadPackage(String), + /// An external command exited non-zero; carries a short diagnostic. + Command(String), + Io(std::io::Error), +} + +impl fmt::Display for MediaError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MediaError::MissingTool(t) => write!(f, "required tool not found: {t}"), + MediaError::MissingSource(s) => write!(f, "missing source: {s}"), + MediaError::BadPackage(s) => write!(f, "unrecognised package layout: {s}"), + MediaError::Command(s) => write!(f, "{s}"), + MediaError::Io(e) => write!(f, "io: {e}"), + } + } +} + +impl std::error::Error for MediaError {} + +impl From for MediaError { + fn from(e: std::io::Error) -> Self { + MediaError::Io(e) + } +} + +type Result = std::result::Result; + +/// Find an executable by name, searching `PATH` plus the usual `sbin` +/// directories (`mkfs.vfat` / `sfdisk` live in `/sbin` or `/usr/sbin`, which are +/// often absent from a GUI process's `PATH`). +fn find_tool(name: &str) -> Result { + if let Ok(path) = std::env::var("PATH") { + for dir in std::env::split_paths(&path) { + let p = dir.join(name); + if p.is_file() { + return Ok(p); + } + } + } + for dir in ["/sbin", "/usr/sbin", "/usr/local/sbin", "/bin", "/usr/bin"] { + let p = Path::new(dir).join(name); + if p.is_file() { + return Ok(p); + } + } + Err(MediaError::MissingTool(name.to_string())) +} + +fn run(mut cmd: Command, what: &str) -> Result<()> { + let out = cmd + .output() + .map_err(|e| MediaError::Command(format!("{what}: failed to launch: {e}")))?; + if !out.status.success() { + let mut msg = format!("{what}: exit {:?}", out.status.code()); + let err = String::from_utf8_lossy(&out.stderr); + let err = err.trim(); + if !err.is_empty() { + msg.push_str(": "); + msg.push_str(err.lines().next_back().unwrap_or(err)); + } + return Err(MediaError::Command(msg)); + } + Ok(()) +} + +/// A FAT32 card image under construction: a single MBR primary partition that +/// mtools populates through a private config file (no mount, no root). +pub struct CardImage { + img: PathBuf, + mtoolsrc: PathBuf, + mcopy: PathBuf, + mmd: PathBuf, + _tmp: Option, +} + +impl CardImage { + /// Create a new `size_mb`-megabyte image at `img_path`, partition it with a + /// single FAT32 (type 0x0c) partition at LBA 2048, format that partition + /// FAT32 with the given volume `label` (upper-cased, <= 11 chars), and + /// prepare mtools to write into it. + pub fn create(img_path: &Path, size_mb: u64, label: &str) -> Result { + let sfdisk = find_tool("sfdisk")?; + let mkfs = find_tool("mkfs.vfat")?; + let mcopy = find_tool("mcopy")?; + let mmd = find_tool("mmd")?; + + // 1. Zero-filled image of the requested size. + let f = fs::File::create(img_path)?; + f.set_len(size_mb.saturating_mul(1024 * 1024))?; + drop(f); + + // 2. MBR: one primary FAT32 (LBA) partition from sector 2048 to the end. + { + let mut cmd = Command::new(&sfdisk); + cmd.arg(img_path).stdin(std::process::Stdio::piped()); + cmd.stdout(std::process::Stdio::null()); + cmd.stderr(std::process::Stdio::piped()); + let mut child = cmd + .spawn() + .map_err(|e| MediaError::Command(format!("sfdisk: {e}")))?; + { + let stdin = child + .stdin + .as_mut() + .ok_or_else(|| MediaError::Command("sfdisk: no stdin".to_string()))?; + writeln!(stdin, "label: dos")?; + writeln!(stdin, "start={PART_LBA}, type=0c")?; + } + let out = child + .wait_with_output() + .map_err(|e| MediaError::Command(format!("sfdisk: {e}")))?; + if !out.status.success() { + return Err(MediaError::Command(format!( + "sfdisk: {}", + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + } + + // 3. Format the partition region (no root) via mkfs.vfat --offset. + let label = sanitize_label(label); + let mut cmd = Command::new(&mkfs); + cmd.args(["-F", "32", "-n", &label, "--offset"]) + .arg(PART_LBA.to_string()) + .arg(img_path) + .stdout(std::process::Stdio::null()); + run(cmd, "mkfs.vfat")?; + + // 4. Private mtools config mapping drive C: to the partition region. + let tmp = tempdir::TempHold::new()?; + let mtoolsrc = tmp.path().join("mtools.conf"); + { + let mut mf = fs::File::create(&mtoolsrc)?; + writeln!( + mf, + "drive C: file=\"{}\" offset={}", + img_path.display(), + PART_OFFSET_BYTES + )?; + } + + Ok(CardImage { + img: img_path.to_path_buf(), + mtoolsrc, + mcopy, + mmd, + _tmp: Some(tmp), + }) + } + + fn mtools_cmd(&self, tool: &Path) -> Command { + let mut cmd = Command::new(tool); + cmd.env("MTOOLSRC", &self.mtoolsrc); + cmd.env("MTOOLS_SKIP_CHECK", "1"); + cmd + } + + /// Create a directory on the card, e.g. `bin`. Tolerates "already exists". + pub fn mkdir(&self, dest: &str) -> Result<()> { + let path = format!("C:/{}", dest.trim_start_matches('/')); + let out = self + .mtools_cmd(&self.mmd) + .arg(&path) + .output() + .map_err(|e| MediaError::Command(format!("mmd: {e}")))?; + if out.status.success() { + return Ok(()); + } + let err = String::from_utf8_lossy(&out.stderr); + if err.to_lowercase().contains("already exists") { + Ok(()) + } else { + Err(MediaError::Command(format!("mmd {dest}: {}", err.trim()))) + } + } + + /// Copy a local file onto the card at `dest` (a card-relative path like + /// `uImage` or `bin/BOOT.bin`). Overwrites. + pub fn copy_file(&self, local: &Path, dest: &str) -> Result<()> { + if !local.is_file() { + return Err(MediaError::MissingSource(local.display().to_string())); + } + let mut cmd = self.mtools_cmd(&self.mcopy); + cmd.arg("-o") // overwrite without prompting + .arg(local) + .arg(format!("C:/{}", dest.trim_start_matches('/'))); + run(cmd, &format!("mcopy {}", local.display())) + } + + /// Copy an entire local directory's contents onto the card under `dest` + /// (created if needed). Recurses. + pub fn copy_dir(&self, local: &Path, dest: &str) -> Result<()> { + if !local.is_dir() { + return Err(MediaError::MissingSource(local.display().to_string())); + } + self.mkdir(dest)?; + for entry in fs::read_dir(local)? { + let entry = entry?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + let child_dest = format!("{}/{}", dest.trim_end_matches('/'), name); + if entry.file_type()?.is_dir() { + self.copy_dir(&entry.path(), &child_dest)?; + } else { + self.copy_file(&entry.path(), &child_dest)?; + } + } + Ok(()) + } + + /// Write a byte buffer onto the card at `dest`, staging through a temp file + /// (mtools copies from the filesystem, not stdin). + pub fn write_bytes(&self, bytes: &[u8], dest: &str) -> Result<()> { + use std::sync::atomic::{AtomicU64, Ordering}; + static CTR: AtomicU64 = AtomicU64::new(0); + let n = CTR.fetch_add(1, Ordering::Relaxed); + let staged = std::env::temp_dir().join(format!( + "alkane-media-stage-{}-{}.bin", + std::process::id(), + n + )); + fs::write(&staged, bytes)?; + let r = self.copy_file(&staged, dest); + let _ = fs::remove_file(&staged); + r + } + + /// The finished image path. + pub fn path(&self) -> &Path { + &self.img + } +} + +/// Upper-case and clamp a FAT volume label to 11 chars; empty becomes `ALKANE`. +fn sanitize_label(label: &str) -> String { + let up: String = label + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-') + .take(11) + .collect::() + .to_ascii_uppercase(); + if up.is_empty() { + "ALKANE".to_string() + } else { + up + } +} + +/// A located vendor SD-recovery card layout: the flasher-OS trio at the package +/// root plus the `bin/` NAND payload directory. +pub struct VendorCardLayout { + /// Directory holding `uImage`, `devicetree.dtb`, `uramdisk.image.gz` and + /// `bin/`. + pub root: PathBuf, +} + +/// Locate the card layout inside an unpacked vendor SD-recovery package. Vendor +/// zips often nest the real card directory one or two levels deep (e.g. +/// `sd_set_default_password_enhanced_0527_S17/.../`). Accept the shallowest +/// directory that contains all three root-level flasher files and a `bin/`. +pub fn locate_vendor_card(unpacked_root: &Path) -> Result { + fn has_layout(dir: &Path) -> bool { + dir.join("uImage").is_file() + && dir.join("devicetree.dtb").is_file() + && dir.join("uramdisk.image.gz").is_file() + && dir.join("bin").is_dir() + } + // Breadth-first to prefer the shallowest match. + let mut queue = vec![unpacked_root.to_path_buf()]; + let mut depth_guard = 0; + while let Some(dir) = queue.first().cloned() { + queue.remove(0); + if has_layout(&dir) { + return Ok(VendorCardLayout { root: dir }); + } + depth_guard += 1; + if depth_guard > 4096 { + break; + } + if let Ok(rd) = fs::read_dir(&dir) { + for e in rd.flatten() { + if e.file_type().map(|t| t.is_dir()).unwrap_or(false) { + queue.push(e.path()); + } + } + } + } + Err(MediaError::BadPackage(format!( + "no flasher-OS trio (uImage/devicetree.dtb/uramdisk.image.gz) + bin/ found under {}", + unpacked_root.display() + ))) +} + +/// Build a genuine-vendor **stock-recovery** card image from an already-unpacked +/// vendor SD-recovery package directory. The card is a single FAT32 partition +/// carrying the vendor layout verbatim: flasher-OS trio at the root plus the +/// `bin/` NAND payload. This is the toolkit codification of the procedure proven +/// by hand on the bench S17 (2026-11-17). +/// +/// `unpacked_pkg` is a directory (the caller unpacks a `.zip`/`.tar.gz` first, +/// reusing [`crate::stock_firmware`]'s extraction helpers or `unzip`). The +/// finished image is written to `out_img`. +pub fn build_stock_recovery_card(unpacked_pkg: &Path, out_img: &Path) -> Result<()> { + let layout = locate_vendor_card(unpacked_pkg)?; + let root = &layout.root; + + // Size the card to comfortably hold the payload (flasher ~45 MB + bin ~34 MB) + // with slack, rounded up; a 256 MiB card is plenty and small to write/verify. + let card = CardImage::create(out_img, 256, "ANTMINER")?; + + for f in ["uImage", "devicetree.dtb", "uramdisk.image.gz"] { + card.copy_file(&root.join(f), f)?; + } + // README.md is harmless vendor documentation; include it if present. + let readme = root.join("README.md"); + if readme.is_file() { + card.copy_file(&readme, "README.md")?; + } + card.copy_dir(&root.join("bin"), "bin")?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// Alkane media (Zynq-7010 first). The card is the same FAT32 side-load shape as +// the vendor recovery: the stock (or our) U-Boot card-detects it and boots the +// `uImage` / `devicetree.dtb` / `uramdisk.image.gz` trio at the card root. The +// difference is only *what* that trio is and whether an installer action runs. +// --------------------------------------------------------------------------- + +/// Pull the three Zynq boot components out of a verified `.afw` (`kernel` +/// zImage, `dtb` fdt, `rootfs` cpio-gzip). Mirrors `boards::zynq`'s roles. +fn zynq_afw_parts(afw: &VerifiedAfw) -> Result<(&[u8], &[u8], &[u8])> { + let get = |role: &str| { + afw.image(role) + .map(|(_, data)| data) + .ok_or_else(|| MediaError::BadPackage(format!("afw missing {role} image"))) + }; + Ok((get("kernel")?, get("dtb")?, get("rootfs")?)) +} + +/// Wrap the raw afw components into the Zynq card side-load trio: +/// (`uImage` = legacy-uImage-wrapped kernel, raw `devicetree.dtb`, +/// `uramdisk.image.gz` = legacy-uImage-wrapped rootfs). `bootm` on the stock +/// U-Boot expects uImage-wrapped kernel and ramdisk; the dtb is raw. +fn zynq_sideload_trio( + kernel_zimage: &[u8], + fdt: &[u8], + rootfs_cpio_gz: &[u8], + time: u32, +) -> (Vec, Vec, Vec) { + ( + uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane"), + fdt.to_vec(), + uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, time, "alkane-rootfs"), + ) +} + +/// Build an alkane **simple-boot** card for a Zynq board from raw afw parts: the +/// card runs alkane from RAM each boot (nothing is written to the board's NAND). +/// Good for a non-destructive try-out or a permanently SD-run board. +pub fn build_zynq_simpleboot_card_from_parts( + kernel_zimage: &[u8], + fdt: &[u8], + rootfs_cpio_gz: &[u8], + out_img: &Path, + time: u32, +) -> Result<()> { + let (uimg, dtb, urd) = zynq_sideload_trio(kernel_zimage, fdt, rootfs_cpio_gz, time); + let card = CardImage::create(out_img, 256, "ALKANE")?; + card.write_bytes(&uimg, "uImage")?; + card.write_bytes(&dtb, "devicetree.dtb")?; + card.write_bytes(&urd, "uramdisk.image.gz")?; + Ok(()) +} + +/// Build an alkane simple-boot card from a verified `.afw`. +pub fn build_zynq_simpleboot_card(afw: &VerifiedAfw, out_img: &Path, time: u32) -> Result<()> { + let (k, d, r) = zynq_afw_parts(afw)?; + build_zynq_simpleboot_card_from_parts(k, d, r, out_img, time) +} + +/// The install hook the Zynq installer-OS runs on boot. It writes the alkane +/// boot slots carried in the card's `bin/` to NAND -- BOOT.bin (0x0..0x1a00000) +/// is never touched -- verifies by read-back, and drives the board's red/green +/// LEDs (GPIO 941 red / 942 green, confirmed on the bench S17): a steady +/// green-on/red-off "done, safe to remove" on success, red-on on failure. The +/// script uses only tools present in the alkane rootfs (busybox, mtd-utils). +/// +/// This is the board-specific part; offsets mirror `zynq_nand`. On-hardware +/// behaviour is validated on the bench S17. +fn zynq_install_script() -> String { + // LED GPIO numbers for the Zynq S17 control board (sysfs). 941 red, 942 green. + format!( + r#"#!/bin/sh +# alkane SD installer hook (Zynq-7010). Runs once on boot from the installer +# initramfs, writes the alkane boot slots from the card's bin/ to NAND, then +# signals the LEDs. BOOT.bin is never written. +set -e +LED_RED=941 +LED_GRN=942 +CARD=/mnt/alkane-card +MTD=/dev/mtd0 # the device covering the boot region; resolved below +OFF_DTB=0x{off_dtb:x} +OFF_KERNEL=0x{off_kernel:x} +OFF_ROOTFS=0x{off_rootfs:x} +ERASE=0x20000 + +led_setup() {{ + for g in $LED_RED $LED_GRN; do + [ -d /sys/class/gpio/gpio$g ] || echo $g > /sys/class/gpio/export 2>/dev/null || true + echo out > /sys/class/gpio/gpio$g/direction 2>/dev/null || true + done +}} +led() {{ echo "$2" > /sys/class/gpio/gpio$1/value 2>/dev/null || true; }} +fail() {{ led_setup; led $LED_RED 1; led $LED_GRN 0; echo "alkane-sd-install FAILED: $1" >&2; exit 1; }} + +led_setup; led $LED_RED 1; led $LED_GRN 1 # both on = working + +mkdir -p $CARD +mount -t vfat /dev/mmcblk0p1 $CARD 2>/dev/null || mount /dev/mmcblk0p1 $CARD || fail "mount card" + +# The boot region lives in mtd0 on this board; write absolute offsets with +# flash_erase + nandwrite (same physical NAND the network installer targets). +write_slot() {{ # name file abs_offset + f="$CARD/bin/$2" + [ -s "$f" ] || fail "missing $2 on card" + flash_erase $MTD $3 0 >/dev/null 2>&1 || fail "erase $1" + nandwrite -p -s $3 $MTD "$f" >/dev/null 2>&1 || fail "write $1" +}} +write_slot dtb devicetree.dtb $OFF_DTB +write_slot kernel uImage $OFF_KERNEL +write_slot rootfs uramdisk.image.gz $OFF_ROOTFS + +sync +umount $CARD 2>/dev/null || true + +# Success: solid green, red off -> safe to power off and remove the card. +led $LED_RED 0; led $LED_GRN 1 +echo "alkane-sd-install: done -- remove the card and reboot into alkane" >&2 +# Blink green to make "done" unmistakable, matching the vendor flasher's cue. +while true; do led $LED_GRN 1; sleep 1; led $LED_GRN 0; sleep 1; done +"#, + off_dtb = ZYNQ_OFF_DTB, + off_kernel = ZYNQ_OFF_KERNEL, + off_rootfs = ZYNQ_OFF_ROOTFS, + ) +} + +/// Build the installer initramfs by injecting the install hook into the afw +/// rootfs cpio.gz as a BusyBox-init start script (`/etc/init.d/S99alkane-sd-install`) +/// and recompressing. Uses `gzip`/`cpio` (newc format, standard initramfs). +fn build_installer_initramfs(rootfs_cpio_gz: &[u8], script: &str) -> Result> { + let gzip = find_tool("gzip")?; + let gunzip = find_tool("gunzip").or_else(|_| find_tool("gzip"))?; + let cpio = find_tool("cpio")?; + let work = tempdir::TempHold::new()?; + let root = work.path().join("root"); + fs::create_dir_all(root.join("etc/init.d"))?; + + // 1. Decompress + unpack the afw rootfs into `root/`. + let gz_path = work.path().join("rootfs.cpio.gz"); + fs::write(&gz_path, rootfs_cpio_gz)?; + let cpio_path = work.path().join("rootfs.cpio"); + { + // gunzip -c rootfs.cpio.gz > rootfs.cpio + let out = Command::new(&gunzip) + .arg("-c") + .arg(&gz_path) + .output() + .map_err(|e| MediaError::Command(format!("gunzip: {e}")))?; + if !out.status.success() { + return Err(MediaError::Command("gunzip rootfs failed".into())); + } + fs::write(&cpio_path, &out.stdout)?; + } + { + // cd root && cpio -idm < ../rootfs.cpio + let cpio_in = fs::File::open(&cpio_path)?; + let status = Command::new(&cpio) + .args(["-i", "-d", "-m", "--no-absolute-filenames"]) + .current_dir(&root) + .stdin(cpio_in) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .map_err(|e| MediaError::Command(format!("cpio -i: {e}")))?; + if !status.success() { + return Err(MediaError::Command("cpio unpack failed".into())); + } + } + + // 2. Inject the install hook, executable. + let hook = root.join("etc/init.d/S99alkane-sd-install"); + fs::write(&hook, script.as_bytes())?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&hook, fs::Permissions::from_mode(0o755))?; + } + + // 3. Repack: (cd root && find . | cpio -o -H newc) | gzip + let repacked_cpio = { + let find = Command::new(find_tool("find")?) + .arg(".") + .current_dir(&root) + .output() + .map_err(|e| MediaError::Command(format!("find: {e}")))?; + if !find.status.success() { + return Err(MediaError::Command("find failed".into())); + } + let mut child = Command::new(&cpio) + .args(["-o", "-H", "newc"]) + .current_dir(&root) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() + .map_err(|e| MediaError::Command(format!("cpio -o: {e}")))?; + child + .stdin + .take() + .ok_or_else(|| MediaError::Command("cpio -o: no stdin".into()))? + .write_all(&find.stdout)?; + let out = child + .wait_with_output() + .map_err(|e| MediaError::Command(format!("cpio -o: {e}")))?; + if !out.status.success() { + return Err(MediaError::Command("cpio repack failed".into())); + } + out.stdout + }; + let gz = { + let mut child = Command::new(&gzip) + .args(["-9", "-c"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() + .map_err(|e| MediaError::Command(format!("gzip: {e}")))?; + child + .stdin + .take() + .ok_or_else(|| MediaError::Command("gzip: no stdin".into()))? + .write_all(&repacked_cpio)?; + let out = child + .wait_with_output() + .map_err(|e| MediaError::Command(format!("gzip: {e}")))?; + if !out.status.success() { + return Err(MediaError::Command("gzip repack failed".into())); + } + out.stdout + }; + Ok(gz) +} + +/// Build an alkane **installer** card for a Zynq board from raw afw parts: it +/// boots an installer-OS (the afw rootfs + an install hook), writes alkane into +/// the board's NAND (BOOT.bin preserved), LED-signals "done", and halts so the +/// operator pulls the card and boots internal alkane. The boot trio runs the +/// installer-OS; the `bin/` payload is what the hook writes to NAND. +pub fn build_zynq_installer_card_from_parts( + kernel_zimage: &[u8], + fdt: &[u8], + rootfs_cpio_gz: &[u8], + out_img: &Path, + time: u32, +) -> Result<()> { + // Boot trio: alkane kernel + dtb + installer initramfs (rootfs + hook). + let installer_rd = build_installer_initramfs(rootfs_cpio_gz, &zynq_install_script())?; + let boot_uimage = uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane-installer"); + let boot_uramdisk = uimage::wrap(Kind::Ramdisk, &installer_rd, time, "alkane-installer-rd"); + + // NAND payload (bin/): exactly what gets written to the board's boot slots. + let nand_kernel = uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane"); + let nand_rootfs = uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, time, "alkane-rootfs"); + + let card = CardImage::create(out_img, 256, "ALKANEINST")?; + card.write_bytes(&boot_uimage, "uImage")?; + card.write_bytes(fdt, "devicetree.dtb")?; + card.write_bytes(&boot_uramdisk, "uramdisk.image.gz")?; + card.mkdir("bin")?; + card.write_bytes(&nand_kernel, "bin/uImage")?; + card.write_bytes(fdt, "bin/devicetree.dtb")?; + card.write_bytes(&nand_rootfs, "bin/uramdisk.image.gz")?; + Ok(()) +} + +/// Build an alkane installer card from a verified `.afw`. +pub fn build_zynq_installer_card(afw: &VerifiedAfw, out_img: &Path, time: u32) -> Result<()> { + let (k, d, r) = zynq_afw_parts(afw)?; + build_zynq_installer_card_from_parts(k, d, r, out_img, time) +} + +/// Write a finished card image to a block device with `dd`. **Destructive** -- +/// the caller is responsible for confirming `device` is the intended removable +/// card (never a system disk). This never runs as part of image building. +pub fn write_image_to_device(img: &Path, device: &Path) -> Result<()> { + if !img.is_file() { + return Err(MediaError::MissingSource(img.display().to_string())); + } + let dd = find_tool("dd")?; + let mut cmd = Command::new(dd); + cmd.arg(format!("if={}", img.display())) + .arg(format!("of={}", device.display())) + .arg("bs=4M") + .arg("oflag=direct") + .arg("conv=fsync"); + run(cmd, &format!("dd to {}", device.display())) +} + +/// A minimal owned temp directory that removes itself on drop (the crate avoids +/// pulling a tempdir dependency; this mirrors the small helper style used +/// elsewhere). +mod tempdir { + use std::path::{Path, PathBuf}; + + pub struct TempHold { + path: PathBuf, + } + + impl TempHold { + pub fn new() -> std::io::Result { + let base = std::env::temp_dir(); + // Unique-ish without pulling rand: pid + a monotonic counter. + use std::sync::atomic::{AtomicU64, Ordering}; + static CTR: AtomicU64 = AtomicU64::new(0); + let n = CTR.fetch_add(1, Ordering::Relaxed); + let dir = base.join(format!("alkane-media-{}-{}", std::process::id(), n)); + std::fs::create_dir_all(&dir)?; + Ok(TempHold { path: dir }) + } + pub fn path(&self) -> &Path { + &self.path + } + } + + impl Drop for TempHold { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(p: &Path, bytes: &[u8]) { + if let Some(parent) = p.parent() { + fs::create_dir_all(parent).unwrap(); + } + fs::write(p, bytes).unwrap(); + } + + /// Build a fake vendor SD-recovery package (nested like the real one) and + /// assemble a stock-recovery card image from it, then read the card back + /// with `mdir`/`mtype` and confirm the layout and content survived. + /// + /// Host-tool test: unix only. On a Windows target (incl. the Wine CI run) + /// the card-building tools are unix binaries that a Windows process cannot + /// exec, and `find_tool` would see them as present in the shared container + /// filesystem, so these are cfg'd out rather than skipped at runtime. + #[cfg(unix)] + #[test] + fn builds_a_stock_recovery_card_from_a_vendor_package() { + // Skip cleanly if the host lacks the tools (keeps CI green where the + // image toolchain is unavailable; the alkane-ci image carries them). + for t in ["sfdisk", "mkfs.vfat", "mcopy", "mmd", "mdir", "mtype"] { + if find_tool(t).is_err() { + eprintln!("skipping: {t} not available"); + return; + } + } + let tmp = tempdir::TempHold::new().unwrap(); + let pkg = tmp.path().join("SD_S17/inner"); + // Flasher-OS trio at the card root. + write(&pkg.join("uImage"), b"FLASHER-KERNEL-xxxxxxxx"); + write(&pkg.join("devicetree.dtb"), b"FLASHER-DTB"); + write(&pkg.join("uramdisk.image.gz"), b"FLASHER-RAMDISK"); + write(&pkg.join("README.md"), b"vendor notes"); + // bin/ NAND payload. + write(&pkg.join("bin/BOOT.bin"), b"BOOTBIN-PAYLOAD"); + write(&pkg.join("bin/devicetree.dtb"), b"MINER-DTB"); + write(&pkg.join("bin/uImage"), b"MINER-KERNEL"); + write(&pkg.join("bin/uramdisk.image.gz"), b"MINER-RAMDISK"); + write(&pkg.join("bin/passwd.txt"), b"root\n"); + + let out = tmp.path().join("card.img"); + build_stock_recovery_card(tmp.path(), &out).unwrap(); + assert!(out.is_file()); + + // Read the card back via mtools against the partition at offset 1 MiB. + let mtoolsrc = tmp.path().join("verify.conf"); + fs::write( + &mtoolsrc, + format!( + "drive C: file=\"{}\" offset={}\n", + out.display(), + PART_OFFSET_BYTES + ), + ) + .unwrap(); + let mdir = find_tool("mdir").unwrap(); + let listing = Command::new(&mdir) + .env("MTOOLSRC", &mtoolsrc) + .env("MTOOLS_SKIP_CHECK", "1") + .args(["-/", "C:/"]) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&listing.stdout); + for name in ["UIMAGE", "DEVICETREE", "URAMDISK", "BIN", "BOOT"] { + assert!( + text.to_uppercase().contains(name), + "card listing missing {name}:\n{text}" + ); + } + + // Content check: bin/BOOT.bin round-trips. + let mtype = find_tool("mtype").unwrap(); + let got = Command::new(&mtype) + .env("MTOOLSRC", &mtoolsrc) + .env("MTOOLS_SKIP_CHECK", "1") + .arg("C:/bin/BOOT.bin") + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&got.stdout).trim_end(), + "BOOTBIN-PAYLOAD" + ); + } + + #[test] + fn rejects_a_package_with_no_card_layout() { + let tmp = tempdir::TempHold::new().unwrap(); + write(&tmp.path().join("random/file.txt"), b"nope"); + let out = tmp.path().join("card.img"); + let err = build_stock_recovery_card(tmp.path(), &out).unwrap_err(); + assert!(matches!(err, MediaError::BadPackage(_))); + } + + #[test] + fn sanitizes_volume_labels() { + assert_eq!(sanitize_label("alkane install!!"), "ALKANEINSTA"); + assert_eq!(sanitize_label(""), "ALKANE"); + assert_eq!(sanitize_label("ANTMINER"), "ANTMINER"); + } + + #[cfg(unix)] + fn have_tools(tools: &[&str]) -> bool { + tools.iter().all(|t| find_tool(t).is_ok()) + } + + /// A minimal gzipped newc cpio containing `etc/` + a probe file, to stand in + /// for an afw rootfs in the installer-initramfs tests. + #[cfg(unix)] + fn fake_cpio_gz(dir: &Path) -> Vec { + fs::create_dir_all(dir.join("etc/init.d")).unwrap(); + fs::write(dir.join("probe"), b"hello-rootfs").unwrap(); + let find = Command::new(find_tool("find").unwrap()) + .arg(".") + .current_dir(dir) + .output() + .unwrap(); + let mut cpio = Command::new(find_tool("cpio").unwrap()) + .args(["-o", "-H", "newc"]) + .current_dir(dir) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap(); + cpio.stdin.take().unwrap().write_all(&find.stdout).unwrap(); + let archive = cpio.wait_with_output().unwrap().stdout; + let mut gz = Command::new(find_tool("gzip").unwrap()) + .args(["-c"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap(); + gz.stdin.take().unwrap().write_all(&archive).unwrap(); + gz.wait_with_output().unwrap().stdout + } + + #[cfg(unix)] + fn uimage_magic(bytes: &[u8]) -> bool { + bytes.len() >= 4 && bytes[0..4] == [0x27, 0x05, 0x19, 0x56] + } + + #[cfg(unix)] + fn mtype_bytes(img: &Path, card_path: &str) -> Vec { + let tmp = tempdir::TempHold::new().unwrap(); + let rc = tmp.path().join("rc"); + fs::write( + &rc, + format!( + "drive C: file=\"{}\" offset={}\n", + img.display(), + PART_OFFSET_BYTES + ), + ) + .unwrap(); + Command::new(find_tool("mtype").unwrap()) + .env("MTOOLSRC", &rc) + .env("MTOOLS_SKIP_CHECK", "1") + .arg(format!("C:/{card_path}")) + .output() + .unwrap() + .stdout + } + + #[cfg(unix)] + #[test] + fn injects_install_hook_into_initramfs() { + if !have_tools(&["cpio", "gzip", "gunzip", "find"]) { + eprintln!("skipping: cpio/gzip toolchain unavailable"); + return; + } + let tmp = tempdir::TempHold::new().unwrap(); + let src = fake_cpio_gz(&tmp.path().join("src")); + let out = + build_installer_initramfs(&src, "#!/bin/sh\necho alkane-sd-install marker\n").unwrap(); + + // Unpack the result and confirm the hook landed executable with content, + // and the original rootfs file survived. + let gz = tmp.path().join("out.cpio.gz"); + fs::write(&gz, &out).unwrap(); + let unz = Command::new(find_tool("gunzip").unwrap()) + .arg("-c") + .arg(&gz) + .output() + .unwrap(); + let cpio_f = tmp.path().join("out.cpio"); + fs::write(&cpio_f, &unz.stdout).unwrap(); + let ex = tmp.path().join("ex"); + fs::create_dir_all(&ex).unwrap(); + let st = Command::new(find_tool("cpio").unwrap()) + .args(["-i", "-d", "-m", "--no-absolute-filenames"]) + .current_dir(&ex) + .stdin(fs::File::open(&cpio_f).unwrap()) + .stderr(std::process::Stdio::null()) + .status() + .unwrap(); + assert!(st.success()); + let hook = ex.join("etc/init.d/S99alkane-sd-install"); + assert!( + hook.is_file(), + "install hook not present in repacked initramfs" + ); + assert!(fs::read_to_string(&hook) + .unwrap() + .contains("alkane-sd-install marker")); + assert!(ex.join("probe").is_file(), "original rootfs content lost"); + } + + #[cfg(unix)] + #[test] + fn builds_a_zynq_simpleboot_card() { + if !have_tools(&["sfdisk", "mkfs.vfat", "mcopy", "mmd", "mdir", "mtype"]) { + return; + } + let tmp = tempdir::TempHold::new().unwrap(); + let out = tmp.path().join("sb.img"); + build_zynq_simpleboot_card_from_parts( + b"ZIMAGE-KERNEL-BYTES", + b"ALKANE-FDT", + b"ROOTFS-CPIO-GZ", + &out, + 0, + ) + .unwrap(); + // uImage and uramdisk are legacy-uImage wrapped; dtb is raw. + assert!(uimage_magic(&mtype_bytes(&out, "uImage"))); + assert!(uimage_magic(&mtype_bytes(&out, "uramdisk.image.gz"))); + assert_eq!(mtype_bytes(&out, "devicetree.dtb"), b"ALKANE-FDT"); + } + + #[cfg(unix)] + #[test] + fn builds_a_zynq_installer_card() { + if !have_tools(&[ + "sfdisk", + "mkfs.vfat", + "mcopy", + "mmd", + "mdir", + "mtype", + "cpio", + "gzip", + "gunzip", + "find", + ]) { + return; + } + let tmp = tempdir::TempHold::new().unwrap(); + let rootfs = fake_cpio_gz(&tmp.path().join("src")); + let out = tmp.path().join("inst.img"); + build_zynq_installer_card_from_parts(b"ZIMAGE", b"FDT", &rootfs, &out, 0).unwrap(); + // Boot trio present (uImage-wrapped kernel + installer initramfs). + assert!(uimage_magic(&mtype_bytes(&out, "uImage"))); + assert!(uimage_magic(&mtype_bytes(&out, "uramdisk.image.gz"))); + // NAND payload under bin/ present and wrapped where expected. + assert!(uimage_magic(&mtype_bytes(&out, "bin/uImage"))); + assert!(uimage_magic(&mtype_bytes(&out, "bin/uramdisk.image.gz"))); + assert_eq!(mtype_bytes(&out, "bin/devicetree.dtb"), b"FDT"); + } + + #[test] + fn install_script_targets_the_boot_slots_and_preserves_bootbin() { + let s = zynq_install_script(); + assert!(s.contains("OFF_DTB=0x1a00000")); + assert!(s.contains("OFF_KERNEL=0x2000000")); + assert!(s.contains("OFF_ROOTFS=0x2800000")); + // BOOT.bin region (below 0x1a00000) must never be a write target. + assert!(!s.contains("0x0 ")); + assert!(s.contains("941") && s.contains("942")); // LED GPIOs + } +} diff --git a/crates/alkane-gui/assets/icons/bug.svg b/crates/alkane-gui/assets/icons/bug.svg new file mode 100644 index 00000000..42755354 --- /dev/null +++ b/crates/alkane-gui/assets/icons/bug.svg @@ -0,0 +1 @@ + diff --git a/crates/alkane-gui/assets/icons/database.svg b/crates/alkane-gui/assets/icons/database.svg new file mode 100644 index 00000000..ca7ad923 --- /dev/null +++ b/crates/alkane-gui/assets/icons/database.svg @@ -0,0 +1 @@ + diff --git a/crates/alkane-gui/assets/icons/gear.svg b/crates/alkane-gui/assets/icons/gear.svg new file mode 100644 index 00000000..f4d8406b --- /dev/null +++ b/crates/alkane-gui/assets/icons/gear.svg @@ -0,0 +1 @@ + diff --git a/crates/alkane-gui/assets/icons/sd-card.svg b/crates/alkane-gui/assets/icons/sd-card.svg new file mode 100644 index 00000000..eaca698b --- /dev/null +++ b/crates/alkane-gui/assets/icons/sd-card.svg @@ -0,0 +1 @@ + diff --git a/crates/alkane-gui/src/alkane_detect.rs b/crates/alkane-gui/src/alkane_detect.rs index 268f04c9..885f48bc 100644 --- a/crates/alkane-gui/src/alkane_detect.rs +++ b/crates/alkane-gui/src/alkane_detect.rs @@ -137,18 +137,93 @@ fn parse_http_json(raw: &[u8]) -> Option { serde_json::from_str(body.trim()).ok() } +/// Read the raw HTTP response head (status line + headers) of a GET on :80. +async fn http_response_head(ip: IpAddr, path: &str) -> Option { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let connect = tokio::net::TcpStream::connect((ip, 80)); + let mut stream = tokio::time::timeout(CONNECT_TIMEOUT, connect) + .await + .ok()? + .ok()?; + let request = format!("GET {path} HTTP/1.0\r\nHost: {ip}\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).await.ok()?; + let mut raw = Vec::new(); + let _ = tokio::time::timeout(READ_TIMEOUT, async { + let mut chunk = [0u8; 2048]; + loop { + match stream.read(&mut chunk).await { + Ok(0) | Err(_) => break, + Ok(n) => { + raw.extend_from_slice(&chunk[..n]); + if raw.windows(4).any(|w| w == b"\r\n\r\n") || raw.len() > 8192 { + break; + } + } + } + } + }) + .await; + let text = String::from_utf8_lossy(&raw); + let head = text.split("\r\n\r\n").next().unwrap_or("").to_string(); + (!head.is_empty()).then_some(head) +} + +/// A stock Antminer whose miner API (:4028) is down -- e.g. no hashboards, so +/// the miner software is not running -- still serves its vendor web UI on :80 +/// with a `Digest realm="antMiner Configuration"` challenge. asic-rs cannot +/// identify such a board without the API, so recognise it here. The control +/// board/model are unknown from :80 alone, so the row is marked stock with an +/// unknown board; the operator picks the control board when flashing. +pub async fn detect_stock_antminer(ip: IpAddr) -> Option { + let head = http_response_head(ip, "/").await?; + let lower = head.to_ascii_lowercase(); + let is_stock_antminer = lower.contains("antminer configuration") + || (lower.contains("server: lighttpd") && lower.contains(" 401 ")); + if !is_stock_antminer { + return None; + } + Some(MinerRow { + ip: ip.to_string(), + brand: "Antminer".to_string(), + model: "Stock (model unknown)".to_string(), + firmware: "Stock".to_string(), + ..Default::default() + }) +} + +/// A stock Antminer the scan could identify as such but whose control board is +/// unknown (e.g. found only by its :80 vendor web UI). Alkane can still be +/// installed once the operator picks the control board, so the install flow +/// offers it with a manual board selector. +pub fn is_unidentified_stock_antminer(row: &MinerRow) -> bool { + row.brand.to_ascii_lowercase().contains("antminer") + && row.firmware.eq_ignore_ascii_case("Stock") + && board_family(row).is_none() +} + /// Whether the row is a board running Alkane OS (found by `detect`). pub fn is_alkane(row: &MinerRow) -> bool { row.alkane_board.is_some() } /// The alkane-os board family the row's control board is, when it can be told: -/// what an Alkane board reports, or for a stock Antminer the Zynq-7010 (S17/T17 -/// era, "XIL (C49)") control board. +/// what an Alkane board reports, the stock Antminer Zynq-7010 (S17/T17 era, +/// "XIL (C49)") control board, or the stock Amlogic A113D ("AML (C76)") control +/// board. pub fn board_family(row: &MinerRow) -> Option { if let Some(board) = &row.alkane_board { return (!board.is_empty()).then(|| board.clone()); } + // A stock A113D (Amlogic AXG) control board -- the "a113d" install target + // (board_labels maps a113d -> "AML (C76)"). Decided on the control-board + // code, not the brand: asic-rs has no make for the Antminer BHB42XXX and + // reports its brand as "Unknown" (model "Unknown: ANTMINER BHB42XXX"), so + // the generic brand guard below would otherwise reject it. The "AML" code is + // only ever derived for an Amlogic Antminer control board, so this is + // specific on its own. + if row.cpu == "AML" && row.board_code == "C76" { + return Some("a113d".to_string()); + } if !row.brand.to_ascii_lowercase().contains("antminer") { return None; } @@ -175,6 +250,15 @@ pub fn install_supported(row: &MinerRow) -> bool { board_family(row).is_some_and(|board| crate::stock_ops::is_supported_board(&board)) } +/// Control boards that can boot from removable SD media, so the toolkit can +/// build an "Installation Media" card for them. Zynq-7010 is proven +/// (stock U-Boot card-detect side-load, confirmed on the bench S17 2026-11-17); +/// the Amlogic A113D is deliberately excluded -- it is eMMC-only with no SD slot +/// (USB recovery disabled), so it stays network-only. +pub fn media_supported(row: &MinerRow) -> bool { + matches!(board_family(row).as_deref(), Some("zynq-7010")) +} + #[cfg(test)] mod tests { use super::*; @@ -243,7 +327,10 @@ mod tests { assert!(install_supported(&s17)); assert!(!is_alkane(&s17)); assert!(!install_supported(&stock("XIL", "C55"))); // S19-era Zynq - assert!(!install_supported(&stock("AML", "C76"))); + // The Amlogic A113D control board is the "a113d" install target. + assert!(install_supported(&stock("AML", "C76"))); + assert_eq!(board_family(&stock("AML", "C76")).as_deref(), Some("a113d")); + assert!(!install_supported(&stock("AML", "CBE"))); // 140mm S19k/S21-class, not a target assert!(!install_supported(&stock("", ""))); let whatsminer = MinerRow { brand: "WhatsMiner".into(), @@ -274,7 +361,9 @@ mod tests { assert!(!install_supported(&other("S19"))); assert!(!install_supported(&other("S17+"))); assert!(!install_supported(&other(""))); - // A reported control board overrides the model. + // A reported control board overrides the model: an "S17" model on an + // Amlogic A113D control board resolves to a113d (the control board), + // not zynq (the model). let s17_on_aml = MinerRow { brand: "Antminer".into(), model: "S17".into(), @@ -282,7 +371,57 @@ mod tests { board_code: "C76".into(), ..Default::default() }; - assert!(!install_supported(&s17_on_aml)); + assert_eq!(board_family(&s17_on_aml).as_deref(), Some("a113d")); + } + + #[test] + fn an_unidentified_stock_antminer_is_flaggable_for_manual_board_install() { + // As detect_stock_antminer builds it: brand Antminer, Stock, no control + // board (found only by its :80 web UI). + let row = MinerRow { + brand: "Antminer".into(), + model: "Stock (model unknown)".into(), + firmware: "Stock".into(), + ..Default::default() + }; + assert!(is_unidentified_stock_antminer(&row)); + assert!(board_family(&row).is_none()); + assert!(!is_alkane(&row)); + // A board with a known control board is NOT "unidentified". + let s17 = MinerRow { + brand: "Antminer".into(), + firmware: "Stock".into(), + cpu: "XIL".into(), + board_code: "C49".into(), + ..Default::default() + }; + assert!(!is_unidentified_stock_antminer(&s17)); + // A non-Antminer is never flagged. + let wm = MinerRow { + brand: "WhatsMiner".into(), + firmware: "Stock".into(), + ..Default::default() + }; + assert!(!is_unidentified_stock_antminer(&wm)); + } + + #[test] + fn a_stock_a113d_bhb42xxx_is_an_install_target_despite_unknown_brand() { + // Exactly as the live scan reports the bench A113D at 10.255.1.18: + // asic-rs cannot pin a make, so brand is "Unknown" and the model is + // "Unknown: ANTMINER BHB42XXX", but the control board classifies as + // "AML (C76)". Install must still be offered. + let bhb = MinerRow { + brand: "Unknown".into(), + model: "Unknown: ANTMINER BHB42XXX".into(), + firmware: "Stock".into(), + cpu: "AML".into(), + board_code: "C76".into(), + ..Default::default() + }; + assert_eq!(board_family(&bhb).as_deref(), Some("a113d")); + assert!(install_supported(&bhb)); + assert!(!is_alkane(&bhb)); } /// Live check against a real board: diff --git a/crates/alkane-gui/src/bench_sequence.rs b/crates/alkane-gui/src/bench_sequence.rs index d251d8e9..b945a42e 100644 --- a/crates/alkane-gui/src/bench_sequence.rs +++ b/crates/alkane-gui/src/bench_sequence.rs @@ -216,6 +216,136 @@ fn wait_for( } } +/// Run the real fleet scan over `range` and report how each board classifies -- +/// the scan step a user performs before acting. Returns the rows found. +fn scan_report(range: &str) -> Vec { + use crate::scan::{self, ScanMsg}; + println!(" [scan] scanning {range} ..."); + let handle = scan::start_scan(vec![range.to_string()], 10); + let mut rows = Vec::new(); + loop { + match handle.rx.recv() { + Ok(ScanMsg::Row(r)) => rows.push(r), + Ok(ScanMsg::Done(_)) | Ok(ScanMsg::Failed(_)) => break, + Ok(_) => {} + Err(_) => break, + } + } + rows.sort_by(|a, b| a.ip.cmp(&b.ip)); + if rows.is_empty() { + println!(" [scan] no boards found"); + } + for r in &rows { + let installable = crate::alkane_detect::install_supported(r) + || crate::alkane_detect::is_unidentified_stock_antminer(r); + println!( + " [scan] {:<15} brand={:<10} model={:<22} fw={:<7} board={:<10} install={} alkane={}", + r.ip, + r.brand, + r.model, + r.firmware, + r.control_board, + installable, + crate::alkane_detect::is_alkane(r), + ); + } + rows +} + +/// A full user-flow test driven headlessly through the GUI engine, including the +/// scan step a user performs: scan -> restore to stock -> scan -> install -> +/// scan -> verify the board serves the API and shows as alkane. Spec: +/// ` [scan-range]`. +pub fn run_flow(spec: &str) -> i32 { + let mut it = spec.split_whitespace(); + let host = it.next().unwrap_or("").to_string(); + let afw = PathBuf::from(it.next().unwrap_or("")); + let range = it.next().unwrap_or("10.255.1.0/24").to_string(); + if host.is_empty() || afw.as_os_str().is_empty() { + eprintln!("ALKANE_BENCH_FLOW=\" [scan-range]\""); + return 2; + } + if !afw.exists() { + eprintln!("afw not found: {}", afw.display()); + return 2; + } + let stock_password = credentials::load_ssh_credentials().map(|(_, p)| p); + let alkane_password = std::env::var("ALKANE_ROOT_PASSWORD") + .ok() + .or_else(|| Some("alkane".to_string())); + let boot_timeout = Duration::from_secs(300); + + println!("== A113D full GUI-flow test (scan -> restore -> scan -> install -> scan) =="); + let mac = mac_of(&host); + + println!("\n[1/6] initial scan (as a user would)"); + scan_report(&range); + + let (desc, is_stock) = classify(&host); + println!("\n[2/6] target {host}: {desc}"); + if is_stock != Some(true) { + println!("[3/6] restore {host} -> stock (flag flip)"); + if !drive( + "restore", + stock_ops::start_restore_flag(vec![host.clone()], alkane_password.clone()), + ) { + println!("[3/6] restore FAILED; aborting"); + return 1; + } + let (_ip, d, ok) = wait_for(mac.as_deref(), &host, true, boot_timeout); + println!( + " {d} => {}", + if ok { "STOCK" } else { "NOT STOCK (fail)" } + ); + if !ok { + return 1; + } + } else { + println!("[3/6] already stock; skipping restore"); + } + + println!("\n[4/6] scan after restore (board should appear as a stock Antminer)"); + scan_report(&range); + + println!("\n[5/6] install alkane from stock"); + let h = stock_ops::start_install( + vec![host.clone()], + "a113d".to_string(), + AfwSource::Local(afw.clone()), + true, + stock_password.clone(), + false, + ); + if !drive("install", h) { + println!("[5/6] install FAILED"); + return 1; + } + let (alkane_ip, d, ok) = wait_for(mac.as_deref(), &host, false, boot_timeout); + println!( + " {d} => {}", + if ok { "ALKANE" } else { "NOT ALKANE (fail)" } + ); + + println!("\n[6/6] scan after install (board should appear as ALKANE via the HTTP API)"); + let rows = scan_report(&range); + let seen_alkane = rows + .iter() + .any(|r| crate::alkane_detect::is_alkane(r) && (r.ip == alkane_ip || r.ip == host)); + println!( + "\n== FLOW RESULT: {} ==", + if ok && seen_alkane { + "PASS (installed, serves API, visible in scan)" + } else { + "INCOMPLETE (see the scan lines above)" + } + ); + if ok && seen_alkane { + 0 + } else { + 1 + } +} + pub fn run(spec: &str) -> i32 { let mut it = spec.split_whitespace(); let host = match it.next() { diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index 092ffcf1..9e1933b5 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -16,6 +16,7 @@ mod fixtures; mod i18n; mod log_scan; mod logs; +mod media_ops; mod model; mod naming; mod pool_prefs; @@ -49,6 +50,12 @@ fn main() { std::process::exit(bench_sequence::run(&spec.to_string_lossy())); } + // Full GUI-flow test (scan -> restore -> scan -> install -> scan -> verify), + // exercising the scan step a user performs. See bench_sequence::run_flow. + if let Some(spec) = std::env::var_os("ALKANE_BENCH_FLOW") { + std::process::exit(bench_sequence::run_flow(&spec.to_string_lossy())); + } + // Headless access-probe check: `ALKANE_ACCESS_PROBE=" "` prints the // lock state the real access probe computes (no GUI, no wx), so the WhatsMiner // :4028 token check and the Antminer digest check can be verified directly. diff --git a/crates/alkane-gui/src/media_ops.rs b/crates/alkane-gui/src/media_ops.rs new file mode 100644 index 00000000..7744cfa0 --- /dev/null +++ b/crates/alkane-gui/src/media_ops.rs @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: MIT +//! GUI-side orchestration for the "Installation Media" feature: enumerate +//! writable removable devices safely, and drive card creation + device write on +//! a background thread, streaming progress with the same [`StockMsg`] channel +//! the install/restore flows use. +//! +//! The card *image* is built with `alkane_flash::sd_media` (root-free); only the +//! final device write touches hardware, and the UI confirms the target first. + +use std::path::PathBuf; +use std::process::Command; +use std::sync::mpsc::channel; +use std::sync::Arc; + +use alkane_artifacts::afw::{verify_afw, VerifyOptions}; +use alkane_flash::sd_media; + +use crate::stock_ops::{StockHandle, StockMsg}; + +/// What kind of card to build. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum MediaKind { + /// Genuine vendor stock-recovery card (from a user-supplied vendor package). + StockRecovery, + /// Alkane that runs from the card each boot (nothing written to the board). + AlkaneSimpleBoot, + /// Alkane installer: boots, writes alkane to the board's storage, LED-signals. + AlkaneInstaller, +} + +impl MediaKind { + pub fn label(self) -> &'static str { + match self { + MediaKind::StockRecovery => "Stock recovery (restore the board to genuine stock)", + MediaKind::AlkaneSimpleBoot => { + "Alkane: run from SD card (nothing written to the board)" + } + MediaKind::AlkaneInstaller => { + "Alkane: installer (writes alkane to the board, then signals done)" + } + } + } +} + +/// A removable device that is a plausible SD/USB card target. Deliberately +/// conservative: only whole disks that are removable or hotplug, never a disk +/// that holds a mounted filesystem the host is using. +#[derive(Clone, Debug)] +pub struct RemovableDevice { + /// e.g. `/dev/sdc`. + pub path: String, + /// Human size, e.g. `14.6G`. + pub size: String, + /// Model string, e.g. `STORAGE DEVICE`. + pub model: String, + /// True if any partition of it is currently mounted (a caution flag the UI + /// surfaces; such a device is still selectable but clearly risky). + pub has_mounted_partition: bool, +} + +impl RemovableDevice { + pub fn describe(&self) -> String { + let mut s = format!("{} ({}", self.path, self.size.trim()); + if !self.model.trim().is_empty() { + s.push_str(", "); + s.push_str(self.model.trim()); + } + s.push(')'); + if self.has_mounted_partition { + s.push_str(" [mounted]"); + } + s + } +} + +/// Enumerate removable whole-disk devices via `lsblk -J`. Returns an empty list +/// if `lsblk` is unavailable or parsing fails (the UI then offers a manual +/// device entry). The root/system disk is never included (it is not removable). +pub fn list_removable_devices() -> Vec { + let out = match Command::new("lsblk") + .args([ + "-J", + "-b", + "-o", + "NAME,SIZE,RM,HOTPLUG,TYPE,MODEL,TRAN,MOUNTPOINT", + ]) + .output() + { + Ok(o) if o.status.success() => o.stdout, + _ => return Vec::new(), + }; + let json: serde_json::Value = match serde_json::from_slice(&out) { + Ok(v) => v, + Err(_) => return Vec::new(), + }; + let mut devices = Vec::new(); + let blockdevices = json + .get("blockdevices") + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default(); + for dev in blockdevices { + let typ = dev.get("type").and_then(|v| v.as_str()).unwrap_or(""); + if typ != "disk" { + continue; + } + let rm = dev.get("rm").and_then(|v| v.as_bool()).unwrap_or(false); + let hotplug = dev + .get("hotplug") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let tran = dev.get("tran").and_then(|v| v.as_str()).unwrap_or(""); + // Removable, or a hotplug USB disk. Never an internal nvme/sata system + // disk (those are rm=false, hotplug=false). + let removable = rm || (hotplug && (tran == "usb" || tran == "mmc")); + if !removable { + continue; + } + let name = dev.get("name").and_then(|v| v.as_str()).unwrap_or(""); + if name.is_empty() { + continue; + } + let size_bytes = dev.get("size").and_then(|v| v.as_u64()).unwrap_or(0); + let model = dev + .get("model") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let mounted = dev + .get("children") + .and_then(|v| v.as_array()) + .map(|parts| { + parts.iter().any(|p| { + p.get("mountpoint") + .and_then(|m| m.as_str()) + .map(|m| !m.is_empty()) + .unwrap_or(false) + }) + }) + .unwrap_or(false) + || dev + .get("mountpoint") + .and_then(|m| m.as_str()) + .map(|m| !m.is_empty()) + .unwrap_or(false); + devices.push(RemovableDevice { + path: format!("/dev/{name}"), + size: human_size(size_bytes), + model, + has_mounted_partition: mounted, + }); + } + devices +} + +fn human_size(bytes: u64) -> String { + const UNITS: [&str; 5] = ["B", "K", "M", "G", "T"]; + let mut v = bytes as f64; + let mut u = 0; + while v >= 1024.0 && u < UNITS.len() - 1 { + v /= 1024.0; + u += 1; + } + format!("{v:.1}{}", UNITS[u]) +} + +/// A fully-specified media-creation request. +pub struct MediaRequest { + pub kind: MediaKind, + /// The source: an `.afw` file (alkane kinds) or a vendor stock package + /// (directory or `.zip`, stock kind). + pub source: PathBuf, + /// Target device, e.g. `/dev/sdc`. When `None`, only the image is built + /// (to `image_out`) and not written. + pub device: Option, + /// Where the intermediate card image is written. + pub image_out: PathBuf, + /// Allow an unsigned `.afw` (bench). + pub allow_unsigned: bool, +} + +/// Build the requested card image (and write it to the device if one is set) on +/// a background thread, streaming [`StockMsg`] exactly like `start_install`. +pub fn start_make_media(req: MediaRequest) -> StockHandle { + let (tx, rx) = channel(); + let cancel = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let cancel_worker = cancel.clone(); + let err_tx = tx.clone(); + + let spawned = std::thread::Builder::new() + .name("alkane-make-media".into()) + .spawn(move || { + let _ = tx.send(StockMsg::Started); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as u32) + .unwrap_or(0); + + let build = || -> Result<(), String> { + match req.kind { + MediaKind::StockRecovery => { + let _ = tx.send(StockMsg::Progress("preparing vendor package...".into())); + let dir = unpack_if_zip(&req.source).map_err(|e| e.to_string())?; + let _ = tx.send(StockMsg::Progress( + "assembling stock-recovery card...".into(), + )); + sd_media::build_stock_recovery_card(&dir, &req.image_out) + .map_err(|e| e.to_string())?; + } + MediaKind::AlkaneSimpleBoot | MediaKind::AlkaneInstaller => { + let _ = tx.send(StockMsg::Progress("verifying .afw...".into())); + let verified = verify_afw( + &req.source, + &VerifyOptions { + allow_unsigned: req.allow_unsigned, + expect_board: Some("zynq-7010".into()), + }, + ) + .map_err(|e| format!(".afw: {e}"))?; + if req.kind == MediaKind::AlkaneSimpleBoot { + let _ = tx + .send(StockMsg::Progress("assembling simple-boot card...".into())); + sd_media::build_zynq_simpleboot_card(&verified, &req.image_out, now) + .map_err(|e| e.to_string())?; + } else { + let _ = tx.send(StockMsg::Progress( + "assembling installer card (injecting install hook)...".into(), + )); + sd_media::build_zynq_installer_card(&verified, &req.image_out, now) + .map_err(|e| e.to_string())?; + } + } + } + if let Some(dev) = &req.device { + if cancel_worker.load(std::sync::atomic::Ordering::Relaxed) { + return Err("cancelled before device write".into()); + } + let _ = tx.send(StockMsg::Progress(format!( + "writing card to {} (do not remove)...", + dev.display() + ))); + sd_media::write_image_to_device(&req.image_out, dev) + .map_err(|e| e.to_string())?; + } + Ok(()) + }; + + let (ok, detail) = match build() { + Ok(()) => { + let where_ = req + .device + .as_ref() + .map(|d| format!("written to {}", d.display())) + .unwrap_or_else(|| format!("image at {}", req.image_out.display())); + (true, format!("card ready ({where_})")) + } + Err(e) => (false, format!("media build failed: {e}")), + }; + let ip = req + .device + .as_ref() + .map(|d| d.display().to_string()) + .unwrap_or_else(|| "card".into()); + let _ = tx.send(StockMsg::Result { ip, ok, detail }); + let _ = tx.send(StockMsg::Done); + }); + + if spawned.is_err() { + let _ = err_tx.send(StockMsg::Result { + ip: String::new(), + ok: false, + detail: "could not start the media worker thread".into(), + }); + let _ = err_tx.send(StockMsg::Done); + } + StockHandle::new(rx, cancel) +} + +/// If `src` is a `.zip`, unpack it to an ephemeral directory and return that; +/// a directory is returned as-is. +fn unpack_if_zip(src: &std::path::Path) -> std::io::Result { + if src.is_dir() { + return Ok(src.to_path_buf()); + } + if src + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("zip")) + { + let staged = std::env::temp_dir().join(format!("alkane-media-pkg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&staged); + std::fs::create_dir_all(&staged)?; + let status = Command::new("unzip") + .args(["-o", "-q"]) + .arg(src) + .arg("-d") + .arg(&staged) + .status()?; + if !status.success() { + return Err(std::io::Error::other("unzip failed")); + } + return Ok(staged); + } + Err(std::io::Error::other( + "stock package must be a directory or a .zip", + )) +} diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index c4e06f5e..a46e0981 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -533,8 +533,18 @@ pub fn start_scan(lines: Vec, timeout_secs: u64) -> ScanHandle { } // asic-rs does not recognise a board running Alkane // OS (no cgminer socket or vendor web UI exposed); - // the toolkit's own probe finds it. - None => (ip, crate::alkane_detect::detect(ip).await), + // the toolkit's own probe finds it. Failing that, + // a stock Antminer whose miner API is down is still + // found by its :80 vendor web UI. + None => { + let row = match crate::alkane_detect::detect(ip).await { + Some(r) => Some(r), + None => { + crate::alkane_detect::detect_stock_antminer(ip).await + } + }; + (ip, row) + } } } }) diff --git a/crates/alkane-gui/src/stock_ops.rs b/crates/alkane-gui/src/stock_ops.rs index b09b685a..57cb243e 100644 --- a/crates/alkane-gui/src/stock_ops.rs +++ b/crates/alkane-gui/src/stock_ops.rs @@ -10,14 +10,75 @@ //! Results stream back over a channel, drained by the UI timer tick exactly like //! restore.rs. The UI gates each behind a typed-FLASH confirmation. +use std::io::Read as _; +use std::net::TcpStream; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{channel, Receiver}; +use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::Arc; +use std::time::{Duration, Instant}; use alkane_artifacts::afw::{verify_afw, VerifyOptions}; use alkane_artifacts::fetch::{self, ReleaseSource}; use alkane_flash::stock::{self, RestoreImages}; + +/// Read the SSH identification banner (no auth) from `host:22`, e.g. +/// `SSH-2.0-dropbear_2026.93`. +fn ssh_banner(host: &str) -> Option { + let addr: std::net::SocketAddr = format!("{host}:22").parse().ok()?; + let mut s = TcpStream::connect_timeout(&addr, Duration::from_secs(4)).ok()?; + s.set_read_timeout(Some(Duration::from_secs(4))).ok()?; + let mut buf = [0u8; 128]; + let n = s.read(&mut buf).ok()?; + if n == 0 { + return None; + } + Some( + String::from_utf8_lossy(&buf[..n]) + .lines() + .next() + .unwrap_or("") + .trim() + .to_string(), + ) +} + +/// Whether a just-installed board's SSH banner looks like alkane. We installed +/// alkane to this specific board, so any SSH banner that is NOT the stock +/// Antminer dropbear (2018/2019) means our image booted. Alkane images ship a +/// current dropbear regardless of whether the image also serves the HTTP API, so +/// this verify works even for minimal images that do not serve `:80` (the +/// HTTP-only scan probe cannot see those). +fn banner_is_alkane(banner: &str) -> bool { + let b = banner.to_ascii_lowercase(); + if b.contains("dropbear_2018") || b.contains("dropbear_2019") { + return false; + } + b.contains("dropbear") || b.contains("openssh") +} + +/// Poll a just-installed board until it comes up as alkane over SSH (not the +/// stock dropbear) or the deadline passes. Streams a progress line on success. +fn verify_alkane_live(ip: &str, tx: &Sender, cancel: &AtomicBool) -> bool { + let deadline = Instant::now() + Duration::from_secs(150); + loop { + if cancel.load(Ordering::Relaxed) { + return false; + } + if let Some(b) = ssh_banner(ip) { + if banner_is_alkane(&b) { + let _ = tx.send(StockMsg::Progress(format!( + "{ip}: alkane is live (ssh \"{b}\")" + ))); + return true; + } + } + if Instant::now() >= deadline { + return false; + } + std::thread::sleep(Duration::from_secs(5)); + } +} use alkane_flash::stock_firmware; use crate::scan::fake_scan_enabled; @@ -83,6 +144,12 @@ pub struct StockHandle { } impl StockHandle { + /// Construct a handle around a worker's receiver and cancel flag. Used by + /// other op modules (e.g. `media_ops`) that reuse this streaming channel. + pub fn new(rx: Receiver, cancel: Arc) -> StockHandle { + StockHandle { rx, cancel } + } + #[allow(dead_code)] pub fn stop(&self) { self.cancel.store(true, Ordering::Relaxed); @@ -154,8 +221,10 @@ pub fn start_install( } AfwSource::Release { name, url } => { let _ = tx.send(StockMsg::Progress("acquiring .afw...".into())); + // Token attaches only for the trusted gitea host (see + // for_asset_url); never sent to a GitHub/other fork host. match fetch::fetch_afw_url( - &ReleaseSource::alkane_os(), + &ReleaseSource::for_asset_url(&url), &name, &url, &download_dir(), @@ -242,10 +311,26 @@ pub fn start_install( let (ok, detail) = match stock::install_from_stock(&ip, &afw_path, &verified, password.as_deref()) { - Ok(()) => ( - true, - "installed alkane-os (verify liveness over the network)".to_string(), - ), + Ok(()) => { + // The write succeeded; now confirm the board rebooted + // into alkane. Use the SSH banner (works even for + // images that do not serve the HTTP API) rather than + // only the HTTP scan probe. + let _ = tx.send(StockMsg::Progress(format!( + "{ip}: installed; awaiting reboot into alkane (up to 150s)..." + ))); + if verify_alkane_live(&ip, &tx, &tc) { + (true, "installed; alkane is live (SSH-verified)".to_string()) + } else { + ( + true, + "installed; alkane not confirmed over SSH within the window -- \ + check the board (a minimal image without the HTTP API still \ + installs and boots; it just will not show in the scan)" + .to_string(), + ) + } + } Err(e) => (false, format!("install failed: {e}")), }; if tx.send(StockMsg::Result { ip, ok, detail }).is_err() { diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 2de48f3a..aed1f2e5 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -3,6 +3,7 @@ use crate::alkane_detect; use crate::credentials; +use crate::media_ops; use crate::model::*; use crate::restore; use crate::scan::{self, ScanMsg}; @@ -27,6 +28,11 @@ pub const ID_EXPORT: i32 = 109; pub const ID_SETTINGS: i32 = 110; // Bug report / feature request dialog (toolbar, between Export and Settings). pub const ID_BUG_REPORT: i32 = 111; +// Unified "Data" toolbar icon button: a dropdown of Presets/Filter/Columns/Export. +pub const ID_DATA: i32 = 112; +// "Installation Media" toolbar icon button: opens the SD-card build dialog +// without needing to right-click a miner. +pub const ID_MEDIA_TOOLBAR: i32 = 113; const ID_REPORT_SEND: i32 = 240; const ID_REPORT_CLOSE: i32 = 241; const ID_REPORT_OPEN: i32 = 242; @@ -105,6 +111,18 @@ const ID_POOLS_CANCEL: i32 = 789; const ID_CTX_INSTALL_ALKANE: i32 = 770; const ID_CTX_UNINSTALL_ALKANE: i32 = 771; const ID_CTX_UPDATE_ALKANE: i32 = 772; +// "Installation Media..." context item (build a bootable SD card). +const ID_CTX_INSTALL_MEDIA: i32 = 773; +// Installation-Media dialog controls (free id block above the install dialog's). +const ID_MEDIA_OK: i32 = 1015; +const ID_MEDIA_CANCEL: i32 = 1016; +const ID_MEDIA_KIND_CHOICE: i32 = 1017; +const ID_MEDIA_DEVICE_CHOICE: i32 = 1019; +const ID_MEDIA_BROWSE: i32 = 1020; +const ID_MEDIA_RELOAD_DEVS: i32 = 1022; +// Install dialog control-board selector (lets the operator pick/override the +// control board, needed when the scan could not determine it). +const ID_INSTALL_BOARD_CHOICE: i32 = 1023; const ID_INSTALL_OK: i32 = 1006; const ID_INSTALL_CANCEL: i32 = 1007; const ID_INSTALL_RELEASE_CHOICE: i32 = 1008; @@ -541,41 +559,6 @@ fn ascii_bar(pct: u8) -> String { format!("[{}{}]", "#".repeat(filled), "-".repeat(width - filled)) } -/// A read-only flash-plan summary for a local `.afw`: its tier and which regions -/// it overwrites (U-Boot / Kernel / Userspace), from the bundle's own manifest. -/// Shown in the install dialog when a file is picked so the operator sees exactly -/// what the flash touches before starting. -fn afw_plan_text(path: &str, expect_board: &str) -> String { - use alkane_artifacts::afw::{verify_afw, VerifyOptions}; - // Verify against the install target's board (review #6): a file for another - // board then surfaces as an error here instead of showing a plausible plan - // that start_install would later reject. - let opts = VerifyOptions { - allow_unsigned: true, - expect_board: Some(expect_board.to_string()), - }; - match verify_afw(std::path::Path::new(path), &opts) { - Ok(v) => { - let p = v.manifest.flash_plan(); - let mark = |b: bool| if b { "[x]" } else { "[ ]" }; - format!( - "Flash plan: tier {} (board {}). Overwrites:\n {} U-Boot{}\n {} Kernel\n {} Userspace (rootfs)", - p.tier, - v.manifest.board, - mark(p.writes_uboot), - if p.writes_uboot { - "" - } else { - " -- preserved" - }, - mark(p.writes_kernel), - mark(p.writes_userspace), - ) - } - Err(e) => format!("Could not read flash plan from this file: {e}"), - } -} - /// The colour a component-health state renders in (round 13 #3): grey = /// unreachable, red = detected but down, yellow = sub-optimal, green = healthy. fn health_color(pal: &Palette, h: crate::model::CompHealth) -> (u8, u8, u8) { @@ -673,6 +656,12 @@ const SVG_BOLT_FULL: &str = include_str!("../assets/icons/bolt-solid-full.svg"); const SVG_BRAIN_FULL: &str = include_str!("../assets/icons/brain-solid-full.svg"); const SVG_FAN_FULL: &str = include_str!("../assets/icons/fan-solid-full.svg"); const SVG_CHIP_FULL: &str = include_str!("../assets/icons/microchip-solid-full.svg"); +// Toolbar icon buttons (round 19): gear (Settings), bug (report), database +// (Data dropdown), sd-card (Installation Media). +const SVG_GEAR: &str = include_str!("../assets/icons/gear.svg"); +const SVG_BUG: &str = include_str!("../assets/icons/bug.svg"); +const SVG_DATA: &str = include_str!("../assets/icons/database.svg"); +const SVG_SDCARD: &str = include_str!("../assets/icons/sd-card.svg"); /// KPI card minimum widths. The count cards (Total/Hashing/...) are narrow; the /// two wide cards (SHA-256 Hashrate, Est. power) need more room so their @@ -990,6 +979,7 @@ pub struct App { stock_op: Option, install_dialog: Widget, install_release_choice: Widget, + install_board_choice: Widget, install_unsigned_check: Widget, install_releases: Vec, install_ips: Vec, @@ -1005,10 +995,24 @@ pub struct App { install_local_label: Widget, // A read-only flash-plan checklist (tier + which regions are overwritten), // filled from a picked local .afw's manifest. - install_plan_label: Widget, // The release repo (owner/repo) the picker scans; defaults to // blueflare/alkane-os, editable + reloadable to any compatible repo. install_repo_input: Widget, + // Installation-Media dialog (sd_media / media_ops): build a bootable SD card + // for a card-bootable board (Zynq first). One background job, reusing + // `stock_op`. The widgets + the state captured when the dialog opens. + media_dialog: Widget, + media_kind_choice: Widget, + media_device_choice: Widget, + media_unsigned_check: Widget, + media_source_label: Widget, + // The browsed source: an .afw (alkane kinds) or a vendor package (stock). + media_source_path: Option, + // Removable devices behind the device choice, by item index (index 0 is the + // "build image only, do not write" option, so devices start at index 1). + media_devices: Vec, + // The board family the card targets (e.g. "zynq-7010"). + media_board: String, uninstall_dialog: Widget, uninstall_firmware_input: Widget, // Restore-to-stock source: the board's on-board stock backup (checkbox, @@ -1244,21 +1248,36 @@ pub fn build(frame: Widget) -> App { // when the language changes (round 15 #13). let mut l10n_labels: Vec<(Widget, &'static str)> = Vec::new(); l10n_labels.push((ranges_btn, "Scan ranges")); - let mut tbtn = |label: &'static str, id: i32| -> Widget { - let b = Widget::button(panel, &crate::i18n::t(label), id); - ctl.add(b, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 4); - l10n_labels.push((b, label)); + // Compact icon toolbar (round 19): a unified "Data" dropdown (presets / + // filter / columns / export), an Installation-Media (SD card) button, Bug + // report, and Settings. Logs moved into the Settings dropdown + // (ID_LOGS_OPEN), so the old standalone Log button is gone. Icon buttons + // carry no text label, so they are not tracked for localization; their + // tooltips name them. + let icon_fg = if wx_rs::is_dark() { + (0xDD, 0xDD, 0xDD) + } else { + (0x33, 0x33, 0x33) + }; + let icon_btn = |svg: &str, id: i32, tip: &str| -> Widget { + let b = Widget::svg_button(panel, &svg_recolored(svg, icon_fg), id, 16, 16); + b.set_tool_tip(&crate::i18n::t(tip)); + ctl.add(b, 0, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_ALL, 2); b }; - let _presets_btn = tbtn("Presets", ID_PRESETS); - let _filter_btn = tbtn("Filter", ID_FILTER); - let _columns_btn = tbtn("Columns", ID_COLUMNS); - let _export_btn = tbtn("Export", ID_EXPORT); - let _report_btn = tbtn("Bug report", ID_BUG_REPORT); - // The old Credentials button is now a Settings menu (round 15 #13). - let _creds_btn = tbtn("Settings", ID_SETTINGS); - // Toggle between the fleet table and the live activity log. - let log_toggle_btn = tbtn("Log", ID_LOG_TOGGLE); + let _data_btn = icon_btn(SVG_DATA, ID_DATA, "Data: presets, filter, columns, export"); + let _media_btn = icon_btn( + SVG_SDCARD, + ID_MEDIA_TOOLBAR, + "Create installation media (SD card)", + ); + let _report_btn = icon_btn(SVG_BUG, ID_BUG_REPORT, "Report a bug or request a feature"); + let _settings_btn = icon_btn(SVG_GEAR, ID_SETTINGS, "Settings, language, and logs"); + // The inline table/log view toggle is kept (toggle_log_view / log_view) but + // no longer surfaced as a toolbar button; logs are reached from Settings. + // Created hidden so the field and toggle_log_view stay valid. + let log_toggle_btn = Widget::button(panel, "Log", ID_LOG_TOGGLE); + log_toggle_btn.show(false); root.add_sizer(ctl, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 4); // Track the KPI captions for live re-localization (index 5, the hashrate // caption, is dynamic per-algorithm so it is refreshed by refresh_kpis). @@ -1410,6 +1429,7 @@ pub fn build(frame: Widget) -> App { stock_op: None, install_dialog: frame, install_release_choice: frame, + install_board_choice: frame, install_unsigned_check: frame, install_releases: Vec::new(), install_ips: Vec::new(), @@ -1417,8 +1437,15 @@ pub fn build(frame: Widget) -> App { install_is_update: false, install_local_path: None, install_local_label: frame, - install_plan_label: frame, install_repo_input: frame, + media_dialog: frame, + media_kind_choice: frame, + media_device_choice: frame, + media_unsigned_check: frame, + media_source_label: frame, + media_source_path: None, + media_devices: Vec::new(), + media_board: stock_ops::DEFAULT_BOARD.to_string(), uninstall_dialog: frame, uninstall_firmware_input: frame, uninstall_onboard_check: frame, @@ -2025,13 +2052,23 @@ impl App { // - Uninstall: a board running Alkane OS (restored to stock). // A mixed stock/Alkane selection gets neither Install nor Update. The // engine still gates on compatibility. - let supported = selected.iter().all(|r| alkane_detect::install_supported(r)); + // Offer install when every selected board is either a known supported + // control board, or a stock Antminer whose control board is unknown + // (found by its :80 web UI) -- the latter installs with a manually + // chosen control board in the dialog. + let supported = selected.iter().all(|r| { + alkane_detect::install_supported(r) || alkane_detect::is_unidentified_stock_antminer(r) + }); let all_alkane = selected.iter().all(|r| alkane_detect::is_alkane(r)); let none_alkane = selected.iter().all(|r| !alkane_detect::is_alkane(r)); let install = supported && none_alkane; let update = supported && all_alkane; let uninstall = all_alkane; - if install || update || uninstall { + // "Installation Media" applies to card-bootable boards (Zynq); it builds + // an SD card and does not need the board to be reachable now. + let media = + !selected.is_empty() && selected.iter().all(|r| alkane_detect::media_supported(r)); + if install || update || uninstall || media { menu.menu_append_separator(); } if install { @@ -2046,6 +2083,9 @@ impl App { "Uninstall alkane OS (restore to stock)...", ); } + if media { + menu.menu_append(ID_CTX_INSTALL_MEDIA, "Installation Media (SD card)..."); + } self.pending_popup = Some((t, menu)); } @@ -2773,27 +2813,25 @@ impl App { /// that carry an .afw compatible with the target board (newest first). Called /// when the dialog opens and from the Reload button. Requires /// `install_release_choice` to already exist. - fn populate_install_releases(&mut self, owner: &str, repo: &str) { + fn populate_install_releases(&mut self, src: &ReleaseSource) { let board = self.install_board.clone(); - wx_rs::set_status_text(&format!("scanning {owner}/{repo} releases...")); - let releases: Vec = - match fetch::list_releases(&ReleaseSource::for_repo(owner, repo)) { - Ok(list) => list - .into_iter() - .filter(|r| !r.draft && r.is_compatible_with(&board)) - .collect(), - Err(e) => { - wx_rs::set_status_text(&format!("could not list {owner}/{repo} releases: {e}")); - Vec::new() - } - }; + let label = format!("{}/{}", src.owner, src.repo); + wx_rs::set_status_text(&format!("scanning {label} releases...")); + let releases: Vec = match fetch::list_releases(src) { + Ok(list) => list + .into_iter() + .filter(|r| !r.draft && r.is_compatible_with(&board)) + .collect(), + Err(e) => { + wx_rs::set_status_text(&format!("could not list {label} releases: {e}")); + Vec::new() + } + }; self.install_releases = releases; let choice = self.install_release_choice; choice.choice_clear(); if self.install_releases.is_empty() { - choice.choice_append(&format!( - "(no release with an .afw for {board} in {owner}/{repo})" - )); + choice.choice_append(&format!("(no release with an .afw for {board} in {label})")); } else { for (i, r) in self.install_releases.iter().enumerate() { let tag = if r.tag.is_empty() { @@ -2809,24 +2847,18 @@ impl App { choice.choice_set_selection(0); } wx_rs::set_status_text(&format!( - "{} release(s) for {board} in {owner}/{repo}", + "{} release(s) for {board} in {label}", self.install_releases.len() )); } - /// Reload the install picker from the owner/repo currently typed in the - /// dialog's repo field (default blueflare/alkane-os if blank/malformed). + /// Reload the install picker from the repo URL currently typed in the + /// dialog's repo field. Accepts a full Gitea or GitHub repo URL (or a bare + /// `owner/repo` on the default Gitea); falls back to blueflare/alkane-os. fn reload_install_repo(&mut self) { let raw = self.install_repo_input.get_value(); - let raw = raw.trim(); - let (owner, repo) = raw.split_once('/').unwrap_or(("blueflare", "alkane-os")); - let owner = owner.trim(); - let repo = repo.trim(); - if owner.is_empty() || repo.is_empty() { - self.populate_install_releases("blueflare", "alkane-os"); - } else { - self.populate_install_releases(owner, repo); - } + let src = ReleaseSource::from_url(raw.trim()).unwrap_or_else(ReleaseSource::alkane_os); + self.populate_install_releases(&src); self.install_dialog.layout(); } @@ -2872,36 +2904,46 @@ impl App { Widget::static_text( dlg, &if update { - format!( - "Update alkane OS on {n} board(s) already running it (updated in place; BOOT.bin is never written):\n{}", - ips.join(", ") - ) + format!("Update {n} board(s):\n{}", ips.join(", ")) } else { - format!( - "Install alkane OS onto {n} board(s) currently on stock:\n{}", - ips.join(", ") - ) + format!("Install onto {n} board(s):\n{}", ips.join(", ")) }, ), 0, sf::BORDER_ALL, 12, ); + // Control-board selector: defaults to the detected board, but the + // operator can override it -- required when the scan could not determine + // the control board (a stock Antminer found only by its :80 web UI). root.add( - Widget::static_text(dlg, &format!("Target board: {board}")), + Widget::static_text(dlg, "Control board:"), 0, - sf::BORDER_LEFT | sf::BORDER_RIGHT, + sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 12, ); + let board_choice = Widget::choice(dlg, ID_INSTALL_BOARD_CHOICE); + let mut board_sel = 0; + for (i, (id, desc)) in stock_ops::SUPPORTED_BOARDS.iter().enumerate() { + board_choice.choice_append(&format!("{id} -- {desc}")); + if *id == board { + board_sel = i as i32; + } + } + board_choice.choice_set_selection(board_sel); root.add( - Widget::static_text( - dlg, - if update { - "Release to update to (newest first):" - } else { - "Release to install (newest first):" - }, - ), + board_choice, + 0, + sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, + 12, + ); + self.install_board_choice = board_choice; + // Keep install_board consistent with the selector's initial choice. + if let Some((id, _)) = stock_ops::SUPPORTED_BOARDS.get(board_sel as usize) { + self.install_board = id.to_string(); + } + root.add( + Widget::static_text(dlg, "Release"), 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 12, @@ -2919,14 +2961,15 @@ impl App { // format; defaults to blueflare/alkane-os. Reload re-scans it and keeps // only the releases compatible with this board. root.add( - Widget::static_text(dlg, "Release repo (owner/repo), then Reload:"), + Widget::static_text(dlg, "Release repo"), 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 12, ); let repo_row = Widget::box_sizer(false); let repo_input = Widget::text_ctrl(dlg, false); - repo_input.set_value("blueflare/alkane-os"); + repo_input.set_value("https://gitea.bluefla.re/blueflare/alkane-os"); + repo_input.set_tool_tip("A Gitea or GitHub repo URL, or owner/repo. Reload to re-scan."); repo_row.add( repo_input, 1, @@ -2942,25 +2985,22 @@ impl App { 12, ); // Initial population from the default repo. - self.populate_install_releases("blueflare", "alkane-os"); + self.populate_install_releases(&ReleaseSource::alkane_os()); // Or install from a local .afw the operator picks (the CLI's local-file // install, now in the GUI). When a file is chosen it takes precedence // over the release selected above; the label shows the current choice. root.add( - Widget::static_text(dlg, "Or install from a local .afw file:"), + Widget::static_text(dlg, "Local .afw"), 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 12, ); let browse_row = Widget::box_sizer(false); - browse_row.add( - Widget::button(dlg, "Browse local .afw...", ID_INSTALL_BROWSE), - 0, - sf::BORDER_RIGHT, - 6, - ); - let local_label = Widget::static_text(dlg, "(none; using the selected release above)"); + let browse_btn = Widget::button(dlg, "Browse...", ID_INSTALL_BROWSE); + browse_btn.set_tool_tip("Install a local .afw instead of the selected release."); + browse_row.add(browse_btn, 0, sf::BORDER_RIGHT, 6); + let local_label = Widget::static_text(dlg, "(using selected release)"); browse_row.add(local_label, 1, sf::ALIGN_CENTRE_VERTICAL, 0); self.install_local_label = local_label; root.add_sizer( @@ -2970,36 +3010,17 @@ impl App { 12, ); - // Flash-plan checklist: detects the tier and which regions a picked local - // .afw overwrites (U-Boot / Kernel / Userspace). - let plan = Widget::static_text( - dlg, - "Flash plan: pick a local .afw above to see its tier and what it overwrites.", - ); - root.add(plan, 0, sf::BORDER_ALL, 12); - self.install_plan_label = plan; - // No password field (issue #46): the board login comes from Settings (or // the firmware's shipped default when unset). // Current bench .afw files are unsigned (SHA-256 integrity, no Ed25519). let unsigned = Widget::check_box(dlg, "Allow unsigned .afw (bench only)"); unsigned.set_checked(true); + unsigned + .set_tool_tip("Bench images are unsigned: SHA-256 proves integrity, not authenticity."); root.add(unsigned, 0, sf::BORDER_ALL, 12); self.install_unsigned_check = unsigned; - // No typed-FLASH step (issue #41): the dialog, the board list and the - // Install button are the confirmation. The warning stays visible. - root.add( - Widget::static_text( - dlg, - "This reflashes the control board. Click Install to start.", - ), - 0, - sf::BORDER_ALL, - 12, - ); - let btns = Widget::box_sizer(false); btns.add_stretch(1); btns.add( @@ -3026,6 +3047,186 @@ impl App { Some(dlg) } + /// Build the "Installation Media" dialog: choose a card kind, an image + /// source, and a target SD device, then build (and optionally write) a + /// bootable card for a card-bootable board (Zynq first). + fn build_install_media_dialog(&mut self) -> Option { + if self.flash_busy() { + wx_rs::set_status_text("busy -- try again once the current operation finishes"); + return None; + } + let board = self + .selected_rows() + .into_iter() + .find_map(crate::alkane_detect::board_family) + .unwrap_or_else(|| stock_ops::DEFAULT_BOARD.to_string()); + self.media_board = board.clone(); + self.media_source_path = None; + + let frame = Widget::main_frame(); + let dlg = Widget::dialog(frame, "Installation Media"); + let root = Widget::box_sizer(true); + root.add( + Widget::static_text(dlg, &format!("Control board: {board}")), + 0, + sf::BORDER_ALL, + 12, + ); + + root.add( + Widget::static_text(dlg, "Media type"), + 0, + sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, + 12, + ); + let kind = Widget::choice(dlg, ID_MEDIA_KIND_CHOICE); + for k in [ + media_ops::MediaKind::StockRecovery, + media_ops::MediaKind::AlkaneSimpleBoot, + media_ops::MediaKind::AlkaneInstaller, + ] { + kind.choice_append(k.label()); + } + kind.choice_set_selection(2); // default: alkane installer + root.add(kind, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12); + self.media_kind_choice = kind; + + root.add( + Widget::static_text(dlg, "Source"), + 0, + sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, + 12, + ); + let browse_row = Widget::box_sizer(false); + let src_browse = Widget::button(dlg, "Browse...", ID_MEDIA_BROWSE); + src_browse.set_tool_tip( + "An .afw for alkane media, or a genuine vendor package (.zip) for stock recovery.", + ); + browse_row.add(src_browse, 0, sf::BORDER_RIGHT, 6); + let src_label = Widget::static_text(dlg, "(none selected)"); + browse_row.add(src_label, 1, sf::ALIGN_CENTRE_VERTICAL, 0); + self.media_source_label = src_label; + root.add_sizer( + browse_row, + 0, + sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, + 12, + ); + + let unsigned = Widget::check_box(dlg, "Allow unsigned .afw (bench only)"); + unsigned.set_checked(true); + unsigned + .set_tool_tip("Bench images are unsigned: SHA-256 proves integrity, not authenticity."); + root.add(unsigned, 0, sf::BORDER_ALL, 12); + self.media_unsigned_check = unsigned; + + let target = Widget::static_text(dlg, "Target card"); + target.set_tool_tip("Writing a card erases it entirely. Confirm the device first."); + root.add( + target, + 0, + sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, + 12, + ); + let dev_row = Widget::box_sizer(false); + let dev = Widget::choice(dlg, ID_MEDIA_DEVICE_CHOICE); + dev_row.add(dev, 1, sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_RIGHT, 6); + dev_row.add(Widget::button(dlg, "Rescan", ID_MEDIA_RELOAD_DEVS), 0, 0, 0); + self.media_device_choice = dev; + root.add_sizer( + dev_row, + 0, + sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, + 12, + ); + self.populate_media_devices(); + + let btns = Widget::box_sizer(false); + btns.add_stretch(1); + btns.add( + Widget::button(dlg, "Create", ID_MEDIA_OK), + 0, + sf::BORDER_ALL, + 6, + ); + btns.add( + Widget::button(dlg, "Cancel", ID_MEDIA_CANCEL), + 0, + sf::BORDER_ALL, + 6, + ); + root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6); + root.set_sizer_on(dlg); + dlg.set_min_size(580, 480); + dlg.fit(dlg); + self.media_dialog = dlg; + Some(dlg) + } + + /// Fill the media device choice from a fresh removable-device scan. Index 0 + /// is "build an image file only" (no card write); real devices follow. + fn populate_media_devices(&mut self) { + self.media_devices = media_ops::list_removable_devices(); + let c = self.media_device_choice; + c.choice_clear(); + c.choice_append("Build an image file only (do not write a card)"); + for d in &self.media_devices { + c.choice_append(&d.describe()); + } + c.choice_set_selection(if self.media_devices.is_empty() { 0 } else { 1 }); + } + + /// Start building the requested card (and writing it, if a device is chosen) + /// on the shared background worker. Reuses `stock_op` and its drain. + fn apply_make_media_confirm(&mut self) { + if self.flash_busy() { + return; + } + let kind = match self.media_kind_choice.choice_get_selection() { + 0 => media_ops::MediaKind::StockRecovery, + 1 => media_ops::MediaKind::AlkaneSimpleBoot, + _ => media_ops::MediaKind::AlkaneInstaller, + }; + let source = match &self.media_source_path { + Some(p) => std::path::PathBuf::from(p), + None => { + wx_rs::set_status_text("pick an image source (.afw or a stock package) first"); + return; + } + }; + let dev_sel = self.media_device_choice.choice_get_selection(); + let device = if dev_sel <= 0 { + None + } else { + self.media_devices + .get((dev_sel - 1) as usize) + .map(|d| std::path::PathBuf::from(&d.path)) + }; + let allow_unsigned = self.media_unsigned_check.is_checked(); + let image_out = alkane_core::platform::config_path("media") + .join(format!("{}-card.img", self.media_board)); + if let Some(parent) = image_out.parent() { + let _ = std::fs::create_dir_all(parent); + } + + self.media_dialog.close(1); + let target = device + .as_ref() + .map(|d| d.display().to_string()) + .unwrap_or_else(|| "image file".into()); + wx_rs::set_status_text(&format!( + "building {} card -> {target}...", + self.media_board + )); + self.stock_op = Some(media_ops::start_make_media(media_ops::MediaRequest { + kind, + source, + device, + image_out, + allow_unsigned, + })); + } + /// Apply the install confirmation: validate the typed keyword, resolve the /// chosen release asset, and start the network-only from-stock install. fn apply_install_confirm(&mut self) { @@ -3034,7 +3235,13 @@ impl App { self.install_dialog.close(0); return; } - let board = self.install_board.clone(); + // Take the control board from the selector (the operator may have picked + // or overridden it, e.g. for a stock Antminer the scan could not identify). + let board = stock_ops::SUPPORTED_BOARDS + .get(self.install_board_choice.choice_get_selection().max(0) as usize) + .map(|(id, _)| id.to_string()) + .unwrap_or_else(|| self.install_board.clone()); + self.install_board = board.clone(); // Source: a local .afw the operator picked takes precedence; otherwise // the selected Gitea release's asset for this board. let (source, source_name) = if let Some(path) = self.install_local_path.clone() { @@ -3528,6 +3735,12 @@ impl App { // Settings menu items (round 15 #13). ID_SCAN_CREDS => return Some(self.build_firmware_creds_dialog()), ID_LOGS_OPEN => return Some(self.build_logs_dialog()), + // "Data" dropdown items (round 19): the former standalone toolbar + // buttons, now entries in one icon button's menu. + ID_PRESETS => return Some(self.build_presets_dialog()), + ID_FILTER => return Some(self.build_filter_dialog()), + ID_COLUMNS => return Some(self.build_columns_dialog()), + ID_EXPORT => return self.open_export_dialog(), ID_HDR_SORT_ASC | ID_HDR_SORT_DESC | ID_HDR_SORT_REL_ASC | ID_HDR_SORT_REL_DESC | ID_HDR_HIDE | ID_HDR_AUTOSIZE | ID_HDR_AUTOSIZE_ALL | ID_HDR_COLUMNS => { return self.on_header_menu(id) @@ -3544,6 +3757,7 @@ impl App { ID_CTX_INSTALL_ALKANE => return self.build_install_dialog(false), ID_CTX_UPDATE_ALKANE => return self.build_install_dialog(true), ID_CTX_UNINSTALL_ALKANE => return self.build_uninstall_dialog(), + ID_CTX_INSTALL_MEDIA => return self.build_install_media_dialog(), ID_CTX_POOLS => return self.build_pools_dialog(), ID_CTX_FLASH => { // A flash needs exclusive hardware access; don't even prompt if @@ -4542,8 +4756,14 @@ impl App { for ip in expired { awaiting.remove(&ip); op_status.remove(&ip); + // The install worker already verifies liveness over SSH; this only + // means the HTTP scan probe did not pick the board up, so its row + // will not auto-refresh to the alkane entry. Common for a minimal + // image that serves SSH but not the HTTP API -- not an install + // failure. crate::logs::log(format!( - "{ip}: installed, but did not answer as alkane within the verify window" + "{ip}: not answering the alkane HTTP API; its row will not auto-update \ + (the image may serve only SSH). See the install result above." )); } } @@ -5441,6 +5661,20 @@ impl App { /// Build + queue the Settings popup menu (round 15 #13): Credentials, a /// Language submenu, and the Logs page. + /// The unified "Data" toolbar dropdown: presets, filter, columns, export. + /// The items reuse the existing action ids and are dispatched by + /// `on_menu_item` (same as any popped menu). + fn open_data_menu(&mut self) { + let t = crate::i18n::t; + let menu = Widget::menu_new(); + menu.menu_append(ID_PRESETS, &t("Presets...")); + menu.menu_append(ID_FILTER, &t("Filter...")); + menu.menu_append(ID_COLUMNS, &t("Columns...")); + menu.menu_append_separator(); + menu.menu_append(ID_EXPORT, &t("Export...")); + self.pending_popup = Some((Widget::main_frame(), menu)); + } + fn open_settings_menu(&mut self) { let menu = Widget::menu_new(); menu.menu_append(ID_SCAN_CREDS, &crate::i18n::t("Credentials")); @@ -6179,6 +6413,14 @@ impl App { self.filter_pending_op = Some(sel); wx_rs::call_after(DEFER_FILTER); } + ID_INSTALL_BOARD_CHOICE => { + // The operator changed the target control board: re-filter the + // release picker for the new board. + if let Some((board, _)) = stock_ops::SUPPORTED_BOARDS.get(sel.max(0) as usize) { + self.install_board = board.to_string(); + self.reload_install_repo(); + } + } _ => {} } } @@ -6229,6 +6471,8 @@ impl App { ID_EXPORT_ALL => self.export_check_all(true), ID_EXPORT_NONE => self.export_check_all(false), ID_SETTINGS => self.open_settings_menu(), + ID_DATA => self.open_data_menu(), + ID_MEDIA_TOOLBAR => return self.build_install_media_dialog(), ID_LOG_TOGGLE => self.toggle_log_view(), ID_BUG_REPORT => return Some(self.build_report_dialog()), ID_REPORT_SEND => self.send_report(), @@ -6299,19 +6543,12 @@ impl App { .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_else(|| path.clone()); - self.install_local_label - .set_label(&format!("Using local file: {name}")); - let board = self.install_board.clone(); - self.install_plan_label - .set_label(&afw_plan_text(&path, &board)); + self.install_local_label.set_label(&name); self.install_local_path = Some(path); self.install_dialog.layout(); } else { self.install_local_label - .set_label("(none; using the selected release above)"); - self.install_plan_label.set_label( - "Flash plan: pick a local .afw above to see its tier and what it overwrites.", - ); + .set_label("(using selected release)"); self.install_local_path = None; } } @@ -6335,6 +6572,24 @@ impl App { self.uninstall_ips.clear(); self.uninstall_dialog.close(0); } + ID_MEDIA_OK => self.apply_make_media_confirm(), + ID_MEDIA_CANCEL => self.media_dialog.close(0), + ID_MEDIA_RELOAD_DEVS => self.populate_media_devices(), + ID_MEDIA_BROWSE => { + if let Some(path) = Widget::file_dialog( + self.media_dialog, + "Choose an .afw (alkane) or a stock vendor package (.zip)", + ) { + let name = std::path::Path::new(&path) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| path.clone()); + self.media_source_label + .set_label(&format!("Source: {name}")); + self.media_source_path = Some(path); + self.media_dialog.layout(); + } + } ID_POOLS_OK => self.apply_pools(), ID_POOLS_CANCEL => self.pools_dialog.close(0), // Pool-preset manager buttons (round 18 #8b). diff --git a/docs/install.md b/docs/install.md index 309957b6..6ba8a961 100644 --- a/docs/install.md +++ b/docs/install.md @@ -1,5 +1,10 @@ # Installing and removing alkane-os +> For building bootable **SD installation media** (stock-recovery cards and +> alkane boot/installer cards) for card-bootable boards, see +> [installation-media.md](installation-media.md). That is a separate, physical +> path alongside the network-only install described here. + Two front-ends drive the same self-contained engine: - The CLI (`alkane-cli afw ...`), documented below, is the scriptable path. diff --git a/docs/installation-media.md b/docs/installation-media.md new file mode 100644 index 00000000..3e99d4af --- /dev/null +++ b/docs/installation-media.md @@ -0,0 +1,70 @@ +# Installation Media (bootable SD cards) + +The toolkit can build a **bootable SD/removable-media card** for control boards +that boot from a card. This is a separate, sanctioned path alongside the +network-only `.afw` install: the ordinary alkane install still runs over the +network from whatever OS the board has, and SD media exists for + +- recovering a board to genuine stock, and +- bootstrapping or installing alkane onto a board through a card. + +It is a **physical** path (insert a card, boot, remove), by design -- unlike the +network install, which needs no physical access. + +## Which boards + +SD media is offered only for boards whose bootrom / stock bootloader boots from a +card. Today that is the **Antminer S17 / Zynq-7010** control board, where the +stock U-Boot card-detects a plain FAT32 card and side-loads the card's boot trio +(confirmed on hardware: no boot-mode strap and no `uEnv.txt` needed, with the +stock bootloader intact). The Amlogic **A113D is excluded** -- it is eMMC-only +with no SD slot (USB recovery disabled), so it stays network-only. + +## What you can build + +| Kind | What it does | +|------|--------------| +| **Stock recovery** | Replicates a genuine Bitmain vendor SD-recovery package onto a card: boot it to write genuine stock back into NAND. You supply the vendor package. | +| **Alkane: run from SD** | Boots alkane from the card each power-on; nothing is written to the board. Good for a non-destructive try-out. | +| **Alkane: installer** | Boots an installer OS from the card that writes alkane into the board's own storage, verifies, and signals the red/green LEDs when done -- then you power off, remove the card, and boot internal alkane. | + +The card is always built as an **image file first** (root-free), then written to +the device. The image is identical to what lands on the card, so it can be +inspected or kept. + +## GUI + +Scan the fleet, right-click a card-bootable board, and choose **Installation +Media (SD card)...**. Pick the kind, Browse to the source (an `.afw` for alkane, +or a genuine vendor package `.zip` for stock recovery), choose the target SD card +(or "build an image file only"), and click **Create**. Writing to a card erases +it entirely -- confirm the target device first. + +## CLI + +``` +# Stock recovery card from a genuine vendor package: +alkane-cli afw make-media --kind stock \ + --stock-package SD_S17.zip --out card.img \ + [--write /dev/sdX --confirm WRITE] + +# Alkane card from an .afw (simpleboot = run from SD, installer = flash to board): +alkane-cli afw make-media --kind alkane --mode installer \ + --afw alkane-os--zynq-7010.afw --allow-unsigned --out card.img \ + [--write /dev/sdX --confirm WRITE] +``` + +Omit `--write` to build only the image file. Writing to a real device requires +`--confirm WRITE`. `--board` defaults to `zynq-7010` (the only supported board +for now). + +## Safety notes + +- **Writing a card erases the whole device.** The GUI device list shows only + removable disks and never a system disk, but always confirm the target. +- Stock recovery relies on the board's **existing stock bootloader** being + intact (it recovers broken userspace/kernel). If the bootloader itself were + wiped, a full card-boot path is needed instead -- a separate case. +- The alkane installer preserves the board's boot-critical regions (on Zynq, + `BOOT.bin` at `0x0..0x1a00000` is never written), mirroring the network + installer's guarantees. diff --git a/thirdparty/wx-rs/patches/0010-svg-button.patch b/thirdparty/wx-rs/patches/0010-svg-button.patch new file mode 100644 index 00000000..b6a08d4c --- /dev/null +++ b/thirdparty/wx-rs/patches/0010-svg-button.patch @@ -0,0 +1,56 @@ +Subject: [PATCH 0010] svg_button: clickable SVG icon button for the toolbar + +--- a/cpp_src/widgets_bridge.cpp ++++ b/cpp_src/widgets_bridge.cpp +@@ -2140,6 +2140,18 @@ + return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle); + } + ++// Like wxbr_svg_icon, but a clickable button: render the (already-recoloured) ++// SVG into a w x h DIP bitmap bundle and wrap it in a wxBitmapButton that emits ++// WxEV_BUTTON_CLICKED with `id`. Used for the toolbar's icon buttons. ++void* wxbr_svg_button(void* parent, const char* svg, int id, int w, int h) { ++ wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h)); ++ wxBitmapButton* btn = new wxBitmapButton((wxWindow*)parent, id, bundle); ++ btn->Bind(wxEVT_BUTTON, [id](wxCommandEvent&) { ++ if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0); ++ }); ++ return (void*)btn; ++} ++ + // Register a raw SVG (with its viewBox width/height for aspect) for a table-cell + // shape sentinel, so the SegmentRenderer can draw it recoloured to the cell's + // segment colour (round 12 #9 access padlocks, #11 status KPI icons). Replaces +--- a/src/widgets.rs ++++ b/src/widgets.rs +@@ -121,6 +121,13 @@ + pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int); + pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void; + pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void; ++ pub fn wxbr_svg_button( ++ parent: *mut c_void, ++ svg: *const c_char, ++ id: c_int, ++ w: c_int, ++ h: c_int, ++ ) -> *mut c_void; + pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int); + pub fn wxbr_set_light_pulse(on: c_int); + pub fn wxbr_bind_sys_colour(win: *mut c_void); +@@ -949,6 +956,16 @@ + Widget(unsafe { notsafe::wxbr_svg_icon(parent.0, c.as_ptr(), w as c_int, h as c_int) }) + } + ++ /// A clickable icon button: render the (already-recoloured) SVG into a ++ /// `w`x`h` DIP bitmap button that emits a button click with `id`. Recolour ++ /// the SVG first (explicit fill, not `currentColor`). ++ pub fn svg_button(parent: Widget, svg: &str, id: i32, w: i32, h: i32) -> Widget { ++ let c = CString::new(svg).unwrap_or_default(); ++ Widget(unsafe { ++ notsafe::wxbr_svg_button(parent.0, c.as_ptr(), id as c_int, w as c_int, h as c_int) ++ }) ++ } ++ + /// Listen for OS light/dark theme changes on this window (emits `SysColour`). + pub fn bind_sys_colour(&self) { + unsafe { notsafe::wxbr_bind_sys_colour(self.0) } diff --git a/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp b/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp index 02818d53..897f51ae 100644 --- a/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp +++ b/thirdparty/wx-rs/wx-rs-0.2.0-patched/cpp_src/widgets_bridge.cpp @@ -2140,6 +2140,18 @@ void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) { return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle); } +// Like wxbr_svg_icon, but a clickable button: render the (already-recoloured) +// SVG into a w x h DIP bitmap bundle and wrap it in a wxBitmapButton that emits +// WxEV_BUTTON_CLICKED with `id`. Used for the toolbar's icon buttons. +void* wxbr_svg_button(void* parent, const char* svg, int id, int w, int h) { + wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h)); + wxBitmapButton* btn = new wxBitmapButton((wxWindow*)parent, id, bundle); + btn->Bind(wxEVT_BUTTON, [id](wxCommandEvent&) { + if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0); + }); + return (void*)btn; +} + // Register a raw SVG (with its viewBox width/height for aspect) for a table-cell // shape sentinel, so the SegmentRenderer can draw it recoloured to the cell's // segment colour (round 12 #9 access padlocks, #11 status KPI icons). Replaces diff --git a/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs b/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs index 2b89079e..e672f87d 100644 --- a/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs +++ b/thirdparty/wx-rs/wx-rs-0.2.0-patched/src/widgets.rs @@ -121,6 +121,13 @@ mod notsafe { pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int); pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void; pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void; + pub fn wxbr_svg_button( + parent: *mut c_void, + svg: *const c_char, + id: c_int, + w: c_int, + h: c_int, + ) -> *mut c_void; pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int); pub fn wxbr_set_light_pulse(on: c_int); pub fn wxbr_bind_sys_colour(win: *mut c_void); @@ -949,6 +956,16 @@ impl Widget { Widget(unsafe { notsafe::wxbr_svg_icon(parent.0, c.as_ptr(), w as c_int, h as c_int) }) } + /// A clickable icon button: render the (already-recoloured) SVG into a + /// `w`x`h` DIP bitmap button that emits a button click with `id`. Recolour + /// the SVG first (explicit fill, not `currentColor`). + pub fn svg_button(parent: Widget, svg: &str, id: i32, w: i32, h: i32) -> Widget { + let c = CString::new(svg).unwrap_or_default(); + Widget(unsafe { + notsafe::wxbr_svg_button(parent.0, c.as_ptr(), id as c_int, w as c_int, h as c_int) + }) + } + /// Listen for OS light/dark theme changes on this window (emits `SysColour`). pub fn bind_sys_colour(&self) { unsafe { notsafe::wxbr_bind_sys_colour(self.0) }