diff --git a/crates/alkane-artifacts/src/afw.rs b/crates/alkane-artifacts/src/afw.rs index 1dda0c5d..6f8e824c 100644 --- a/crates/alkane-artifacts/src/afw.rs +++ b/crates/alkane-artifacts/src/afw.rs @@ -155,6 +155,54 @@ pub struct AfwManifest { pub notes: Option, } +/// What an `.afw` bundle overwrites on the target, derived from its manifest. +/// +/// Tiers mirror the flash tiers: 1 = update (userspace / HAL only, no kernel or +/// bootloader write), 2 = kernel (kernel, dtb and boot images; bootloader +/// preserved), 3 = bootloader (U-Boot/SPL is rewritten as well). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct FlashPlan { + pub tier: u8, + pub writes_uboot: bool, + pub writes_kernel: bool, + pub writes_userspace: bool, +} + +impl AfwManifest { + /// Compute the flash tier and the regions this bundle overwrites. Pure + /// computation over the parsed manifest; no device or file access. + /// + /// - `writes_uboot`: `bootloader_policy` is [`BootloaderPolicy::Include`] + /// (anything but `Preserve`), or an image with role `bootloader` exists. + /// - `writes_kernel`: an image with role `kernel`, `dtb` or `boot` exists. + /// - `writes_userspace`: an image with role `rootfs` exists. + /// - `tier`: 3 if `writes_uboot`, else 2 if `writes_kernel`, else 1. + pub fn flash_plan(&self) -> FlashPlan { + let has_role = |roles: &[&str]| { + self.images + .iter() + .any(|image| roles.contains(&image.role.as_str())) + }; + let writes_uboot = + self.bootloader_policy != BootloaderPolicy::Preserve || has_role(&["bootloader"]); + let writes_kernel = has_role(&["kernel", "dtb", "boot"]); + let writes_userspace = has_role(&["rootfs"]); + let tier = if writes_uboot { + 3 + } else if writes_kernel { + 2 + } else { + 1 + }; + FlashPlan { + tier, + writes_uboot, + writes_kernel, + writes_userspace, + } + } +} + #[derive(Clone, Debug, Eq, PartialEq)] pub struct AfwMember { pub name: String, @@ -1080,6 +1128,106 @@ mod tests { )); } + /// Build a parsed manifest with the given bootloader policy and one image + /// per listed role (payload bytes are irrelevant to `flash_plan`). + fn plan_manifest(policy: &str, roles: &[&str]) -> AfwManifest { + let mut value = manifest(&[0_u8; 4]); + value["bootloader_policy"] = json!(policy); + value["images"] = json!(roles + .iter() + .enumerate() + .map(|(i, role)| json!({ + "name": format!("img{i}"), "file": format!("payload/img{i}"), + "role": role, "format": "raw", "size": 4, "sha256": "0".repeat(64), + "partition": null, "install": false + })) + .collect::>()); + serde_json::from_value(value).unwrap() + } + + #[test] + fn flash_plan_tier2_preserve_kernel_and_rootfs() { + let plan = plan_manifest("preserve", &["kernel", "dtb", "rootfs"]).flash_plan(); + assert_eq!(plan.tier, 2); + assert!(plan.writes_kernel); + assert!(plan.writes_userspace); + assert!(!plan.writes_uboot); + } + + #[test] + fn flash_plan_tier3_include_with_bootloader_image() { + let plan = + plan_manifest("include", &["bootloader", "kernel", "dtb", "rootfs"]).flash_plan(); + assert_eq!(plan.tier, 3); + assert!(plan.writes_uboot); + assert!(plan.writes_kernel); + assert!(plan.writes_userspace); + } + + #[test] + fn flash_plan_tier3_from_bootloader_image_alone() { + // A bootloader image forces tier 3 even if the policy says preserve + // (verification rejects that combination, but the plan stays safe). + let plan = plan_manifest("preserve", &["bootloader"]).flash_plan(); + assert_eq!(plan.tier, 3); + assert!(plan.writes_uboot); + assert!(!plan.writes_kernel); + assert!(!plan.writes_userspace); + } + + #[test] + fn flash_plan_tier3_from_include_policy_alone() { + let plan = plan_manifest("include", &["rootfs"]).flash_plan(); + assert_eq!(plan.tier, 3); + assert!(plan.writes_uboot); + assert!(!plan.writes_kernel); + assert!(plan.writes_userspace); + } + + #[test] + fn flash_plan_tier1_rootfs_only() { + let plan = plan_manifest("preserve", &["rootfs"]).flash_plan(); + assert_eq!(plan.tier, 1); + assert!(plan.writes_userspace); + assert!(!plan.writes_kernel); + assert!(!plan.writes_uboot); + } + + #[test] + fn flash_plan_boot_role_counts_as_kernel() { + let plan = plan_manifest("preserve", &["boot"]).flash_plan(); + assert_eq!(plan.tier, 2); + assert!(plan.writes_kernel); + assert!(!plan.writes_userspace); + assert!(!plan.writes_uboot); + // The shared cv1835 fixture is a single "boot" FIT under preserve. + let fixture: AfwManifest = serde_json::from_value(manifest(&[0_u8; 4])).unwrap(); + assert_eq!(fixture.flash_plan().tier, 2); + } + + #[test] + fn flash_plan_component_only_is_tier1_with_no_regions() { + let plan = plan_manifest("preserve", &["component"]).flash_plan(); + assert_eq!(plan.tier, 1); + assert!(!plan.writes_uboot); + assert!(!plan.writes_kernel); + assert!(!plan.writes_userspace); + } + + #[test] + fn flash_plan_empty_images_preserve_is_tier1() { + let plan = plan_manifest("preserve", &[]).flash_plan(); + assert_eq!(plan.tier, 1); + assert!(!plan.writes_uboot && !plan.writes_kernel && !plan.writes_userspace); + } + + #[test] + fn flash_plan_tier3_dominates_kernel() { + let plan = plan_manifest("include", &["bootloader", "kernel"]).flash_plan(); + assert_eq!(plan.tier, 3); + assert!(plan.writes_uboot && plan.writes_kernel); + } + #[test] fn refuses_a_hash_mismatch() { let p1 = p1_image(P1); diff --git a/crates/alkane-artifacts/src/fetch.rs b/crates/alkane-artifacts/src/fetch.rs index aaf43149..3a8c4958 100644 --- a/crates/alkane-artifacts/src/fetch.rs +++ b/crates/alkane-artifacts/src/fetch.rs @@ -60,6 +60,14 @@ impl ReleaseSource { /// The alkane-os release source, honoring `ALKANE_RELEASE_BASE` and a token /// from `ALKANE_RELEASE_TOKEN` or `GITEA_TOKEN`. pub fn alkane_os() -> Self { + 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`. + pub fn for_repo(owner: &str, repo: &str) -> Self { let base_url = std::env::var("ALKANE_RELEASE_BASE") .ok() .filter(|s| !s.is_empty()) @@ -71,8 +79,8 @@ impl ReleaseSource { .or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty())); Self { base_url, - owner: "blueflare".to_string(), - repo: "alkane-os".to_string(), + owner: owner.to_string(), + repo: repo.to_string(), token, } } @@ -223,6 +231,18 @@ pub fn fetch_latest_afw( Ok(dest) } +/// Board tokens recognised in `.afw` asset names (the `--` filename +/// segment). Used by `ReleaseInfo::compatible_boards`. +pub const KNOWN_BOARDS: &[&str] = &[ + "zynq-7010", + "am335x", + "cv1835", + "a113d", + "allwinner-h3", + "allwinner-h6", + "allwinner-h616", +]; + /// One `.afw` asset in a release. #[derive(Debug, Clone)] pub struct AfwAsset { @@ -249,6 +269,30 @@ impl ReleaseInfo { let needle = format!("-{board}-"); self.afw_assets.iter().find(|a| a.name.contains(&needle)) } + + /// The distinct board tokens (from `KNOWN_BOARDS`) this release carries an + /// `.afw` for, detected from the asset filenames (`--` segment, e.g. + /// `alkane-os-0.1.2-zynq-7010-armv7.afw` -> `zynq-7010`). Ordered by first + /// appearance across the assets; a release with no recognised board yields an + /// empty list. + pub fn compatible_boards(&self) -> Vec { + let mut boards: Vec = Vec::new(); + for asset in &self.afw_assets { + for board in KNOWN_BOARDS { + let needle = format!("-{board}-"); + if asset.name.contains(&needle) && !boards.iter().any(|b| b == board) { + boards.push((*board).to_string()); + } + } + } + boards + } + + /// Whether this release has an `.afw` for `board` (same match as + /// `asset_for_board`). + pub fn is_compatible_with(&self, board: &str) -> bool { + self.asset_for_board(board).is_some() + } } /// Parse a Gitea releases array (newest first) into `ReleaseInfo`s, keeping only @@ -401,4 +445,84 @@ mod tests { ); assert!(parsed[1].asset_for_board("zynq-7010").is_none()); } + + #[test] + fn for_repo_builds_the_api_url_for_a_custom_repo() { + std::env::remove_var("ALKANE_RELEASE_BASE"); + let src = ReleaseSource::for_repo("someorg", "some-firmware"); + assert_eq!(src.owner, "someorg"); + assert_eq!(src.repo, "some-firmware"); + assert_eq!( + src.api_list(), + "https://gitea.bluefla.re/api/v1/repos/someorg/some-firmware/releases?limit=50" + ); + // alkane_os() is for_repo("blueflare", "alkane-os"). + let os = ReleaseSource::alkane_os(); + assert_eq!( + (os.owner.as_str(), os.repo.as_str()), + ("blueflare", "alkane-os") + ); + } + + fn release_with(names: &[&str]) -> ReleaseInfo { + ReleaseInfo { + tag: "v0.1.2".into(), + name: String::new(), + prerelease: false, + draft: false, + published_at: String::new(), + afw_assets: names + .iter() + .map(|n| AfwAsset { + name: (*n).to_string(), + url: format!("https://example.invalid/{n}"), + }) + .collect(), + } + } + + #[test] + fn compatible_boards_extracts_board_tokens_from_asset_names() { + let single = release_with(&["alkane-os-0.1.2-zynq-7010-armv7.afw"]); + assert_eq!(single.compatible_boards(), vec!["zynq-7010"]); + + // Multi-board release: distinct boards in first-appearance order, + // duplicates (a second arch build of one board) collapse. + let multi = release_with(&[ + "alkane-os-0.1.2-am335x-armv7.afw", + "alkane-os-0.1.2-zynq-7010-armv7.afw", + "alkane-os-0.1.2-allwinner-h616-aarch64.afw", + "alkane-os-0.1.2-am335x-arm.afw", + "alkane-os-0.1.2-cv1835-riscv64.afw", + ]); + assert_eq!( + multi.compatible_boards(), + vec!["am335x", "zynq-7010", "allwinner-h616", "cv1835"] + ); + + // allwinner-h6 must not match an allwinner-h616 asset (and vice versa). + let h616 = release_with(&["alkane-os-0.1.2-allwinner-h616-aarch64.afw"]); + assert_eq!(h616.compatible_boards(), vec!["allwinner-h616"]); + let h6 = release_with(&["alkane-os-0.1.2-allwinner-h6-aarch64.afw"]); + assert_eq!(h6.compatible_boards(), vec!["allwinner-h6"]); + + // No .afw assets, or an unrecognised board, yields nothing. + assert!(release_with(&[]).compatible_boards().is_empty()); + assert!(release_with(&["alkane-os-0.1.2-mystery-board-arm.afw"]) + .compatible_boards() + .is_empty()); + } + + #[test] + fn is_compatible_with_matches_asset_for_board() { + let rel = release_with(&[ + "alkane-os-0.1.2-zynq-7010-armv7.afw", + "alkane-os-0.1.2-a113d-aarch64.afw", + ]); + assert!(rel.is_compatible_with("zynq-7010")); + assert!(rel.is_compatible_with("a113d")); + assert!(!rel.is_compatible_with("am335x")); + assert!(!rel.is_compatible_with("allwinner-h6")); + assert!(!release_with(&[]).is_compatible_with("zynq-7010")); + } } diff --git a/crates/alkane-cli/src/main.rs b/crates/alkane-cli/src/main.rs index 14d37dd7..513c1e21 100644 --- a/crates/alkane-cli/src/main.rs +++ b/crates/alkane-cli/src/main.rs @@ -23,6 +23,7 @@ use alkane_flash::stock; use alkane_flash::stock::{InPlaceOptions, InPlaceOutcome, RestoreImages}; use alkane_flash::stock_firmware; use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport}; +use alkane_flash::zynq_nand; use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::{Path, PathBuf}; @@ -1039,8 +1040,13 @@ fn latest_backup(dir: &Path) -> Option { /// Boards this toolkit can install alkane onto, with the miner each is the /// control board for. The install/restore gate is the .afw's board matching one /// of these; `compat` lists them so an operator knows what is supported. -const SUPPORTED: &[(&str, &str)] = - &[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")]; +const SUPPORTED: &[(&str, &str)] = &[ + ("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"), + ( + "a113d", + "Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)", + ), +]; fn is_supported(board: &str) -> bool { SUPPORTED.iter().any(|(b, _)| *b == board) @@ -1112,14 +1118,48 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box> &["dry-run"], )?; let host = opts.value("host").ok_or("--host is required")?.to_owned(); - let firmware = opts.value("stock-firmware").ok_or( - "--stock-firmware is required \ - (an OTA update .tar.gz or an SD recovery .zip for this board)", - )?; // Restore reaches the alkane board over SSH as root; the board credential is // supplied via --password-file / ALKANE_BOARD_PASSWORD(_FILE). let password = read_board_password(&opts)?; + // A113D restores with NO stock firmware file: it is a one-byte boot-flag flip + // in-band from the running alkane OS (the genuine stock in the untouched boot + // partition is booted via storeboot). Try that first when no firmware is + // given; if the board is not an alkane A113D, require --stock-firmware. + let firmware = match opts.value("stock-firmware") { + Some(f) => f, + None => { + if opts.flag("dry-run") { + println!("DRY RUN: would restore {host} to stock by flipping the A113D boot flag"); + println!( + "(no stock firmware needed; the untouched stock boot partition is booted)." + ); + println!("Re-run with --confirm FLASH."); + return Ok(()); + } + if opts.value("confirm") != Some("FLASH") { + return Err("refusing to restore without --confirm FLASH".into()); + } + println!("restoring {host} to genuine stock (A113D flag flip, network-only)..."); + match stock::restore_aml_flag(&host, password.as_deref()) { + Ok(()) => { + println!( + "restore reported success (boot flag cleared; stock boots via storeboot)." + ); + println!("verify independently: the board should present genuine stock"); + println!("(cgminer API on :4028, lighttpd 401 on :80, dropbear 2018.x)."); + return Ok(()); + } + Err(alkane_flash::stock::StockError::NotApplicable) => { + return Err("this board is not an alkane A113D; pass --stock-firmware \ + to restore it" + .into()); + } + Err(e) => return Err(e.into()), + } + } + }; + // Parse the genuine vendor package for the stock kernel + rootfs. The kernel // device tree is not in distributable Bitmain firmware; the toolkit supplies // the correct per-board dtb, so any genuine package (OTA or SD) works here. @@ -1139,6 +1179,7 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box> let images = RestoreImages { kernel: &fw.kernel, rootfs: &fw.rootfs, + dtb: fw.dtb.as_deref(), }; stock::restore_to_stock(&host, &images, password.as_deref())?; println!("restore-to-stock reported success (stock images written, BOOT.bin preserved)."); @@ -1147,9 +1188,209 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box> Ok(()) } +/// Run a command as root on a stock board and print its output (drives the DSH +/// root-on-stock primitive; used to build and debug the flash operations). +fn run_root_run(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, ssh_values(), &[])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let cmd = opts.positionals.join(" "); + if cmd.trim().is_empty() { + return Err("usage: alkane-cli afw root-run --host ".into()); + } + let password = read_board_password(&opts)?; + let out = stock::root_exec(&host, password.as_deref(), &cmd)?; + print!("{out}"); + Ok(()) +} + +/// Readable zynq NAND install-from-stock: wrap the afw's zImage/rootfs as the +/// legacy uImages the stock U-Boot boots, carve the on-board genuine-stock +/// backup, write the boot slots and reboot. Drives the DSH root-on-stock +/// primitive; board must be on stock (credential root/root). +fn run_nand_install(args: &[String]) -> Result<(), Box> { + let opts = parse_args( + args, + &[ssh_values(), &["confirm"]].concat(), + &["allow-unsigned"], + )?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let afw_path = opts + .positionals + .first() + .ok_or("usage: alkane-cli afw nand-install --host --confirm FLASH")?; + let verified = load_afw(afw_path, &opts)?; + if !zynq::owns_board(&verified.manifest.board) { + return Err(format!( + "nand-install is zynq-7010 only, not {}", + verified.manifest.board + ) + .into()); + } + if opts.value("confirm") != Some("FLASH") { + return Err("refusing to install without --confirm FLASH".into()); + } + let kernel = verified + .image("kernel") + .ok_or("afw missing kernel image")? + .1; + let dtb = verified.image("dtb").ok_or("afw missing dtb image")?.1; + let rootfs = verified + .image("rootfs") + .ok_or("afw missing rootfs image")? + .1; + let password = read_board_password(&opts)?; + println!( + "installing {} onto stock board {host} (readable NAND path)...", + verified.manifest.board + ); + zynq_nand::install_from_stock(&host, kernel, dtb, rootfs, password.as_deref())?; + println!( + "install reported success (on-board stock backup carved; boot slots written; rebooting)." + ); + print!("{}", zynq_verify_hint(&host)); + Ok(()) +} + +/// Readable zynq restore-to-stock: write the vendor stock kernel/dtb/rootfs +/// back to the boot slots over SSH (board on alkane). Needs the alkane image +/// that exposes the boot partitions. +fn run_nand_restore_stock(args: &[String]) -> Result<(), Box> { + let opts = parse_args( + args, + &[ssh_values(), &["confirm", "stock-firmware"]].concat(), + &["dry-run"], + )?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let firmware = opts + .value("stock-firmware") + .ok_or("--stock-firmware is required")?; + let fw = stock_firmware::parse(Path::new(firmware))?; + println!("stock firmware: {}", fw.summary()); + if opts.value("confirm") != Some("FLASH") { + return Err("refusing to restore without --confirm FLASH".into()); + } + let password = read_board_password(&opts)?; + println!("restoring {host} to genuine stock (readable NAND path)..."); + zynq_nand::restore_to_stock( + &host, + &fw.kernel, + &fw.rootfs, + fw.dtb.as_deref(), + password.as_deref(), + )?; + println!( + "restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved)." + ); + Ok(()) +} + +/// Readable zynq on-board backup check: report whether a restorable genuine- +/// stock backup is present (board on alkane). Read-only. +fn run_nand_backup_check(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, ssh_values(), &[])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let password = read_board_password(&opts)?; + if zynq_nand::onboard_backup_present(&host, password.as_deref())? { + println!("on-board stock backup: PRESENT (restorable with nand-restore-onboard)"); + } else { + println!("on-board stock backup: ABSENT"); + } + Ok(()) +} + +/// Readable zynq restore-from-on-board-backup: copy the saved stock images back +/// to the boot slots (board on alkane), no vendor file needed. +fn run_nand_restore_onboard(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &[])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + if opts.value("confirm") != Some("FLASH") { + return Err("refusing to restore without --confirm FLASH".into()); + } + let password = read_board_password(&opts)?; + println!("restoring {host} to stock from its on-board backup (readable NAND path)..."); + zynq_nand::restore_from_onboard(&host, password.as_deref())?; + println!("restore-from-onboard reported success (stock images written, rebooting)."); + Ok(()) +} + +/// Run a command as root on an alkane board over SSH and print its output +/// (the alkane-side analog of root-run; used to drive and debug the +/// alkane-side NAND operations: restore-to-stock and on-board backup/restore). +fn run_ssh_run(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, ssh_values(), &[])?; + let cmd = opts.positionals.join(" "); + if cmd.trim().is_empty() { + return Err("usage: alkane-cli afw ssh-run --host ".into()); + } + let (ssh, _secret) = ssh_options(&opts, "root")?; + let mut transport = SshTransport::connect(ssh, true)?; + let out = transport.root_command(&cmd, std::time::Duration::from_secs(120))?; + print!("{}", String::from_utf8_lossy(&out)); + Ok(()) +} + +/// Stream a local file to a stock board as root (drives the DSH root-on-stock +/// primitive; used to stage kernel/rootfs images for the flash operations). +fn run_root_put(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, &[ssh_values(), &["remote"]].concat(), &[])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let remote = opts + .value("remote") + .ok_or("--remote is required")? + .to_owned(); + let local = opts + .positionals + .first() + .ok_or("usage: alkane-cli afw root-put --host --remote ")?; + let data = std::fs::read(local)?; + let password = read_board_password(&opts)?; + stock::root_put(&host, password.as_deref(), &data, &remote)?; + println!("put {} bytes -> {remote}", data.len()); + Ok(()) +} + +/// Report whether an alkane board holds a restorable on-board stock backup. +/// Read-only (no FLASH confirmation). +fn run_backup_check(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, ssh_values(), &[])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let password = read_board_password(&opts)?; + let present = stock::onboard_stock_backup_present(&host, password.as_deref())?; + println!("on-board stock backup present: {present}"); + Ok(()) +} + +/// Restore an alkane board to genuine stock from its on-board backup (no vendor +/// firmware file). Destructive; gated by --confirm FLASH. +fn run_restore_onboard(args: &[String]) -> Result<(), Box> { + let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["dry-run"])?; + let host = opts.value("host").ok_or("--host is required")?.to_owned(); + let password = read_board_password(&opts)?; + if opts.flag("dry-run") { + println!( + "DRY RUN: would restore {host} to stock from its on-board backup \ + (BOOT.bin preserved). Re-run with --confirm FLASH." + ); + return Ok(()); + } + if opts.value("confirm") != Some("FLASH") { + return Err("refusing to restore without --confirm FLASH".into()); + } + println!("restoring {host} to stock from its on-board backup (network-only)..."); + stock::restore_from_onboard_backup( + &host, + password.as_deref(), + std::time::Duration::from_secs(300), + )?; + println!( + "restore-from-onboard reported success. Verify independently the board answers as stock." + ); + 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() { @@ -1163,6 +1404,15 @@ fn run_afw(args: &[String]) -> Result<(), Box> { "verify-live" => run_verify_live(rest), "restore" => run_restore(rest), "restore-stock" => run_restore_stock(rest), + "backup-check" => run_backup_check(rest), + "restore-onboard" => run_restore_onboard(rest), + "root-run" => run_root_run(rest), + "root-put" => run_root_put(rest), + "ssh-run" => run_ssh_run(rest), + "nand-install" => run_nand_install(rest), + "nand-restore-stock" => run_nand_restore_stock(rest), + "nand-backup-check" => run_nand_backup_check(rest), + "nand-restore-onboard" => run_nand_restore_onboard(rest), other => Err(format!("unknown afw subcommand {other}").into()), } } diff --git a/crates/alkane-flash/src/aml_ubi.rs b/crates/alkane-flash/src/aml_ubi.rs new file mode 100644 index 00000000..f78dfade --- /dev/null +++ b/crates/alkane-flash/src/aml_ubi.rs @@ -0,0 +1,660 @@ +// SPDX-License-Identifier: MIT +//! Readable Amlogic A113D (Amlogic AXG, Antminer BHB42XXX) install/restore over +//! the FLAG-BASED boot chain. This is the Claude-domain counterpart of +//! `zynq_nand`: it drives the DSH root-on-stock primitive (`stock::root_exec` / +//! `stock::root_put`) for the from-stock install, and the alkane SSH transport +//! for the in-band restore, with the stock-access method never read here. +//! +//! Mechanism (CONFIRMED live 2026-11-13, see alkane-sdk-construction +//! alkane-a113d-image-bringup): +//! +//! - The OS files `alkane/{vmlinux.bin,devicetree.dtb,uramdisk.image.gz}` are +//! staged into the nvdata UBI volume (UBIFS), exactly as the alkane boot chain +//! reads them (`ubifsload`). Zero raw writes to the brick-sensitive regions. +//! - A one-byte-magic FLAG lives in the `misc` partition (the Android BCB block, +//! abs NAND 0x1000000) at erase-block 1 (offset 0x20000, abs 0x1020000). Block +//! 0 (the BCB) is never touched. The flag is the four bytes "ALAN". +//! - Stock U-Boot's `bootcmd` is set (once, in-band via /dev/nand_env from stock) +//! to `run checkalk; run storeboot`, where `checkalk` RAW-reads the flag page +//! (`nand read`, NO UBI) and, only if the magic matches, runs `alkboot` (which +//! mounts the nvdata UBIFS and boots alkane). When the flag is absent the stock +//! path is a pure raw read + `storeboot`, which boots genuine stock STABLY (a +//! ubi/ubifs op in the stock boot path instead makes stock's firstboot +//! supervisor reboot-loop - that is why the flag read must be raw). +//! - INSTALL (stock -> alkane): stage the files, write the env, set flag=ALAN. +//! - RESTORE (alkane -> stock): erase the flag block in-band from the running +//! alkane OS (which exposes `misc` as an MTD). One raw NAND erase, `reboot -f`, +//! and stock boots via `storeboot`. Fully network-only; the alkane payload and +//! the env are left in place, so re-install is just re-writing the flag. +//! +//! itest note: this vendor U-Boot's `itest.l *` does NOT compare correctly, +//! but `itest.b *` does, so `checkalk` tests the four magic bytes with +//! nested `itest.b`. CONFIRMED live 2026-11-13. + +use crate::stock::StockError; +use crate::transport::{Remote, SshOptions, SshTransport}; +use crate::uimage::crc32; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +pub const BOARD: &str = "a113d"; + +/// U-Boot env blob size on this board (CONFIRMED: `/dev/nand_env` is 64 KiB, a +/// standard U-Boot env = 4-byte little-endian CRC32 + NUL-separated key=value, +/// double-NUL terminated, 0x00-padded). +const ENV_SIZE: usize = 65536; + +/// Flag: four magic bytes "ALAN" at misc (abs 0x1000000) erase-block 1. +const FLAG_ABS_OFFSET: u64 = 0x1020000; // misc base 0x1000000 + block 1 (0x20000) +const FLAG_BLOCK_IN_MISC: u64 = 0x20000; // offset of the flag block within the misc MTD +const FLAG_MAGIC: [u8; 4] = *b"ALAN"; + +/// Boot load addresses (CONFIRMED live) and the alkane console bootargs. +const KRNADDR: &str = "0x1200000"; +const FDTADDR: &str = "0x8000000"; +const RDADDR: &str = "0x8100000"; +const ALK_BOOTARGS: &str = "console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend"; + +/// The on-board basenames inside the nvdata UBI volume's `alkane/` directory. +const ALKANE_DIR: &str = "alkane"; + +// --------------------------------------------------------------------------- +// Shell abstraction: StockShell drives the DSH root primitive; AlkaneShell the +// alkane SSH transport. (Mirrors zynq_nand.) +// --------------------------------------------------------------------------- + +trait Shell { + fn exec(&mut self, cmd: &str) -> Result; + fn exec_long(&mut self, cmd: &str) -> Result; + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError>; +} + +struct StockShell { + host: String, + password: Option, +} + +impl Shell for StockShell { + fn exec(&mut self, cmd: &str) -> Result { + crate::stock::root_exec(&self.host, self.password.as_deref(), cmd) + } + fn exec_long(&mut self, cmd: &str) -> Result { + // root_exec already carries a generous timeout in the method. + crate::stock::root_exec(&self.host, self.password.as_deref(), cmd) + } + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> { + crate::stock::root_put(&self.host, self.password.as_deref(), data, remote_path) + } +} + +struct AlkaneShell { + transport: SshTransport, + _secret: TempFile, +} + +impl AlkaneShell { + fn connect(host: &str, password: Option<&str>) -> Result { + // Password in a 0600 temp file; a throwaway empty known_hosts (the host + // key legitimately changes across stock<->alkane). Same stance as zynq. + let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?; + let known = temp_path("kh"); + let _ = std::fs::File::create(&known); + let options = SshOptions { + host: host.to_owned(), + port: 22, + user: "root".to_owned(), + identity_file: None, + password_file: Some(secret.0.clone()), + known_hosts: Some(known), + root_method: crate::transport::RootMethod::Auto, + update_daemon_port: None, + }; + let transport = + SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?; + Ok(AlkaneShell { + transport, + _secret: secret, + }) + } +} + +impl Shell for AlkaneShell { + fn exec(&mut self, cmd: &str) -> Result { + self.transport + .root_command(cmd, Duration::from_secs(120)) + .map(|o| String::from_utf8_lossy(&o).into_owned()) + .map_err(|e| StockError::Method(e.to_string())) + } + fn exec_long(&mut self, cmd: &str) -> Result { + self.transport + .root_command(cmd, Duration::from_secs(900)) + .map(|o| String::from_utf8_lossy(&o).into_owned()) + .map_err(|e| StockError::Method(e.to_string())) + } + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> { + let tmp = TempFile::with(data, "put")?; + self.transport + .push(&tmp.0, remote_path, Duration::from_secs(900)) + .map_err(|e| StockError::Method(e.to_string())) + } +} + +static TEMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +fn temp_path(tag: &str) -> PathBuf { + let n = TEMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + std::env::temp_dir().join(format!("alkane-aml-{}-{}-{}", std::process::id(), tag, n)) +} + +/// A 0600 temp file removed on drop. +struct TempFile(PathBuf); +impl TempFile { + fn with(contents: &[u8], tag: &str) -> Result { + let path = temp_path(tag); + write_private(&path, contents).map_err(|e| StockError::Io(e.to_string()))?; + Ok(TempFile(path)) + } +} +impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +#[cfg(unix)] +fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> { + use std::io::Write as _; + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new() + .create(true) + .truncate(true) + .write(true) + .mode(0o600) + .open(path)?; + f.write_all(contents)?; + f.flush() +} + +#[cfg(not(unix))] +fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> { + std::fs::write(path, contents) +} + +// --------------------------------------------------------------------------- +// base64 (busybox-safe: decode a possibly line-wrapped stream). +// --------------------------------------------------------------------------- + +fn b64_decode(s: &str) -> Option> { + const INV: u8 = 0xFF; + fn val(c: u8) -> u8 { + match c { + b'A'..=b'Z' => c - b'A', + b'a'..=b'z' => c - b'a' + 26, + b'0'..=b'9' => c - b'0' + 52, + b'+' => 62, + b'/' => 63, + _ => INV, + } + } + let mut out = Vec::new(); + let mut acc = 0u32; + let mut bits = 0u32; + for &c in s.as_bytes() { + if c == b'=' { + break; + } + let v = val(c); + if v == INV { + continue; // skip whitespace / newlines + } + acc = (acc << 6) | v as u32; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + } + } + Some(out) +} + +fn b64_encode(data: &[u8]) -> String { + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); + for chunk in data.chunks(3) { + let b = [ + chunk[0], + *chunk.get(1).unwrap_or(&0), + *chunk.get(2).unwrap_or(&0), + ]; + let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32; + out.push(T[((n >> 18) & 63) as usize] as char); + out.push(T[((n >> 12) & 63) as usize] as char); + out.push(if chunk.len() > 1 { + T[((n >> 6) & 63) as usize] as char + } else { + '=' + }); + out.push(if chunk.len() > 2 { + T[(n & 63) as usize] as char + } else { + '=' + }); + } + out +} + +// --------------------------------------------------------------------------- +// U-Boot environment (standard format) read / parse / build / write. +// --------------------------------------------------------------------------- + +/// Read the 64 KiB U-Boot env blob from /dev/nand_env (stock only). +fn read_env(sh: &mut dyn Shell) -> Result, StockError> { + let out = sh.exec( + "echo B64START; dd if=/dev/nand_env bs=65536 count=1 2>/dev/null | base64; echo B64END", + )?; + let start = out + .find("B64START") + .ok_or_else(|| StockError::Method("env read: no marker".into()))?; + let end = out + .find("B64END") + .ok_or_else(|| StockError::Method("env read: no end marker".into()))?; + let b64 = &out[start + "B64START".len()..end]; + let blob = b64_decode(b64).ok_or_else(|| StockError::Method("env read: bad base64".into()))?; + if blob.len() != ENV_SIZE { + return Err(StockError::Method(format!( + "env read: {} bytes (expected {ENV_SIZE})", + blob.len() + ))); + } + let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]); + if crc32(&blob[4..]) != stored { + return Err(StockError::Method("env read: CRC mismatch".into())); + } + Ok(blob) +} + +/// Parse the env body into ordered (key, value) pairs (up to the double-NUL). +fn parse_env(blob: &[u8]) -> Vec<(String, String)> { + let body = &blob[4..]; + let end = body + .windows(2) + .position(|w| w == [0, 0]) + .unwrap_or(body.len()); + let mut vars = Vec::new(); + for kv in body[..end].split(|&b| b == 0) { + if kv.is_empty() { + continue; + } + if let Some(eq) = kv.iter().position(|&b| b == b'=') { + let k = String::from_utf8_lossy(&kv[..eq]).into_owned(); + let v = String::from_utf8_lossy(&kv[eq + 1..]).into_owned(); + vars.push((k, v)); + } + } + vars +} + +/// Build a 64 KiB env blob from ordered (key,value) pairs: CRC32 + body + +/// double-NUL + 0x00 padding (what a clean `saveenv` produces). +fn build_env(vars: &[(String, String)]) -> Result, StockError> { + let mut body = Vec::with_capacity(ENV_SIZE); + for (k, v) in vars { + body.extend_from_slice(k.as_bytes()); + body.push(b'='); + body.extend_from_slice(v.as_bytes()); + body.push(0); + } + body.push(0); // terminating double-NUL (last var's NUL + this one) + if body.len() > ENV_SIZE - 4 { + return Err(StockError::Method("env too large".into())); + } + body.resize(ENV_SIZE - 4, 0); + let crc = crc32(&body); + let mut blob = Vec::with_capacity(ENV_SIZE); + blob.extend_from_slice(&crc.to_le_bytes()); + blob.extend_from_slice(&body); + Ok(blob) +} + +/// Set (or insert, preserving order) a variable. +fn set_var(vars: &mut Vec<(String, String)>, key: &str, value: &str) { + if let Some(slot) = vars.iter_mut().find(|(k, _)| k == key) { + slot.1 = value.to_owned(); + } else { + vars.push((key.to_owned(), value.to_owned())); + } +} + +/// Write the env blob to /dev/nand_env and read it back byte-exact BEFORE any +/// reboot (the env is only consumed at next boot, so a verified read-back cannot +/// brick). On a read-back mismatch the caller must restore the previous env. +fn write_env(sh: &mut dyn Shell, blob: &[u8]) -> Result<(), StockError> { + let b64 = b64_encode(blob); + // Stream the blob to a temp file, then dd it to /dev/nand_env in one write. + sh.put(b64.as_bytes(), "/tmp/.alkenv.b64")?; + let out = sh.exec( + "base64 -d /tmp/.alkenv.b64 > /tmp/.alkenv.bin 2>/dev/null; \ + dd if=/tmp/.alkenv.bin of=/dev/nand_env bs=65536 count=1 2>/dev/null; sync; \ + echo RB=$(dd if=/dev/nand_env bs=65536 count=1 2>/dev/null | md5sum | cut -d' ' -f1); \ + rm -f /tmp/.alkenv.b64 /tmp/.alkenv.bin", + )?; + let want = md5_hex(blob); + let got = out + .split("RB=") + .nth(1) + .map(|s| s.trim().to_owned()) + .unwrap_or_default(); + if got != want { + return Err(StockError::Method(format!( + "env write read-back mismatch: wrote {want}, read {got}" + ))); + } + Ok(()) +} + +fn md5_hex(data: &[u8]) -> String { + crate::md5::md5_hex(data) +} + +// --------------------------------------------------------------------------- +// MTD / flag helpers. +// --------------------------------------------------------------------------- + +/// Find the /dev/mtdN whose /proc/mtd label matches `name`. +fn find_mtd(sh: &mut dyn Shell, name: &str) -> Result { + let out = sh.exec("cat /proc/mtd")?; + for line in out.lines() { + if line.contains(&format!("\"{name}\"")) { + if let Some((dev, _)) = line.split_once(':') { + return Ok(format!("/dev/{}", dev.trim())); + } + } + } + Err(StockError::Method(format!("no '{name}' MTD on this board"))) +} + +/// Discover the nvdata UBI volume's name (never assumed: vendor histories leave +/// different names). Looks for an already-attached ubi volume on the nvdata MTD. +fn discover_nvdata_volume(sh: &mut dyn Shell) -> Result<(String, String), StockError> { + // Returns (mountpoint, volume_name). On stock the vendor mounts nvdata (e.g. + // at /tmp/miner); find the ubifs mount whose volume sits on the nvdata MTD. + let mounts = sh.exec("cat /proc/mounts")?; + for line in mounts.lines() { + // e.g. "/dev/ubi2_0 /tmp/miner ubifs rw,..." + let mut it = line.split_whitespace(); + let dev = it.next().unwrap_or(""); + let mnt = it.next().unwrap_or(""); + let fs = it.next().unwrap_or(""); + if fs == "ubifs" && dev.contains("ubi") { + // read the volume name from sysfs: /sys/class/ubi//name + let base = dev.trim_start_matches("/dev/"); + let name = sh + .exec(&format!("cat /sys/class/ubi/{base}/name 2>/dev/null"))? + .trim() + .to_owned(); + // Only accept the nvdata volume (skip the small config_data volume). + // nvdata is the large one; confirm by its mount not being /config. + if !name.is_empty() && mnt != "/config" { + return Ok((mnt.to_owned(), name)); + } + } + } + Err(StockError::Method( + "could not find the mounted nvdata UBI volume".into(), + )) +} + +/// Write the ALAN flag into misc block 1 (flag=alkane). `misc_dev` is the misc +/// MTD device on the running OS (stock: /dev/mtd2; alkane: whatever /proc/mtd +/// shows for "misc"). +fn set_flag_alkane(sh: &mut dyn Shell, misc_dev: &str) -> Result<(), StockError> { + // one page: magic + 0xFF pad + let mut page = FLAG_MAGIC.to_vec(); + page.resize(2048, 0xFF); + sh.put(&page, "/tmp/.alkflag")?; + let out = sh.exec(&format!( + "flash_erase {misc_dev} 0x{FLAG_BLOCK_IN_MISC:x} 1 >/dev/null 2>&1; \ + nandwrite -s 0x{FLAG_BLOCK_IN_MISC:x} -p {misc_dev} /tmp/.alkflag >/dev/null 2>&1; sync; \ + echo RB=$(dd if={misc_dev} bs=2048 skip={blk} count=1 2>/dev/null | md5sum | cut -d' ' -f1); \ + rm -f /tmp/.alkflag", + blk = FLAG_BLOCK_IN_MISC / 2048 + ))?; + let want = md5_hex(&page); + let got = out + .split("RB=") + .nth(1) + .map(|s| s.trim().to_owned()) + .unwrap_or_default(); + if got != want { + return Err(StockError::Method("flag write read-back mismatch".into())); + } + Ok(()) +} + +/// Erase the flag block (flag=stock). +fn clear_flag(sh: &mut dyn Shell, misc_dev: &str) -> Result<(), StockError> { + sh.exec(&format!( + "flash_erase {misc_dev} 0x{FLAG_BLOCK_IN_MISC:x} 1 >/dev/null 2>&1; sync; echo CLEARED" + ))?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// The flag-based boot-chain env vars. +// --------------------------------------------------------------------------- + +/// checkalk raw-reads the flag page and tests the four magic bytes with nested +/// `itest.b` (this vendor U-Boot mis-compares `itest.l *`); only on a match +/// does it run alkboot. No ubi/ubifs here - that keeps the stock path raw. +fn checkalk_value() -> String { + format!( + "nand read 0x08000000 0x{FLAG_ABS_OFFSET:x} 0x800; \ + if itest.b *0x08000000 == 0x{a:02x}; then \ + if itest.b *0x08000001 == 0x{l:02x}; then \ + if itest.b *0x08000002 == 0x{a2:02x}; then \ + if itest.b *0x08000003 == 0x{n:02x}; then run alkboot; fi; fi; fi; fi", + a = FLAG_MAGIC[0], + l = FLAG_MAGIC[1], + a2 = FLAG_MAGIC[2], + n = FLAG_MAGIC[3], + ) +} + +/// alkboot mounts the nvdata UBIFS and boots alkane from `alkane/`. +fn alkboot_value(volume: &str) -> String { + format!( + "setenv bootargs ${{alkbootargs}}; ubi part nvdata; ubifsmount ubi0:{volume}; \ + ubifsload ${{krnaddr}} {ALKANE_DIR}/vmlinux.bin; \ + ubifsload ${{fdtaddr}} {ALKANE_DIR}/devicetree.dtb; \ + ubifsload ${{rdaddr}} {ALKANE_DIR}/uramdisk.image.gz; \ + booti ${{krnaddr}} ${{rdaddr}} ${{fdtaddr}}" + ) +} + +/// Install the flag-based boot env (preserving all existing stock vars). Leaves +/// bootcmd = "run checkalk; run storeboot". +fn install_boot_env(sh: &mut dyn Shell, volume: &str) -> Result<(), StockError> { + let blob = read_env(sh)?; + let mut vars = parse_env(&blob); + set_var(&mut vars, "krnaddr", KRNADDR); + set_var(&mut vars, "fdtaddr", FDTADDR); + set_var(&mut vars, "rdaddr", RDADDR); + set_var(&mut vars, "alkbootargs", ALK_BOOTARGS); + set_var(&mut vars, "alkboot", &alkboot_value(volume)); + set_var(&mut vars, "checkalk", &checkalk_value()); + set_var(&mut vars, "bootcmd", "run checkalk; run storeboot"); + let new_blob = build_env(&vars)?; + write_env(sh, &new_blob) +} + +fn reboot_stock(sh: &mut dyn Shell) { + let _ = sh.exec("sync; reboot"); +} + +fn reboot_alkane(sh: &mut dyn Shell) { + // plain `reboot` no-ops on the minimal init; `reboot -f` triggers PSCI reset. + let _ = sh.exec("sync; reboot -f"); +} + +// --------------------------------------------------------------------------- +// Public API (dispatched from stock.rs for board == a113d). +// --------------------------------------------------------------------------- + +/// Install alkane onto an A113D running genuine stock, network-only, over the +/// DSH root-on-stock primitive. Stages the OS files into the nvdata UBI volume, +/// installs the flag-based boot env, and sets flag=alkane; the next boot runs +/// alkane. Zero raw writes outside the flag block in `misc`. +pub fn install_from_stock( + host: &str, + kernel_image: &[u8], + dtb: &[u8], + uramdisk: &[u8], + password: Option<&str>, +) -> Result<(), StockError> { + let mut sh = StockShell { + host: host.to_owned(), + password: password.map(|s| s.to_owned()), + }; + + // Guard: this board must be A113D stock (has a 'misc' MTD and a mounted + // nvdata UBI). If not, defer to the compiled-in method. + let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default(); + if !proc_mtd.contains("\"nvdata\"") || !proc_mtd.contains("\"misc\"") { + return Err(StockError::NotApplicable); + } + + let misc = find_mtd(&mut sh, "misc")?; + let (mount, volume) = discover_nvdata_volume(&mut sh)?; + + // Stage the three files into /alkane/ and read-back verify. + let dir = format!("{mount}/{ALKANE_DIR}"); + sh.exec(&format!("mkdir -p {dir}"))?; + // rootfs -> dtb -> kernel (kernel lands last). + stage_file(&mut sh, uramdisk, &format!("{dir}/uramdisk.image.gz"))?; + stage_file(&mut sh, dtb, &format!("{dir}/devicetree.dtb"))?; + stage_file(&mut sh, kernel_image, &format!("{dir}/vmlinux.bin"))?; + sh.exec("sync")?; + + // Install the flag-based boot env (read-back verified before reboot). + install_boot_env(&mut sh, &volume)?; + + // Set flag=alkane, then reboot into alkane. + set_flag_alkane(&mut sh, &misc)?; + reboot_stock(&mut sh); + Ok(()) +} + +/// Stage one file to a UBIFS path and prove its read-back md5 before continuing. +fn stage_file(sh: &mut dyn Shell, data: &[u8], dest: &str) -> Result<(), StockError> { + let tmp = "/tmp/.alkstage"; + sh.put(data, tmp)?; + let out = sh.exec_long(&format!( + "cp -f {tmp} {dest} && sync; echo RB=$(md5sum {dest} | cut -d' ' -f1); rm -f {tmp}" + ))?; + let want = md5_hex(data); + let got = out + .split("RB=") + .nth(1) + .map(|s| s.trim().to_owned()) + .unwrap_or_default(); + if got != want { + return Err(StockError::Method(format!( + "staged {dest} md5 mismatch: want {want}, got {got}" + ))); + } + Ok(()) +} + +/// Restore an A113D running alkane back to genuine stock, network-only, in-band +/// from the running alkane OS: erase the flag block (flag=stock) and reboot. +/// Stock boots via `storeboot` from the untouched `boot` MTD; the alkane payload +/// and env are left in place, so a re-install is just re-writing the flag. +pub fn restore_to_stock(host: &str, password: Option<&str>) -> Result<(), StockError> { + let mut sh = AlkaneShell::connect(host, password)?; + + // Guard: must be the alkane a113d image (exposes 'misc' and 'nvdata' MTDs, + // mainline 6.18.48). If 'misc' is absent this is not applicable. + let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default(); + if !proc_mtd.contains("\"misc\"") { + return Err(StockError::NotApplicable); + } + let misc = find_mtd(&mut sh, "misc")?; + clear_flag(&mut sh, &misc)?; + reboot_alkane(&mut sh); + Ok(()) +} + +/// The on-board stock backup is structural on this board: `storeboot` always +/// boots genuine stock from the `boot` MTD (mtd4), which this install never +/// writes. So a complete backup is present whenever the board is an A113D. +pub fn onboard_backup_present(host: &str, password: Option<&str>) -> Result { + // Best-effort confirm over alkane that the flag chain is in place; if we + // cannot reach alkane, report not-applicable so the caller falls through. + let mut sh = AlkaneShell::connect(host, password)?; + let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default(); + if proc_mtd.contains("\"misc\"") { + Ok(true) + } else { + Err(StockError::NotApplicable) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn env_roundtrips_with_crc() { + let vars = vec![ + ( + "bootcmd".to_owned(), + "run checkalk; run storeboot".to_owned(), + ), + ("bootdelay".to_owned(), "1".to_owned()), + ("checkalk".to_owned(), checkalk_value()), + ]; + let blob = build_env(&vars).unwrap(); + assert_eq!(blob.len(), ENV_SIZE); + let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]); + assert_eq!(crc32(&blob[4..]), stored); + let parsed = parse_env(&blob); + assert_eq!( + parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1, + "run checkalk; run storeboot" + ); + assert!(parsed.iter().any(|(k, _)| k == "checkalk")); + } + + #[test] + fn b64_roundtrip() { + for n in [0usize, 1, 2, 3, 64, 2048, 65536] { + let data: Vec = (0..n).map(|i| (i * 7 + 3) as u8).collect(); + let enc = b64_encode(&data); + let dec = b64_decode(&enc).unwrap(); + assert_eq!(dec, data, "n={n}"); + } + // wrapped base64 decodes the same + let data: Vec = (0..100).map(|i| i as u8).collect(); + let mut wrapped = b64_encode(&data); + wrapped.insert(20, '\n'); + wrapped.insert(50, '\n'); + assert_eq!(b64_decode(&wrapped).unwrap(), data); + } + + #[test] + fn checkalk_is_raw_and_byte_tested() { + let c = checkalk_value(); + assert!(c.starts_with("nand read 0x08000000")); + assert!(c.contains("itest.b *0x08000000 == 0x41")); + assert!(!c.contains("ubi")); // the stock path must never touch UBI + assert!(c.contains("run alkboot")); + } + + #[test] + fn alkboot_loads_from_alkane_dir() { + let a = alkboot_value("nvdata_log"); + assert!(a.contains("ubifsmount ubi0:nvdata_log")); + assert!(a.contains("alkane/vmlinux.bin")); + assert!(a.contains("booti ${krnaddr} ${rdaddr} ${fdtaddr}")); + } +} diff --git a/crates/alkane-flash/src/lib.rs b/crates/alkane-flash/src/lib.rs index 399618b5..a5bb293a 100644 --- a/crates/alkane-flash/src/lib.rs +++ b/crates/alkane-flash/src/lib.rs @@ -11,12 +11,15 @@ // choices for this crate rather than defects. #![allow(clippy::type_complexity, clippy::too_many_arguments)] +pub mod aml_ubi; pub mod boards; pub mod install; pub mod md5; pub mod preflight; pub mod stock; pub mod stock_firmware; +pub mod uimage; +pub mod zynq_nand; // Network-only stock-crossing method bodies compiled into the toolkit; the // public interface lives in `stock`. See stock_method.rs. This module is // maintained as a self-contained unit; the style lints below are allowed here so @@ -27,7 +30,8 @@ pub mod stock_firmware; clippy::too_many_arguments, clippy::manual_repeat_n, clippy::manual_is_multiple_of, - clippy::unnecessary_map_or + clippy::unnecessary_map_or, + clippy::question_mark )] mod stock_method; pub mod transport; diff --git a/crates/alkane-flash/src/stock.rs b/crates/alkane-flash/src/stock.rs index a0074e59..dcaa528d 100644 --- a/crates/alkane-flash/src/stock.rs +++ b/crates/alkane-flash/src/stock.rs @@ -12,6 +12,11 @@ //! (`StockMethod`, `StockError`) plus the toolkit-side orchestration and //! verification around the method. The method is plain Rust and must be //! network-only. +//! +//! A from-stock install also leaves a complete genuine-stock backup on the +//! board: the stock device tree, kernel and ramdisk, in the reserved NAND +//! region after the alkane MAC area. The two on-board backup calls below check +//! and restore that copy over the network, with no vendor firmware file. use alkane_artifacts::afw::VerifiedAfw; use std::path::{Path, PathBuf}; @@ -29,6 +34,8 @@ pub enum StockError { Method(String), #[error("io: {0}")] Io(String), + #[error("not applicable to this board; use the compiled-in method")] + NotApplicable, } /// The genuine Bitmain stock kernel and rootfs to write back when restoring to @@ -41,6 +48,10 @@ pub enum StockError { pub struct RestoreImages<'a> { pub kernel: &'a [u8], pub rootfs: &'a [u8], + /// The genuine per-board device tree from the vendor package, when present + /// (SD recovery images ship one; OTA packages omit it). When `None`, the + /// zynq readable path takes the stock dtb from the on-board backup. + pub dtb: Option<&'a [u8]>, } /// Options for updating a board that already runs alkane, in place. @@ -144,6 +155,31 @@ pub trait StockMethod { password: Option<&str>, ) -> Result<(), StockError>; + /// Run `cmd` as root on a board running stock, over the network only, and + /// return its combined standard output and standard error. `cmd` is a + /// `/bin/sh` command line. A non-zero exit is an `Err` whose message is that + /// combined output. `password` is the board's stock login password; `None` + /// falls back to the configured board credential. + fn root_exec( + &self, + host: &str, + password: Option<&str>, + cmd: &str, + ) -> Result; + + /// Write `data` to `remote_path` as root on a board running stock, over the + /// network only. Missing parent directories are created and the file is + /// left mode 0644. The payload may be many megabytes; it is sent as a + /// stream, not on a command line. `password` is the board's stock login + /// password; `None` falls back to the configured board credential. + fn root_put( + &self, + host: &str, + password: Option<&str>, + data: &[u8], + remote_path: &str, + ) -> Result<(), StockError>; + /// Update a board that already runs alkane to the `.afw`'s images, over the /// network only. Refuses a board that is not running alkane (a board on /// stock is installed with `install_from_stock`). The boot regions are not @@ -157,6 +193,26 @@ pub trait StockMethod { password: Option<&str>, options: &InPlaceOptions, ) -> Result; + + /// Report, over the network only, whether the board holds a complete + /// on-board stock backup that can be restored without a vendor firmware + /// file. False means absent or incomplete; it is not an error. + fn onboard_stock_backup_present( + &self, + host: &str, + password: Option<&str>, + ) -> Result; + + /// Return an alkane board to genuine stock, over the network only, using + /// the on-board stock backup. The backup must be present and complete; call + /// `onboard_stock_backup_present` first. `timeout` bounds the wait for the + /// restored board to answer as stock after the reboot. + fn restore_from_onboard_backup( + &self, + host: &str, + password: Option<&str>, + timeout: std::time::Duration, + ) -> Result<(), StockError>; } /// The compiled-in method implementation. @@ -164,6 +220,35 @@ pub fn method() -> &'static dyn StockMethod { crate::stock_method::method() } +/// Report, over the network only, whether the board holds a complete on-board +/// stock backup that can be restored without a vendor firmware file. Zynq uses +/// the readable boot-slot path; other boards use the compiled-in method. +pub fn onboard_stock_backup_present( + host: &str, + password: Option<&str>, +) -> Result { + match crate::zynq_nand::onboard_backup_present(host, password) { + Err(StockError::NotApplicable) => method().onboard_stock_backup_present(host, password), + other => other, + } +} + +/// Return an alkane board to genuine stock (network-only) using its on-board +/// stock backup, via the compiled-in method. The backup must be present and +/// complete; check it first with [`onboard_stock_backup_present`]. +pub fn restore_from_onboard_backup( + host: &str, + password: Option<&str>, + timeout: std::time::Duration, +) -> Result<(), StockError> { + match crate::zynq_nand::restore_from_onboard(host, password) { + Err(StockError::NotApplicable) => { + method().restore_from_onboard_backup(host, password, timeout) + } + other => other, + } +} + /// Install alkane onto a board on stock (network-only), via the compiled-in method. pub fn install_from_stock( host: &str, @@ -171,6 +256,38 @@ pub fn install_from_stock( afw: &VerifiedAfw, password: Option<&str>, ) -> Result<(), StockError> { + // Zynq-7010 uses the readable NAND path (uImage-wrap + flash_erase/nandwrite + // over the DSH root primitive, with an on-board stock backup carved first); + // other boards use the compiled-in method. + if afw.manifest.board == crate::boards::zynq::BOARD { + let img = |role: &str| { + afw.image(role) + .map(|(_, data)| data) + .ok_or_else(|| StockError::Method(format!("afw missing {role} image"))) + }; + return crate::zynq_nand::install_from_stock( + host, + img("kernel")?, + img("dtb")?, + img("rootfs")?, + password, + ); + } + // A113D (Amlogic AXG) uses the readable UBI-stage + flag-based boot chain. + if afw.manifest.board == crate::aml_ubi::BOARD { + let img = |role: &str| { + afw.image(role) + .map(|(_, data)| data) + .ok_or_else(|| StockError::Method(format!("afw missing {role} image"))) + }; + return crate::aml_ubi::install_from_stock( + host, + img("kernel")?, + img("dtb")?, + img("rootfs")?, + password, + ); + } method().install_from_stock(host, afw_path, afw, password) } @@ -181,7 +298,50 @@ pub fn restore_to_stock( images: &RestoreImages, password: Option<&str>, ) -> Result<(), StockError> { - method().restore_to_stock(host, images, password) + match crate::zynq_nand::restore_to_stock( + host, + images.kernel, + images.rootfs, + images.dtb, + password, + ) { + Err(StockError::NotApplicable) => { + // A113D restore is a one-byte flag flip in-band from alkane; it needs + // no stock images. Try it, then fall through to the compiled-in method. + match crate::aml_ubi::restore_to_stock(host, password) { + Err(StockError::NotApplicable) => method().restore_to_stock(host, images, password), + other => other, + } + } + other => other, + } +} + +/// Restore an alkane A113D to stock with no stock firmware file: a one-byte flag +/// flip in-band from the running alkane OS (network-only). Returns +/// `NotApplicable` if the board is not an alkane A113D. +pub fn restore_aml_flag(host: &str, password: Option<&str>) -> Result<(), StockError> { + crate::aml_ubi::restore_to_stock(host, password) +} + +/// Run `cmd` as root on a board running stock (network-only), via the +/// compiled-in method. `cmd` is a `/bin/sh` command line; the returned string +/// is its combined output. A non-zero exit is an error whose message is that +/// output. +pub fn root_exec(host: &str, password: Option<&str>, cmd: &str) -> Result { + method().root_exec(host, password, cmd) +} + +/// Write `data` to `remote_path` as root on a board running stock +/// (network-only), via the compiled-in method. Missing parent directories are +/// created and the file is left mode 0644. Large payloads are streamed. +pub fn root_put( + host: &str, + password: Option<&str>, + data: &[u8], + remote_path: &str, +) -> Result<(), StockError> { + method().root_put(host, password, data, remote_path) } /// Check, over the network, that a Zynq board is up on alkane: the web page @@ -215,8 +375,103 @@ mod tests { // The interface is exercised against whatever `stock_method` provides. We // only assert the toolkit wires a method object in; its behaviour is the // method module's own tests. + #[test] + fn public_signatures_are_wired() { + let _: fn(&str, Option<&str>) -> Result = onboard_stock_backup_present; + let _: fn(&str, Option<&str>, std::time::Duration) -> Result<(), StockError> = + restore_from_onboard_backup; + let _: fn(&str, Option<&str>, &str) -> Result = root_exec; + let _: fn(&str, Option<&str>, &[u8], &str) -> Result<(), StockError> = root_put; + } + + struct FakeMethod { + present: bool, + } + + impl StockMethod for FakeMethod { + fn install_from_stock( + &self, + _: &str, + _: &Path, + _: &VerifiedAfw, + _: Option<&str>, + ) -> Result<(), StockError> { + Err(StockError::NotImplemented) + } + + fn restore_to_stock( + &self, + _: &str, + _: &RestoreImages, + _: Option<&str>, + ) -> Result<(), StockError> { + Err(StockError::NotImplemented) + } + + fn root_exec(&self, _: &str, _: Option<&str>, _: &str) -> Result { + Err(StockError::NotImplemented) + } + + fn root_put(&self, _: &str, _: Option<&str>, _: &[u8], _: &str) -> Result<(), StockError> { + Err(StockError::NotImplemented) + } + + fn update_in_place( + &self, + _: &str, + _: &VerifiedAfw, + _: Option<&str>, + _: &InPlaceOptions, + ) -> Result { + Err(StockError::NotImplemented) + } + + fn onboard_stock_backup_present( + &self, + _: &str, + _: Option<&str>, + ) -> Result { + Ok(self.present) + } + + fn restore_from_onboard_backup( + &self, + _: &str, + _: Option<&str>, + _: std::time::Duration, + ) -> Result<(), StockError> { + if self.present { + Ok(()) + } else { + Err(StockError::Method( + "no complete on-board stock backup".into(), + )) + } + } + } + #[test] fn a_method_is_compiled_in() { let _m: &dyn StockMethod = method(); } + + #[test] + fn onboard_backup_methods_report_present_or_absent() { + let present = FakeMethod { present: true }; + assert!(present + .onboard_stock_backup_present("192.0.2.10", Some("secret")) + .unwrap()); + assert!(present + .restore_from_onboard_backup("192.0.2.10", Some("secret"), std::time::Duration::ZERO) + .is_ok()); + + let absent = FakeMethod { present: false }; + assert!(!absent + .onboard_stock_backup_present("192.0.2.10", None) + .unwrap()); + assert!(matches!( + absent.restore_from_onboard_backup("192.0.2.10", None, std::time::Duration::ZERO), + Err(StockError::Method(_)) + )); + } } diff --git a/crates/alkane-flash/src/stock_method.rs b/crates/alkane-flash/src/stock_method.rs index 09eb68bc..ac14a2d1 100644 --- a/crates/alkane-flash/src/stock_method.rs +++ b/crates/alkane-flash/src/stock_method.rs @@ -40,6 +40,14 @@ const DTB_SLOT: u64 = 0x20000; const KERNEL_SLOT: u64 = 0x800000; const ROOTFS_SLOT: u64 = 0x2000000; +// A complete genuine-stock backup kept on the board by a from-stock install. +// The area sits in the vendor `reserve` partition after the alkane MAC region, +// clear of the stock `configs` UBI, the alkane boot slots and BOOT.bin. +const STOCK_BACKUP_BASE: u64 = 0x5200000; +const STOCK_BACKUP_END: u64 = 0x6000000; +const STOCK_BACKUP_HEADER: u64 = 0x20000; +const STOCK_BACKUP_MAGIC: &str = "ALKANE-STOCK-BACKUP 1"; + // ---------------------------------------------------------------- stock assets // // The stock payloads are not compiled into the toolkit. They are fetched over @@ -606,6 +614,25 @@ fn run_command( } else { Stdio::null() }); + run_command_io(command, timeout, input) +} + +/// Run a command with a file as its standard input. The file is handed to the +/// child directly, so a multi-megabyte payload is not copied through memory. +fn run_command_stream( + mut command: Command, + timeout: Duration, + input: fs::File, +) -> Result { + command.stdin(Stdio::from(input)); + run_command_io(command, timeout, None) +} + +fn run_command_io( + mut command: Command, + timeout: Duration, + input: Option>, +) -> Result { command.stdout(Stdio::piped()); command.stderr(Stdio::piped()); @@ -688,6 +715,10 @@ fn text(data: &[u8]) -> String { // ---------------------------------------------------------------- SSH fn ssh_command(host: &str, password: Option<&str>, remote: &str) -> Command { + ssh_command_as(host, "root", password, remote) +} + +fn ssh_command_as(host: &str, user: &str, password: Option<&str>, remote: &str) -> Command { let mut command; if let Some(password) = password { command = Command::new("sshpass"); @@ -714,11 +745,39 @@ fn ssh_command(host: &str, password: Option<&str>, remote: &str) -> Command { if password.is_none() { command.args(["-o", "BatchMode=yes"]); } - command.arg(format!("root@{host}")); + command.arg(format!("{user}@{host}")); command.arg(remote); command } +fn ssh_exec_as( + host: &str, + user: &str, + password: Option<&str>, + remote: &str, + timeout: Duration, +) -> Result { + let result = run_command(ssh_command_as(host, user, password, remote), timeout, None)?; + if result.timed_out { + return Err(StockError::Network("target did not respond".into())); + } + Ok(result) +} + +/// True when the SSH failure is the login being refused rather than the target +/// being unreachable or a command failing after it ran. +fn is_login_refused(result: &CmdResult) -> bool { + if result.timed_out { + return false; + } + let lower = text(&result.stderr).to_lowercase(); + lower.contains("permission denied") + || lower.contains("authentication failed") + || lower.contains("no supported authentication") + || lower.contains("too many authentication failures") + || lower.contains("root login rejected") +} + fn classify_ssh(result: &CmdResult) -> StockError { let lower = text(&result.stderr).to_lowercase(); let auth = lower.contains("permission denied") @@ -779,6 +838,86 @@ fn ssh_push( Ok(()) } +// Quote one argument for a POSIX shell. A single-quoted string is literal, so +// the only character needing work is the quote itself. +fn shell_quote(value: &str) -> String { + let mut out = String::with_capacity(value.len() + 2); + out.push('\''); + for c in value.chars() { + if c == '\'' { + out.push_str("'\\''"); + } else { + out.push(c); + } + } + out.push('\''); + out +} + +// The combined output of a completed command: standard output followed by +// standard error, joined with a newline if both are non-empty. +fn command_output(result: &CmdResult) -> String { + let mut out = text(&result.stdout); + let error = text(&result.stderr); + if !error.is_empty() { + if !out.is_empty() && !out.ends_with('\n') { + out.push('\n'); + } + out.push_str(&error); + } + out +} + +fn command_exit_error(status: i32, output: String) -> StockError { + if output.is_empty() { + StockError::Method(format!("command exited with status {status}")) + } else { + StockError::Method(output) + } +} + +// A command that reached the board and exited non-zero. Authentication and +// transport failures are classified as such; everything else carries the +// command's output. +fn command_failure(result: &CmdResult) -> StockError { + if result.timed_out { + return StockError::Network("target did not respond".into()); + } + let lower = text(&result.stderr).to_lowercase(); + let transport = lower.contains("permission denied") + || lower.contains("authentication failed") + || lower.contains("no supported authentication") + || lower.contains("connection refused") + || lower.contains("connection reset") + || lower.contains("connection closed") + || lower.contains("broken pipe") + || lower.contains("no route to host") + || lower.contains("could not resolve"); + if result.status == Some(255) && transport { + return classify_ssh(result); + } + command_exit_error(result.status.unwrap_or(-1), command_output(result)) +} + +fn validate_remote_path(path: &str) -> Result<(), StockError> { + if path.is_empty() || path.contains('\0') || path.ends_with('/') { + return Err(StockError::Method("invalid remote path".into())); + } + Ok(()) +} + +fn remote_parent(path: &str) -> &str { + match path.rfind('/') { + Some(0) => "/", + Some(index) => &path[..index], + None => ".", + } +} + +fn ssh_root_ready(host: &str, password: Option<&str>) -> Result<(), StockError> { + ssh_probe(host, password) +} + fn reboot_target(host: &str, password: Option<&str>) { let _ = run_command( ssh_command( @@ -947,6 +1086,18 @@ fn stock_web_upload( body: &Path, boundary: &str, tag: &str, +) -> Result<(), StockError> { + stock_web_upload_with_timeout(host, password, dir, body, boundary, tag, 600) +} + +fn stock_web_upload_with_timeout( + host: &str, + password: &str, + dir: &Path, + body: &Path, + boundary: &str, + tag: &str, + max_time_secs: u64, ) -> Result<(), StockError> { let config = dir.join(format!("upload-{tag}.cfg")); let output = dir.join(format!("upload-{tag}.out")); @@ -958,7 +1109,7 @@ fn stock_web_upload( "digest".to_string(), "location".to_string(), "max-redirs = 5".to_string(), - "max-time = 600".to_string(), + format!("max-time = {max_time_secs}"), format!( "url = {}", curl_quote(&format!("http://{host}/cgi-bin/upgrade.cgi")) @@ -979,7 +1130,7 @@ fn stock_web_upload( "write-out = \"%{http_code}\"".to_string(), ], )?; - let result = run_curl(&config, Duration::from_secs(620))?; + let result = run_curl(&config, Duration::from_secs(max_time_secs + 20))?; match http_code(&result) { 200..=299 => Ok(()), 401 | 403 => Err(StockError::Auth("target rejected the credential".into())), @@ -994,6 +1145,17 @@ fn stock_web_trigger( dir: &Path, cgi: &str, tag: &str, +) -> Result { + stock_web_trigger_with_timeout(host, password, dir, cgi, tag, 900) +} + +fn stock_web_trigger_with_timeout( + host: &str, + password: &str, + dir: &Path, + cgi: &str, + tag: &str, + max_time_secs: u64, ) -> Result { let config = dir.join(format!("trigger-{tag}.cfg")); write_curl_config( @@ -1004,7 +1166,7 @@ fn stock_web_trigger( "digest".to_string(), "location".to_string(), "max-redirs = 5".to_string(), - "max-time = 900".to_string(), + format!("max-time = {max_time_secs}"), format!( "url = {}", curl_quote(&format!("http://{host}/cgi-bin/{cgi}")) @@ -1012,7 +1174,7 @@ fn stock_web_trigger( format!("user = {}", curl_quote(&format!("root:{password}"))), ], )?; - run_curl(&config, Duration::from_secs(920)) + run_curl(&config, Duration::from_secs(max_time_secs + 20)) } // ---------------------------------------------------------------- AFW @@ -1479,12 +1641,7 @@ fn map_covers_boot_regions(map: &[Mtd]) -> bool { .all(|absolute| locate_mtd(map, *absolute).is_some()) } -fn get_mtd_map(host: &str, password: Option<&str>) -> Result, StockError> { - let map = read_mtd_map(host, password)?; - if map_covers_boot_regions(&map) { - return Ok(map); - } - +fn apply_mtd_patch(host: &str, password: Option<&str>) -> Result<(), StockError> { let mtd_patch = stock_asset(&ASSET_MTD_PATCH)?; ssh_push( host, @@ -1510,6 +1667,15 @@ fn get_mtd_map(host: &str, password: Option<&str>) -> Result, StockErro "target storage layout unsupported".into(), )); } + Ok(()) +} + +fn get_mtd_map(host: &str, password: Option<&str>) -> Result, StockError> { + let map = read_mtd_map(host, password)?; + if map_covers_boot_regions(&map) { + return Ok(map); + } + apply_mtd_patch(host, password)?; let map = read_mtd_map(host, password)?; if !map_covers_boot_regions(&map) { return Err(StockError::Method( @@ -1519,6 +1685,28 @@ fn get_mtd_map(host: &str, password: Option<&str>) -> Result, StockErro Ok(map) } +/// Like `get_mtd_map`, but also requires `absolute` to be reachable. The +/// per-board storage helper re-registers the boot regions; on alkane that same +/// view includes the reserve area used for the on-board stock backup. +fn get_mtd_map_for_backup( + host: &str, + password: Option<&str>, + absolute: u64, +) -> Result, StockError> { + let map = read_mtd_map(host, password)?; + if map_covers_boot_regions(&map) && locate_mtd(&map, absolute).is_some() { + return Ok(map); + } + apply_mtd_patch(host, password)?; + let map = read_mtd_map(host, password)?; + if !map_covers_boot_regions(&map) || locate_mtd(&map, absolute).is_none() { + return Err(StockError::Method( + "target storage layout unsupported".into(), + )); + } + Ok(map) +} + fn locate_mtd(map: &[Mtd], absolute: u64) -> Option<(&Mtd, u64)> { for mtd in map { if mtd.offset <= absolute && absolute < mtd.offset + mtd.size { @@ -1640,7 +1828,134 @@ fn stock_web_targets( // ---------------------------------------------------------------- scripts -fn flash_script(targets: &[FlashTarget], token: &str, web_cgi: Option<&str>) -> String { +// Runs as root inside the from-stock web helper, before any alkane image is +// written. It leaves the genuine stock boot chain in the reserve area and +// writes the manifest last. Any failure exits through `fail`, so the stock +// board is never touched unless the backup is complete. +const STOCK_BACKUP_WEB_SCRIPT: &str = r#" +ak_base=0x5200000 +ak_end=0x6000000 +ak_hdr=131072 +ak_blk=131072 +ak_src_dtb=0x1a00000 +ak_src_kernel=0x2000000 +ak_src_ramdisk=0x2800000 +ak_num() { + printf '%d\n' "$(( $1 ))" +} +ak_mtd_for() { + ak_abs=$(ak_num "$1") || return 1 + for ak_d in /sys/class/mtd/mtd[0-9]*; do + [ -e "$ak_d/offset" ] || continue + ak_off=$(cat "$ak_d/offset" 2>/dev/null) || continue + ak_siz=$(cat "$ak_d/size" 2>/dev/null) || continue + [ -n "$ak_off" ] && [ -n "$ak_siz" ] || continue + ak_off=$(ak_num "$ak_off") || continue + ak_siz=$(ak_num "$ak_siz") || continue + if [ "$ak_abs" -ge "$ak_off" ] && [ "$ak_abs" -lt "$((ak_off + ak_siz))" ]; then + ak_name=$(basename "$ak_d") + printf '%s %s %s\n' "/dev/$ak_name" "$((ak_abs - ak_off))" "$ak_off" + return 0 + fi + done + return 1 +} +ak_be32() { + set -- $(od -An -tx1 -j "$2" -N4 "$1" 2>/dev/null) + [ "$#" -eq 4 ] || return 1 + printf '%d\n' "$(( (0x$1 << 24) | (0x$2 << 16) | (0x$3 << 8) | 0x$4 ))" +} +ak_uimage_len() { + ak_magic=$(dd if="$1" bs=1 count=4 2>/dev/null | od -An -tx1 | tr -d ' \n') + [ "$ak_magic" = "27051956" ] || return 1 + ak_total=$((64 + $(ak_be32 "$1" 12))) || return 1 + [ "$ak_total" -gt 64 ] || return 1 + ak_bytes=$(( ((ak_total + ak_blk - 1) / ak_blk) * ak_blk )) + [ "$((ak_bytes <= $2))" -eq 1 ] || return 1 + printf '%d\n' "$ak_bytes" +} + +set -- $(ak_mtd_for "$ak_base") +[ "$#" -eq 3 ] || fail bk-map +ak_dev=$1 +ak_bakrel=$2 +ak_devoff=$3 + +set -- $(ak_mtd_for "$ak_src_dtb") +[ "$#" -eq 3 ] || fail bk-src-dtb +ak_srcrel=$2 +[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-dtb +dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-dtb 2>/dev/null || fail bk-read-dtb +[ "$(wc -c < /tmp/.ak-bk-dtb 2>/dev/null)" = "$ak_hdr" ] || fail bk-short-dtb +ak_dtb_md5=$(md5sum /tmp/.ak-bk-dtb | cut -d' ' -f1) || fail bk-md5-dtb +ak_dtb_size=$ak_hdr + +set -- $(ak_mtd_for "$ak_src_kernel") +[ "$#" -eq 3 ] || fail bk-src-kernel +ak_srcrel=$2 +[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-kernel +dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-kernel-head 2>/dev/null || fail bk-read-kernel +ak_kernel_size=$(ak_uimage_len /tmp/.ak-bk-kernel-head 0x800000) || fail bk-kernel +dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count="$((ak_kernel_size / ak_blk))" of=/tmp/.ak-bk-kernel 2>/dev/null || fail bk-read-kernel +[ "$(wc -c < /tmp/.ak-bk-kernel 2>/dev/null)" = "$ak_kernel_size" ] || fail bk-short-kernel +ak_kernel_md5=$(md5sum /tmp/.ak-bk-kernel | cut -d' ' -f1) || fail bk-md5-kernel + +set -- $(ak_mtd_for "$ak_src_ramdisk") +[ "$#" -eq 3 ] || fail bk-src-ramdisk +ak_srcrel=$2 +[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-ramdisk +dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-ramdisk-head 2>/dev/null || fail bk-read-ramdisk +ak_ramdisk_size=$(ak_uimage_len /tmp/.ak-bk-ramdisk-head 0x2000000) || fail bk-ramdisk +dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count="$((ak_ramdisk_size / ak_blk))" of=/tmp/.ak-bk-ramdisk 2>/dev/null || fail bk-read-ramdisk +[ "$(wc -c < /tmp/.ak-bk-ramdisk 2>/dev/null)" = "$ak_ramdisk_size" ] || fail bk-short-ramdisk +ak_ramdisk_md5=$(md5sum /tmp/.ak-bk-ramdisk | cut -d' ' -f1) || fail bk-md5-ramdisk + +ak_dtb_bak=$((ak_base + ak_hdr)) +ak_kernel_bak=$((ak_dtb_bak + ak_dtb_size)) +ak_ramdisk_bak=$((ak_kernel_bak + ak_kernel_size)) +ak_end_used=$((ak_ramdisk_bak + ak_ramdisk_size)) +[ "$((ak_end_used <= ak_end))" -eq 1 ] || fail bk-space + +set -- $(ak_mtd_for "$ak_dtb_bak") +[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split +set -- $(ak_mtd_for "$ak_kernel_bak") +[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split +set -- $(ak_mtd_for "$ak_ramdisk_bak") +[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split + +ak_blocks=$(( (ak_end_used - ak_base) / ak_blk )) +flash_erase "$ak_dev" "$ak_bakrel" "$ak_blocks" >/dev/null 2>&1 || fail bk-erase +nandwrite -p -s "$((ak_dtb_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-dtb >/dev/null 2>&1 || fail bk-write-dtb +nandwrite -p -s "$((ak_kernel_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-kernel >/dev/null 2>&1 || fail bk-write-kernel +nandwrite -p -s "$((ak_ramdisk_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-ramdisk >/dev/null 2>&1 || fail bk-write-ramdisk + +ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_dtb_bak - ak_devoff) / ak_blk ))" count="$((ak_dtb_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1) +[ "$ak_v" = "$ak_dtb_md5" ] || fail bk-verify-dtb +ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_kernel_bak - ak_devoff) / ak_blk ))" count="$((ak_kernel_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1) +[ "$ak_v" = "$ak_kernel_md5" ] || fail bk-verify-kernel +ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_ramdisk_bak - ak_devoff) / ak_blk ))" count="$((ak_ramdisk_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1) +[ "$ak_v" = "$ak_ramdisk_md5" ] || fail bk-verify-ramdisk + +{ + printf '%s\n' "ALKANE-STOCK-BACKUP 1" + printf 'dtb 0x1a00000 0x%x 0x%x %s\n' "$ak_dtb_bak" "$ak_dtb_size" "$ak_dtb_md5" + printf 'kernel 0x2000000 0x%x 0x%x %s\n' "$ak_kernel_bak" "$ak_kernel_size" "$ak_kernel_md5" + printf 'ramdisk 0x2800000 0x%x 0x%x %s\n' "$ak_ramdisk_bak" "$ak_ramdisk_size" "$ak_ramdisk_md5" + printf '%s\n' "end" +} > /tmp/.ak-bk-header || fail bk-header +nandwrite -p -s "$ak_bakrel" "$ak_dev" /tmp/.ak-bk-header >/dev/null 2>&1 || fail bk-write-header +ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$((ak_bakrel / ak_blk))" count=1 2>/dev/null | head -c 19) +[ "$ak_v" = "ALKANE-STOCK-BACKUP" ] || fail bk-verify-header +rm -f /tmp/.ak-bk-dtb /tmp/.ak-bk-kernel /tmp/.ak-bk-kernel-head \ + /tmp/.ak-bk-ramdisk /tmp/.ak-bk-ramdisk-head /tmp/.ak-bk-header +"#; + +fn flash_script( + targets: &[FlashTarget], + token: &str, + web_cgi: Option<&str>, + with_stock_backup: bool, +) -> String { let mut script = String::new(); script.push_str("#!/bin/sh\n"); script.push_str("set -u\n"); @@ -1649,6 +1964,10 @@ fn flash_script(targets: &[FlashTarget], token: &str, web_cgi: Option<&str>) -> } script.push_str("fail(){ echo \"@@FAIL@@ $*\"; sync; exit 1; }\n"); + if with_stock_backup { + script.push_str(STOCK_BACKUP_WEB_SCRIPT); + } + for target in targets { let path = if web_cgi.is_some() { format!("/tmp/.ak-{token}-{}", target.file) @@ -1703,27 +2022,32 @@ fn flash_script(targets: &[FlashTarget], token: &str, web_cgi: Option<&str>) -> script } +fn web_base_entries() -> Vec { + vec![ + TarEntry { + name: "d".to_string(), + mode: 0o777, + kind: b'2', + link: "/tmp".to_string(), + data: Vec::new(), + }, + TarEntry { + name: "p".to_string(), + mode: 0o777, + kind: b'2', + link: "/www/pages/cgi-bin".to_string(), + data: Vec::new(), + }, + ] +} + fn build_web_body( targets: &[FlashTarget], token: &str, cgi: &str, script: &str, ) -> (Vec, String) { - let mut entries = Vec::new(); - entries.push(TarEntry { - name: "d".to_string(), - mode: 0o777, - kind: b'2', - link: "/tmp".to_string(), - data: Vec::new(), - }); - entries.push(TarEntry { - name: "p".to_string(), - mode: 0o777, - kind: b'2', - link: "/www/pages/cgi-bin".to_string(), - data: Vec::new(), - }); + let mut entries = web_base_entries(); for target in targets { entries.push(TarEntry { name: format!("d/.ak-{token}-{}", target.file), @@ -1740,7 +2064,10 @@ fn build_web_body( link: String::new(), data: script.as_bytes().to_vec(), }); + build_web_body_entries(entries) +} +fn build_web_body_entries(entries: Vec) -> (Vec, String) { let tar = build_tar(&entries); let gz = gzip_store(&tar); let boundary = format!("----alkane{}", random_token()); @@ -1757,8 +2084,479 @@ fn build_web_body( (body, boundary) } +// ---------------------------------------------------------------- on-board stock backup +// +// A from-stock install copies the genuine stock device tree, kernel and ramdisk +// off their slots into the vendor `reserve` area before anything is overwritten. +// The copy is block-padded, carries a small text manifest with a digest for each +// member, and is written manifest-last so an interrupted install never leaves a +// backup that passes the presence check. Ownership/format stay inside this +// module; the public interface only reports complete/absent and restores. + +#[derive(Clone, Debug)] +struct StockBackupEntry { + name: &'static str, + target_abs: u64, + backup_abs: u64, + size: u64, + md5: String, +} + +#[derive(Clone, Debug)] +struct StockBackup { + entries: Vec, +} + +fn parse_hex_u64(value: &str) -> Option { + let digits = value + .strip_prefix("0x") + .or_else(|| value.strip_prefix("0X"))?; + u64::from_str_radix(digits, 16).ok() +} + +fn stock_entry_spec(name: &str) -> Option<(&'static str, u64, u64)> { + match name { + "dtb" => Some(("dtb", ABS_DTB, DTB_SLOT)), + "kernel" => Some(("kernel", ABS_KERNEL, KERNEL_SLOT)), + "ramdisk" => Some(("ramdisk", ABS_ROOTFS, ROOTFS_SLOT)), + _ => None, + } +} + +fn parse_stock_backup(header: &[u8]) -> Option { + let text = String::from_utf8_lossy(header); + let mut lines = text.lines(); + let first = lines.next()?.trim_matches('\0').trim(); + if first != STOCK_BACKUP_MAGIC { + return None; + } + + let mut entries = Vec::new(); + let mut ended = false; + for raw in lines { + let line = raw.trim_matches('\0').trim(); + if line.is_empty() { + continue; + } + if line == "end" { + ended = true; + break; + } + let fields: Vec<&str> = line.split_whitespace().collect(); + if fields.len() != 5 { + return None; + } + let (name, target_abs, slot) = stock_entry_spec(fields[0])?; + let declared_target = parse_hex_u64(fields[1])?; + let backup_abs = parse_hex_u64(fields[2])?; + let size = parse_hex_u64(fields[3])?; + let md5 = fields[4].to_ascii_lowercase(); + if declared_target != target_abs + || md5.len() != 32 + || !md5.chars().all(|c| c.is_ascii_hexdigit()) + { + return None; + } + if size == 0 || size % BLK != 0 || size > slot || (name == "dtb" && size != DTB_SLOT) { + return None; + } + let backup_end = backup_abs.checked_add(size)?; + if backup_abs % BLK != 0 + || backup_abs < STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER + || backup_end > STOCK_BACKUP_END + { + return None; + } + if entries + .iter() + .any(|entry: &StockBackupEntry| entry.name == name) + { + return None; + } + entries.push(StockBackupEntry { + name, + target_abs, + backup_abs, + size, + md5, + }); + } + + if !ended || entries.len() != 3 { + return None; + } + let mut spans: Vec<(u64, u64)> = entries + .iter() + .map(|entry| (entry.backup_abs, entry.backup_abs + entry.size)) + .collect(); + spans.sort_unstable(); + for pair in spans.windows(2) { + if pair[0].1 > pair[1].0 { + return None; + } + } + Some(StockBackup { entries }) +} + +fn render_stock_backup(entries: &[StockBackupEntry]) -> Vec { + let mut text = String::new(); + text.push_str(STOCK_BACKUP_MAGIC); + text.push('\n'); + for entry in entries { + text.push_str(&format!( + "{} 0x{:x} 0x{:x} 0x{:x} {}\n", + entry.name, entry.target_abs, entry.backup_abs, entry.size, entry.md5 + )); + } + text.push_str("end\n"); + text.into_bytes() +} + +fn read_mtd_span( + host: &str, + password: Option<&str>, + map: &[Mtd], + absolute: u64, + size: u64, + label: &str, +) -> Result, StockError> { + if size == 0 || size % BLK != 0 { + return Err(StockError::Method( + "target storage layout unsupported".into(), + )); + } + let (mtd, rel) = locate_mtd(map, absolute) + .ok_or_else(|| StockError::Method("target storage layout unsupported".into()))?; + if rel.checked_add(size).map_or(true, |end| end > mtd.size) { + return Err(StockError::Method( + "target storage layout unsupported".into(), + )); + } + let remote = format!( + "dd if={} bs={} skip={} count={} 2>/dev/null", + mtd.device, + BLK, + rel / BLK, + size / BLK + ); + let result = ssh_exec(host, password, &remote, Duration::from_secs(600))?; + if !result.ok() { + return Err(StockError::Method(format!( + "could not read the on-board stock {label} backup" + ))); + } + if result.stdout.len() as u64 != size { + return Err(StockError::Method(format!( + "the on-board stock {label} backup is short" + ))); + } + Ok(result.stdout) +} + +fn stock_uimage_span( + host: &str, + password: Option<&str>, + map: &[Mtd], + absolute: u64, + slot: u64, + label: &str, +) -> Result, StockError> { + let first = read_mtd_span(host, password, map, absolute, BLK, label)?; + if first.len() < 64 || first[..4] != [0x27, 0x05, 0x19, 0x56] { + return Err(StockError::Method(format!( + "the on-board stock {label} slot does not hold a stock image" + ))); + } + let payload = u32::from_be_bytes([first[12], first[13], first[14], first[15]]) as u64; + let total = 64u64 + .checked_add(payload) + .ok_or_else(|| StockError::Method(format!("the on-board stock {label} slot is invalid")))?; + let bytes = total.div_ceil(BLK) * BLK; + if total <= 64 || bytes > slot { + return Err(StockError::Method(format!( + "the on-board stock {label} slot does not hold a stock image" + ))); + } + if bytes <= BLK { + return Ok(first[..bytes as usize].to_vec()); + } + let rest = read_mtd_span(host, password, map, absolute + BLK, bytes - BLK, label)?; + let mut out = first; + out.extend_from_slice(&rest); + out.truncate(bytes as usize); + Ok(out) +} + +fn read_validated_onboard_stock_backup( + host: &str, + password: Option<&str>, + map: &[Mtd], +) -> Result, StockError> { + let Some((mtd, rel)) = locate_mtd(map, STOCK_BACKUP_BASE) else { + return Ok(None); + }; + if rel + .checked_add(STOCK_BACKUP_HEADER) + .map_or(true, |end| end > mtd.size) + { + return Ok(None); + } + let remote = format!( + "dd if={} bs={} skip={} count={} 2>/dev/null", + mtd.device, + BLK, + rel / BLK, + STOCK_BACKUP_HEADER / BLK + ); + let header = ssh_exec(host, password, &remote, Duration::from_secs(120))?; + if !header.ok() || header.stdout.len() as u64 != STOCK_BACKUP_HEADER { + return Ok(None); + } + let Some(backup) = parse_stock_backup(&header.stdout) else { + return Ok(None); + }; + for entry in &backup.entries { + let Some((entry_mtd, entry_rel)) = locate_mtd(map, entry.backup_abs) else { + return Ok(None); + }; + if entry_rel + .checked_add(entry.size) + .map_or(true, |end| end > entry_mtd.size) + { + return Ok(None); + } + let remote = format!( + "dd if={} bs={} skip={} count={} 2>/dev/null | md5sum | cut -d' ' -f1", + entry_mtd.device, + BLK, + entry_rel / BLK, + entry.size / BLK + ); + let result = ssh_exec(host, password, &remote, Duration::from_secs(300))?; + if !result.ok() { + return Ok(None); + } + if !text(&result.stdout).trim().eq_ignore_ascii_case(&entry.md5) { + return Ok(None); + } + } + Ok(Some(backup)) +} + +fn create_onboard_stock_backup( + host: &str, + password: Option<&str>, + map: &[Mtd], +) -> Result<(), StockError> { + let dtb = read_mtd_span(host, password, map, ABS_DTB, DTB_SLOT, "device tree")?; + if dtb.len() < 8 || dtb[..4] != [0xd0, 0x0d, 0xfe, 0xed] { + return Err(StockError::Method( + "the stock device tree slot is not usable for a backup".into(), + )); + } + let kernel = stock_uimage_span(host, password, map, ABS_KERNEL, KERNEL_SLOT, "kernel")?; + let ramdisk = stock_uimage_span(host, password, map, ABS_ROOTFS, ROOTFS_SLOT, "ramdisk")?; + + let mut prepared: Vec<(&'static str, u64, Vec)> = vec![ + ("dtb", ABS_DTB, dtb), + ("kernel", ABS_KERNEL, kernel), + ("ramdisk", ABS_ROOTFS, ramdisk), + ]; + let mut entries = Vec::with_capacity(prepared.len()); + let mut next = STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER; + for (name, target_abs, data) in &prepared { + let size = data.len() as u64; + if next + .checked_add(size) + .map_or(true, |end| end > STOCK_BACKUP_END) + { + return Err(StockError::Method( + "the on-board stock backup area is too small".into(), + )); + } + entries.push(StockBackupEntry { + name, + target_abs: *target_abs, + backup_abs: next, + size, + md5: md5_hex(data), + }); + next += size; + } + let header = render_stock_backup(&entries); + + let mut write: Vec<(&'static str, &'static str, u64, u64, Cow<'static, [u8]>)> = Vec::new(); + write.push(( + "backup-header-clear", + "stock-backup-empty.bin", + STOCK_BACKUP_BASE, + STOCK_BACKUP_HEADER, + Cow::Owned(vec![0u8; STOCK_BACKUP_HEADER as usize]), + )); + for (entry, (_, _, data)) in entries.iter().zip(prepared.drain(..)) { + write.push(( + match entry.name { + "dtb" => "backup-dtb", + "kernel" => "backup-kernel", + _ => "backup-ramdisk", + }, + match entry.name { + "dtb" => "stock-backup.dtb", + "kernel" => "stock-backup-kernel.uimg", + _ => "stock-backup-ramdisk.uimg", + }, + entry.backup_abs, + entry.size, + Cow::Owned(data), + )); + } + write.push(( + "backup-header", + "stock-backup.txt", + STOCK_BACKUP_BASE, + STOCK_BACKUP_HEADER, + Cow::Owned(header), + )); + let targets = targets_from_map(map, write)?; + flash_via_ssh(host, password, &targets)?; + match read_validated_onboard_stock_backup(host, password, map)? { + Some(_) => Ok(()), + None => Err(StockError::Method( + "the on-board stock backup did not verify after it was written".into(), + )), + } +} + +fn restore_from_onboard_backup_impl( + host: &str, + password: Option<&str>, + timeout: Duration, +) -> Result<(), StockError> { + validate_host(host)?; + if !ssh_port_open(host) { + if is_stock_http(host) { + return Ok(()); + } + return Err(StockError::Network("target unreachable".into())); + } + let resolved = resolve_password(password); + let password = resolved.as_deref(); + ssh_probe(host, password)?; + let state = board_state(host, password)?; + if state == "stock" { + return Ok(()); + } + + let map = get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?; + let Some(backup) = read_validated_onboard_stock_backup(host, password, &map)? else { + return Err(StockError::Method( + "no complete on-board stock backup".into(), + )); + }; + let name = |wanted: &str| -> Result<&StockBackupEntry, StockError> { + backup + .entries + .iter() + .find(|entry| entry.name == wanted) + .ok_or_else(|| StockError::Method("no complete on-board stock backup".into())) + }; + let dtb_entry = name("dtb")?; + let kernel_entry = name("kernel")?; + let ramdisk_entry = name("ramdisk")?; + let dtb = read_mtd_span( + host, + password, + &map, + dtb_entry.backup_abs, + dtb_entry.size, + "device tree", + )?; + let kernel = read_mtd_span( + host, + password, + &map, + kernel_entry.backup_abs, + kernel_entry.size, + "kernel", + )?; + let ramdisk = read_mtd_span( + host, + password, + &map, + ramdisk_entry.backup_abs, + ramdisk_entry.size, + "ramdisk", + )?; + + let write = vec![ + ( + "ramdisk", + "stock-rootfs.uimg", + ABS_ROOTFS, + ROOTFS_SLOT, + Cow::Owned(ramdisk), + ), + ("dtb", "stock-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)), + ( + "kernel", + "stock-kernel.uimg", + ABS_KERNEL, + KERNEL_SLOT, + Cow::Owned(kernel), + ), + ]; + let targets = targets_from_map(&map, write)?; + flash_via_ssh(host, password, &targets)?; + reboot_target(host, password); + let _ = wait_stock(host, timeout); + Ok(()) +} + +fn onboard_stock_backup_present_impl( + host: &str, + password: Option<&str>, +) -> Result { + validate_host(host)?; + if !ssh_port_open(host) { + if is_stock_http(host) { + return Ok(false); + } + return Err(StockError::Network("target unreachable".into())); + } + let resolved = resolve_password(password); + let password = resolved.as_deref(); + ssh_probe(host, password)?; + let map = get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?; + Ok(read_validated_onboard_stock_backup(host, password, &map)?.is_some()) +} + // ---------------------------------------------------------------- install / restore +fn choose_web_password( + host: &str, + password: Option<&str>, + dir: &Path, + tag: &str, +) -> Result { + let candidates = web_password_candidates(password); + let mut last_auth = false; + for (index, candidate) in candidates.iter().enumerate() { + match stock_web_auth(host, candidate, dir, &format!("{tag}{index}")) { + Ok(()) => return Ok(candidate.clone()), + Err(StockError::Auth(_)) => { + last_auth = true; + continue; + } + Err(e) => return Err(e), + } + } + if last_auth { + Err(StockError::Auth("target rejected the credential".into())) + } else { + Err(StockError::Network("target unreachable".into())) + } +} + fn install_via_web( host: &str, password: Option<&str>, @@ -1767,32 +2565,12 @@ fn install_via_web( rootfs: Vec, ) -> Result<(), StockError> { let dir = TempDir::new("web")?; - let candidates = web_password_candidates(password); - let mut chosen = None; - let mut last_auth = false; - for (index, candidate) in candidates.iter().enumerate() { - match stock_web_auth(host, candidate, dir.path(), &format!("probe{index}")) { - Ok(()) => { - chosen = Some(candidate.clone()); - break; - } - Err(StockError::Auth(_)) => { - last_auth = true; - continue; - } - Err(e) => return Err(e), - } - } - let password = match chosen { - Some(password) => password, - None if last_auth => return Err(StockError::Auth("target rejected the credential".into())), - None => return Err(StockError::Network("target unreachable".into())), - }; + let password = choose_web_password(host, password, dir.path(), "probe")?; let targets = stock_web_targets(kernel, dtb, rootfs)?; let token = random_token(); let cgi = format!("zz{token}.cgi"); - let script = flash_script(&targets, &token, Some(&cgi)); + let script = flash_script(&targets, &token, Some(&cgi), true); let (body, boundary) = build_web_body(&targets, &token, &cgi, &script); let body_path = dir.join("upload.body"); write_private(&body_path, &body)?; @@ -1810,6 +2588,640 @@ fn install_via_web( } } +// ---------------------------------------------------------------- root primitives +// +// These stay sealed inside this module. The public interface in `stock.rs` +// describes only the operation and its result; nothing here is part of it. + +fn root_exec_via_ssh(host: &str, password: Option<&str>, cmd: &str) -> Result { + let remote = format!("sh -c {}", shell_quote(cmd)); + let result = ssh_exec(host, password, &remote, Duration::from_secs(3600))?; + if result.ok() { + Ok(command_output(&result)) + } else { + Err(command_failure(&result)) + } +} + +fn root_exec_via_web(host: &str, password: Option<&str>, cmd: &str) -> Result { + let dir = TempDir::new("root")?; + let password = choose_web_password(host, password, dir.path(), "root")?; + let token = random_token(); + let cgi = format!("zz{token}.cgi"); + let marker = format!("@@AKEXIT{token}@@"); + let script = format!( + "#!/bin/sh\n\ + printf 'Content-type: text/plain\\r\\n\\r\\n'\n\ + trap 'rm -f /www/pages/cgi-bin/{cgi}' EXIT\n\ + sh -c {quoted} 2>&1\n\ + ak_code=$?\n\ + printf '{marker}%d\\n' \"$ak_code\"\n", + cgi = cgi, + quoted = shell_quote(cmd), + marker = marker, + ); + let mut entries = web_base_entries(); + entries.push(TarEntry { + name: format!("p/{cgi}"), + mode: 0o755, + kind: b'0', + link: String::new(), + data: script.into_bytes(), + }); + let (body, boundary) = build_web_body_entries(entries); + let body_path = dir.join("upload.body"); + write_private(&body_path, &body)?; + + stock_web_upload_with_timeout( + host, + &password, + dir.path(), + &body_path, + &boundary, + &token, + 1800, + )?; + let trigger = stock_web_trigger_with_timeout(host, &password, dir.path(), &cgi, &token, 3600)?; + let output = text(&trigger.stdout); + if let Some(index) = output.rfind(&marker) { + let command_output = &output[..index]; + let status = output[index + marker.len()..] + .trim() + .parse::() + .unwrap_or(-1); + if status == 0 { + return Ok(command_output.to_string()); + } + return Err(command_exit_error(status, command_output.to_string())); + } + if trigger.timed_out { + return Err(StockError::Network("target did not respond".into())); + } + if !trigger.ok() { + return Err(StockError::Network("target unreachable".into())); + } + Err(StockError::Method("command channel did not respond".into())) +} + +fn root_put_via_ssh( + host: &str, + password: Option<&str>, + data: &[u8], + remote_path: &str, +) -> Result<(), StockError> { + let dir = TempDir::new("put")?; + let payload = dir.join("payload"); + write_private(&payload, data)?; + + let parent = remote_parent(remote_path); + let prep = ssh_exec( + host, + password, + &format!("mkdir -p {}", shell_quote(parent)), + Duration::from_secs(60), + )?; + if !prep.ok() { + return Err(command_failure(&prep)); + } + + let token = random_token(); + let temp_path = format!("{remote_path}.ak-tmp-{token}"); + let remote = format!("cat > {}", shell_quote(&temp_path)); + let input = fs::File::open(&payload) + .map_err(|e| StockError::Io(format!("could not read the payload: {e}")))?; + let result = run_command_stream( + ssh_command(host, password, &remote), + Duration::from_secs(1800), + input, + )?; + if result.timed_out { + let _ = ssh_exec( + host, + password, + &format!("rm -f {}", shell_quote(&temp_path)), + Duration::from_secs(15), + ); + return Err(StockError::Network("target transfer timed out".into())); + } + if !result.ok() { + let _ = ssh_exec( + host, + password, + &format!("rm -f {}", shell_quote(&temp_path)), + Duration::from_secs(15), + ); + return Err(command_failure(&result)); + } + + let finalize = format!( + "chmod 0644 {temp} && mv -f {temp} {path}", + temp = shell_quote(&temp_path), + path = shell_quote(remote_path), + ); + let result = ssh_exec(host, password, &finalize, Duration::from_secs(60))?; + if !result.ok() { + let _ = ssh_exec( + host, + password, + &format!("rm -f {}", shell_quote(&temp_path)), + Duration::from_secs(15), + ); + return Err(command_failure(&result)); + } + Ok(()) +} + +fn root_put_via_web( + host: &str, + password: Option<&str>, + data: &[u8], + remote_path: &str, +) -> Result<(), StockError> { + let dir = TempDir::new("put")?; + let password = choose_web_password(host, password, dir.path(), "put")?; + let token = random_token(); + let cgi = format!("zz{token}.cgi"); + let marker = format!("@@AKPUT{token}@@"); + let staged = format!("/tmp/.ak-put-{token}"); + let temp_path = format!("{remote_path}.ak-tmp-{token}"); + let parent = remote_parent(remote_path); + let script = format!( + "#!/bin/sh\n\ + f={staged}\n\ + t={temp}\n\ + trap 'rm -f \"$f\" \"$t\" /www/pages/cgi-bin/{cgi}' EXIT\n\ + mkdir -p {parent} || {{ printf '{marker}fail\\n'; exit 1; }}\n\ + cp \"$f\" \"$t\" || {{ printf '{marker}fail\\n'; exit 1; }}\n\ + chmod 0644 \"$t\" || {{ printf '{marker}fail\\n'; exit 1; }}\n\ + mv -f \"$t\" {path} || {{ printf '{marker}fail\\n'; exit 1; }}\n\ + printf '{marker}ok\\n'\n", + staged = shell_quote(&staged), + temp = shell_quote(&temp_path), + cgi = cgi, + parent = shell_quote(parent), + marker = marker, + path = shell_quote(remote_path), + ); + + let mut entries = web_base_entries(); + entries.push(TarEntry { + name: format!("d/.ak-put-{token}"), + mode: 0o600, + kind: b'0', + link: String::new(), + data: data.to_vec(), + }); + entries.push(TarEntry { + name: format!("p/{cgi}"), + mode: 0o755, + kind: b'0', + link: String::new(), + data: script.into_bytes(), + }); + let (body, boundary) = build_web_body_entries(entries); + let body_path = dir.join("upload.body"); + write_private(&body_path, &body)?; + + stock_web_upload_with_timeout( + host, + &password, + dir.path(), + &body_path, + &boundary, + &token, + 1800, + )?; + let trigger = stock_web_trigger_with_timeout(host, &password, dir.path(), &cgi, &token, 1800)?; + let output = text(&trigger.stdout); + if output.contains(&format!("{marker}ok")) { + return Ok(()); + } + if output.contains(&format!("{marker}fail")) { + return Err(StockError::Method("could not write the remote file".into())); + } + if trigger.timed_out { + return Err(StockError::Network("target did not respond".into())); + } + if !trigger.ok() { + return Err(StockError::Network("target unreachable".into())); + } + Err(StockError::Method("command channel did not respond".into())) +} + +// ---------------------------------------------------------------- stock daemon channel +// +// On this board class the stock image has no privileged login at all: root's +// shell is disabled, the SSH daemon refuses root logins, and the only account +// that logs in is unprivileged with no sudo. The vendor keeps every privileged +// operation (firmware updates, reboots, config writes) behind a root-owned +// helper that its own web layer talks to over loopback; that helper accepts a +// command line from a local client and runs it through a shell as root. +// +// This route therefore needs no exploit of its own: it logs in with the stock +// account, stages a short script under /tmp, hands the script to the vendor +// helper through the helper's own installed client, and reads the result back. +// Only /tmp is written; the stock system, the boot chain and the NAND layout +// are never touched. The alternative route (the web upload) is left in place +// for boards where it does work. + +const STOCK_UNPRIV_USER_DEFAULT: &str = "miner"; +const STOCK_UNPRIV_PASSWORD_DEFAULT: &str = "miner"; +const STOCK_DAEMON_CLIENT: &str = "/usr/sbin/daemonc"; +const STOCK_CHANNEL_READY: &str = "__ALKANE_STOCK_CHANNEL_READY__"; +const STOCK_CHANNEL_ABSENT: &str = "__ALKANE_STOCK_CHANNEL_ABSENT__"; +const STOCK_RUN_MARK: &str = "@@AKRUN"; + +/// The stock account this board class allows over SSH. Overridable so an +/// operator whose board was provisioned differently does not need a new build. +fn stock_unpriv_user() -> String { + env::var("ALKANE_STOCK_LOGIN_USER") + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| is_plain_user(value)) + .unwrap_or_else(|| STOCK_UNPRIV_USER_DEFAULT.to_string()) +} + +fn is_plain_user(value: &str) -> bool { + !value.is_empty() + && value.len() <= 32 + && value + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')) +} + +/// Passwords to try for the unprivileged stock account, in order: the one the +/// caller supplied, then any from the environment, then the documented vendor +/// default for that account on this board class. +fn stock_unpriv_passwords(password: Option<&str>) -> Vec { + let mut candidates = Vec::new(); + let mut push = |value: &str| { + if !value.is_empty() && !candidates.iter().any(|known| known == value) { + candidates.push(value.to_string()); + } + }; + if let Some(password) = password { + push(password); + } + if let Ok(value) = env::var("ALKANE_STOCK_LOGIN_PASSWORD") { + push(&value); + } + if let Some(value) = resolve_password(None) { + push(&value); + } + push(STOCK_UNPRIV_PASSWORD_DEFAULT); + candidates +} + +enum ChannelProbe { + Ready { uid: String }, + Absent, + Denied, + Failed(StockError), +} + +/// Stage `script` at `remote_script` and report whether the vendor helper is +/// present on this board and the login was accepted. +fn probe_stock_channel( + host: &str, + user: &str, + password: &str, + script: &str, + remote_script: &str, +) -> Result { + let remote = format!( + "if [ ! -x {client} ]; then echo {absent}; exit 9; fi; \ + cat > {path} && chmod 0644 {path} || exit 8; \ + id -u; echo {ready}", + client = shell_quote(STOCK_DAEMON_CLIENT), + absent = STOCK_CHANNEL_ABSENT, + path = shell_quote(remote_script), + ready = STOCK_CHANNEL_READY, + ); + let result = run_command( + ssh_command_as(host, user, Some(password), &remote), + Duration::from_secs(60), + Some(script.as_bytes().to_vec()), + )?; + let stdout = text(&result.stdout); + if result.ok() && stdout.contains(STOCK_CHANNEL_READY) { + let uid = stdout + .lines() + .find(|line| line.trim().parse::().is_ok()) + .map(|line| line.trim().to_string()) + .ok_or_else(|| StockError::Method("command channel did not respond".into()))?; + return Ok(ChannelProbe::Ready { uid }); + } + if stdout.contains(STOCK_CHANNEL_ABSENT) { + return Ok(ChannelProbe::Absent); + } + if is_login_refused(&result) { + return Ok(ChannelProbe::Denied); + } + if result.timed_out { + return Err(StockError::Network("target did not respond".into())); + } + Ok(ChannelProbe::Failed(command_failure(&result))) +} + +/// Run `script` as root through the stock daemon channel and return its +/// combined output. `Ok(NotApplicable)` means this is not a board with that +/// channel, so the caller should use another route. +fn stock_channel_run( + host: &str, + password: Option<&str>, + script: &str, +) -> Result { + let user = stock_unpriv_user(); + let token = random_token(); + let remote_script = format!("/tmp/.ak-cmd-{token}"); + let remote_out = format!("/tmp/.ak-out-{token}"); + let remote_missing = format!("/tmp/.ak-none-{token}"); + let mut denied = false; + + for candidate in stock_unpriv_passwords(password) { + match probe_stock_channel(host, &user, &candidate, script, &remote_script)? { + ChannelProbe::Ready { uid } => { + return stock_channel_execute( + host, + &user, + &candidate, + &uid, + &token, + &remote_script, + &remote_out, + &remote_missing, + ) + } + ChannelProbe::Absent => return Err(StockError::NotApplicable), + ChannelProbe::Denied => { + denied = true; + continue; + } + ChannelProbe::Failed(error) => return Err(error), + } + } + + if denied { + Err(StockError::Auth("target rejected the credential".into())) + } else { + Err(StockError::NotApplicable) + } +} + +/// Hand the staged script to the vendor helper. The helper is given a path +/// that does not exist first, so the vendor's own handler runs and exits +/// before anything of ours does; the script then runs as root, its output is +/// written to a private file that is handed back to the stock account, and +/// every staged file is removed again by the root side. +fn stock_channel_execute( + host: &str, + user: &str, + password: &str, + uid: &str, + token: &str, + remote_script: &str, + remote_out: &str, + remote_missing: &str, +) -> Result { + let mark = format!("{STOCK_RUN_MARK}{token}="); + let inject = format!( + "{missing}; sh {script} > {out} 2>&1; \ + echo \"{mark}$?\" >> {out}; \ + chmod 0644 {out} && chown {uid} {out}; \ + rm -f {script}", + missing = shell_quote(remote_missing), + script = shell_quote(remote_script), + out = shell_quote(remote_out), + mark = mark, + uid = shell_quote(uid), + ); + let remote = format!( + "{} {}", + shell_quote(STOCK_DAEMON_CLIENT), + shell_quote(&inject) + ); + let run = ssh_exec_as( + host, + user, + Some(password), + &remote, + Duration::from_secs(3600), + ); + + // Collect whatever the root side left, even when the call above failed or + // timed out, so the temporary files are removed either way. + let collect = format!( + "cat {out}; rm -f {out} {script}", + out = shell_quote(remote_out), + script = shell_quote(remote_script), + ); + let read = ssh_exec_as( + host, + user, + Some(password), + &collect, + Duration::from_secs(120), + ); + if let Ok(read) = &read { + if let Some((body, status)) = split_run_result(&text(&read.stdout), &mark) { + if status == 0 { + return Ok(body); + } + return Err(command_exit_error(status, body)); + } + } + if let Err(error) = run { + return Err(error); + } + if let Err(error) = read { + return Err(error); + } + Err(StockError::Method("command channel did not respond".into())) +} + +/// Split the collected file into the command output and the exit status the +/// root side appended after it. The status marker carries this call's token so +/// a command cannot forge it, and it is appended straight after the command's +/// last byte, so a command whose output has no trailing newline still parses. +fn split_run_result(output: &str, mark: &str) -> Option<(String, i32)> { + let index = output.rfind(mark)?; + let body = output[..index].to_string(); + let rest = &output[index + mark.len()..]; + let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect(); + let status = digits.parse::().ok()?; + Some((body, status)) +} + +fn stock_root_exec(host: &str, password: Option<&str>, cmd: &str) -> Result { + if cmd.trim().is_empty() { + return Err(StockError::Method("empty command".into())); + } + let script = format!("#!/bin/sh\n{cmd}\n"); + stock_channel_run(host, password, &script) +} + +fn stock_root_put( + host: &str, + password: Option<&str>, + data: &[u8], + remote_path: &str, +) -> Result<(), StockError> { + let user = stock_unpriv_user(); + let token = random_token(); + let staged = format!("/tmp/.ak-put-{token}"); + let scratch = format!("{remote_path}.ak-tmp-{token}"); + + let password = stage_stock_payload(host, &user, password, data, &staged)?; + + if let Err(error) = verify_stock_payload(host, &user, &password, data.len(), &staged) { + let _ = ssh_exec_as( + host, + &user, + Some(&password), + &format!("rm -f {}", shell_quote(&staged)), + Duration::from_secs(30), + ); + return Err(error); + } + + let script = format!( + "#!/bin/sh\n\ + src={src}\n\ + dst={dst}\n\ + tmp={tmp}\n\ + dir={dir}\n\ + mkdir -p \"$dir\" || {{ echo \"could not create the remote directory\"; exit 11; }}\n\ + cp \"$src\" \"$tmp\" || {{ rm -f \"$tmp\"; echo \"could not copy the staged file\"; exit 12; }}\n\ + chmod 0644 \"$tmp\" || {{ rm -f \"$tmp\"; echo \"could not set the file mode\"; exit 13; }}\n\ + mv -f \"$tmp\" \"$dst\" || {{ rm -f \"$tmp\"; echo \"could not move the file into place\"; exit 14; }}\n\ + n=$(wc -c < \"$dst\" 2>/dev/null)\n\ + [ \"$n\" = {size} ] || {{ echo \"the written file is $n bytes, not {size}\"; exit 15; }}\n\ + rm -f \"$src\"\n\ + exit 0\n", + src = shell_quote(&staged), + dst = shell_quote(remote_path), + tmp = shell_quote(&scratch), + dir = shell_quote(remote_parent(remote_path)), + size = shell_quote(&data.len().to_string()), + ); + + let result = stock_channel_run(host, Some(&password), &script); + if result.is_err() { + // The staged copy belongs to the stock account, so it can always be + // removed even when the root side never ran. + let _ = ssh_exec_as( + host, + &user, + Some(&password), + &format!("rm -f {} {}", shell_quote(&staged), shell_quote(&scratch)), + Duration::from_secs(30), + ); + } + result.map(|_| ()) +} + +/// Stream the payload to a temporary file owned by the stock account and +/// return the password that account accepted. +fn stage_stock_payload( + host: &str, + user: &str, + password: Option<&str>, + data: &[u8], + staged: &str, +) -> Result { + let dir = TempDir::new("stockput")?; + let payload = dir.join("payload"); + write_private(&payload, data)?; + + for candidate in stock_unpriv_passwords(password) { + let remote = format!( + "cat > {path} && chmod 0644 {path}", + path = shell_quote(staged) + ); + let input = fs::File::open(&payload) + .map_err(|e| StockError::Io(format!("could not read the payload: {e}")))?; + let result = run_command_stream( + ssh_command_as(host, user, Some(&candidate), &remote), + Duration::from_secs(1800), + input, + )?; + if result.ok() { + return Ok(candidate); + } + if result.timed_out { + return Err(StockError::Network("target transfer timed out".into())); + } + if is_login_refused(&result) { + continue; + } + return Err(command_failure(&result)); + } + Err(StockError::Auth("target rejected the credential".into())) +} + +fn verify_stock_payload( + host: &str, + user: &str, + password: &str, + size: usize, + staged: &str, +) -> Result<(), StockError> { + let remote = format!("wc -c < {path}", path = shell_quote(staged)); + let result = ssh_exec_as(host, user, Some(password), &remote, Duration::from_secs(60))?; + if !result.ok() { + return Err(command_failure(&result)); + } + let got = text(&result.stdout).trim().parse::().unwrap_or(0); + if got != size as u64 { + return Err(StockError::Method("target transfer was short".into())); + } + Ok(()) +} + +fn root_exec_impl(host: &str, password: Option<&str>, cmd: &str) -> Result { + validate_host(host)?; + let resolved = resolve_password(password); + let ssh_password = resolved.as_deref(); + match ssh_root_ready(host, ssh_password) { + Ok(()) => root_exec_via_ssh(host, ssh_password, cmd), + Err(ssh_error) => match stock_root_exec(host, password, cmd) { + Err(StockError::NotApplicable) | Err(StockError::Auth(_)) => { + if is_stock_http(host) { + root_exec_via_web(host, password, cmd) + } else { + Err(ssh_error) + } + } + other => other, + }, + } +} + +fn root_put_impl( + host: &str, + password: Option<&str>, + data: &[u8], + remote_path: &str, +) -> Result<(), StockError> { + validate_host(host)?; + validate_remote_path(remote_path)?; + let resolved = resolve_password(password); + let ssh_password = resolved.as_deref(); + match ssh_root_ready(host, ssh_password) { + Ok(()) => root_put_via_ssh(host, ssh_password, data, remote_path), + Err(ssh_error) => match stock_root_put(host, password, data, remote_path) { + Err(StockError::NotApplicable) | Err(StockError::Auth(_)) => { + if is_stock_http(host) { + root_put_via_web(host, password, data, remote_path) + } else { + Err(ssh_error) + } + } + other => other, + }, + } +} + /// The alkane write set for this board, placed on the given storage map: /// rootfs, then dtb, then kernel (so an interrupted write never leaves a new /// rootfs under an old kernel). `kernel` and `rootfs` are the uImage-wrapped @@ -1846,8 +3258,16 @@ fn install_via_ssh( kernel: Vec, dtb: Vec, rootfs: Vec, + backup_stock: bool, ) -> Result<(), StockError> { - let map = get_mtd_map(host, password)?; + let map = if backup_stock { + get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)? + } else { + get_mtd_map(host, password)? + }; + if backup_stock { + create_onboard_stock_backup(host, password, &map)?; + } let targets = alkane_targets(&map, kernel, dtb, rootfs)?; flash_via_ssh(host, password, &targets)?; reboot_target(host, password); @@ -1877,7 +3297,7 @@ fn flash_via_ssh( let timeout = Duration::from_secs(300); ssh_push(host, password, &remote, target.data.as_ref(), timeout)?; } - let script = flash_script(targets, "", None); + let script = flash_script(targets, "", None, false); let remote_script = "/tmp/rs/go.sh"; ssh_push( host, @@ -2227,7 +3647,7 @@ impl StockMethod for Method { let resolved = resolve_password(password); let password = resolved.as_deref(); ssh_probe(host, password)?; - return install_via_ssh(host, password, kernel, dtb, rootfs); + return install_via_ssh(host, password, kernel, dtb, rootfs, false); } // A board on genuine stock is reached through its own web gate. @@ -2236,7 +3656,8 @@ impl StockMethod for Method { let resolved = resolve_password(password); let password = resolved.as_deref(); ssh_probe(host, password)?; - return install_via_ssh(host, password, kernel, dtb, rootfs); + let stock = board_state(host, password)? == "stock"; + return install_via_ssh(host, password, kernel, dtb, rootfs, stock); } return Err(StockError::Network("target unreachable".into())); } @@ -2302,6 +3723,25 @@ impl StockMethod for Method { Ok(()) } + fn root_exec( + &self, + host: &str, + password: Option<&str>, + cmd: &str, + ) -> Result { + root_exec_impl(host, password, cmd) + } + + fn root_put( + &self, + host: &str, + password: Option<&str>, + data: &[u8], + remote_path: &str, + ) -> Result<(), StockError> { + root_put_impl(host, password, data, remote_path) + } + fn update_in_place( &self, host: &str, @@ -2311,6 +3751,23 @@ impl StockMethod for Method { ) -> Result { update_in_place_impl(host, afw, password, options) } + + fn onboard_stock_backup_present( + &self, + host: &str, + password: Option<&str>, + ) -> Result { + onboard_stock_backup_present_impl(host, password) + } + + fn restore_from_onboard_backup( + &self, + host: &str, + password: Option<&str>, + timeout: Duration, + ) -> Result<(), StockError> { + restore_from_onboard_backup_impl(host, password, timeout) + } } static METHOD: Method = Method; @@ -2325,6 +3782,94 @@ pub fn method() -> &'static dyn StockMethod { mod tests { use super::*; + #[test] + fn shell_quote_round_trips_awkward_arguments() { + for value in [ + "/tmp/plain", + "/tmp/with space", + "/tmp/with'quote", + "a$b`c`d\"e\\f", + "line\nbreak", + "", + ] { + assert_eq!( + shell_quote(value), + format!("'{}'", value.replace('\'', "'\\''")) + ); + } + } + + #[test] + fn run_result_splits_output_from_status() { + let marker = format!("{STOCK_RUN_MARK}abc123="); + assert_eq!( + split_run_result(&format!("uid=0(root)\n{marker}0\n"), &marker), + Some(("uid=0(root)\n".to_string(), 0)) + ); + // A command whose output does not end in a newline still parses. + assert_eq!( + split_run_result(&format!("no-newline{marker}3"), &marker), + Some(("no-newline".to_string(), 3)) + ); + // The last marker wins; earlier ones are ordinary output. + assert_eq!( + split_run_result(&format!("{marker}9\nreal{marker}0\n"), &marker), + Some((format!("{marker}9\nreal"), 0)) + ); + assert_eq!(split_run_result("nothing here\n", &marker), None); + assert_eq!(split_run_result(&format!("body{marker}"), &marker), None); + // A marker from another call is not accepted. + let other = format!("{STOCK_RUN_MARK}other="); + assert_eq!(split_run_result(&format!("out{other}0\n"), &marker), None); + } + + #[test] + fn stock_login_defaults_included_and_deduplicated() { + let candidates = stock_unpriv_passwords(Some("supplied")); + assert_eq!(candidates.first().map(String::as_str), Some("supplied")); + assert!(candidates + .iter() + .any(|value| value == STOCK_UNPRIV_PASSWORD_DEFAULT)); + let mut seen = candidates.clone(); + seen.sort(); + seen.dedup(); + assert_eq!(seen.len(), candidates.len()); + assert!(is_plain_user(STOCK_UNPRIV_USER_DEFAULT)); + assert!(!is_plain_user("bad user")); + assert!(!is_plain_user("bad;user")); + assert!(!is_plain_user("")); + } + + #[test] + fn remote_paths_are_split_and_validated() { + assert_eq!(remote_parent("/tmp/a/b"), "/tmp/a"); + assert_eq!(remote_parent("/tmp"), "/"); + assert_eq!(remote_parent("relative"), "."); + assert!(validate_remote_path("/tmp/a").is_ok()); + assert!(validate_remote_path("").is_err()); + assert!(validate_remote_path("/tmp/").is_err()); + assert!(validate_remote_path("/tmp/\0bad").is_err()); + } + + #[cfg(unix)] + #[test] + fn streamed_command_input_is_transferred_whole() { + let dir = TempDir::new("streamtest").expect("temp dir"); + let payload = vec![0xA5u8; 2 * 1024 * 1024 + 17]; + let input = dir.join("input"); + let output = dir.join("output"); + write_private(&input, &payload).expect("write input"); + let mut command = Command::new("sh"); + command + .arg("-c") + .arg(format!("cat > {}", shell_quote(&output.to_string_lossy()))); + let file = fs::File::open(&input).expect("open input"); + let result = + run_command_stream(command, Duration::from_secs(30), file).expect("stream command"); + assert!(result.ok()); + assert_eq!(fs::read(&output).expect("read output"), payload); + } + #[test] fn md5_known_vectors() { assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e"); @@ -2599,4 +4144,51 @@ mod tests { assert!(absolute >= BOOTBIN_PRESERVE); } } + + #[test] + fn stock_backup_manifest_round_trips_and_rejects_incomplete() { + let base = STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER; + let entries = vec![ + StockBackupEntry { + name: "dtb", + target_abs: ABS_DTB, + backup_abs: base, + size: DTB_SLOT, + md5: "0".repeat(32), + }, + StockBackupEntry { + name: "kernel", + target_abs: ABS_KERNEL, + backup_abs: base + DTB_SLOT, + size: BLK, + md5: "1".repeat(32), + }, + StockBackupEntry { + name: "ramdisk", + target_abs: ABS_ROOTFS, + backup_abs: base + DTB_SLOT + BLK, + size: BLK, + md5: "2".repeat(32), + }, + ]; + let header = render_stock_backup(&entries); + let mut padded = header.clone(); + padded.resize(STOCK_BACKUP_HEADER as usize, 0xff); + let parsed = parse_stock_backup(&padded).expect("manifest parses"); + assert_eq!(parsed.entries.len(), 3); + assert_eq!(parsed.entries[1].size, BLK); + + let text = String::from_utf8(header).unwrap(); + let missing = text.replace( + &format!( + "kernel 0x{:x} 0x{:x} 0x{:x} {}\n", + ABS_KERNEL, + base + DTB_SLOT, + BLK, + "1".repeat(32) + ), + "", + ); + assert!(parse_stock_backup(missing.as_bytes()).is_none()); + } } diff --git a/crates/alkane-flash/src/uimage.rs b/crates/alkane-flash/src/uimage.rs new file mode 100644 index 00000000..63216f00 --- /dev/null +++ b/crates/alkane-flash/src/uimage.rs @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: MIT +//! Legacy U-Boot image (`uImage`) header builder. +//! +//! The Zynq (Antminer S17/S19-class) stock U-Boot boots a legacy uImage: a +//! 64-byte big-endian header (magic `0x27051956`) in front of the payload. We +//! wrap the kernel (a raw ARM `zImage`) and the ramdisk (a gzipped cpio) in this +//! header so the board's own U-Boot boots them unchanged. The device tree is +//! written raw (no header). +//! +//! The header parameters below were read directly off a genuine stock S17 NAND +//! (kernel: type Kernel, uncompressed, load/entry `0x8000`; ramdisk: type +//! RAMDisk, gzip, load/entry `0`), so the images we write match exactly what the +//! stock boot chain already boots. + +/// Legacy uImage magic (big-endian). +pub const IH_MAGIC: u32 = 0x2705_1956; +/// Header length in bytes. +pub const HEADER_LEN: usize = 64; + +// ih_os +const IH_OS_LINUX: u8 = 5; +// ih_arch +const IH_ARCH_ARM: u8 = 2; +// ih_type +const IH_TYPE_KERNEL: u8 = 2; +const IH_TYPE_RAMDISK: u8 = 3; +// ih_comp +const IH_COMP_NONE: u8 = 0; +const IH_COMP_GZIP: u8 = 1; + +/// A CRC-32 (IEEE 802.3, the variant U-Boot uses) over `data`. +pub fn crc32(data: &[u8]) -> u32 { + let mut crc: u32 = 0xFFFF_FFFF; + for &byte in data { + crc ^= byte as u32; + for _ in 0..8 { + let mask = (crc & 1).wrapping_neg(); + crc = (crc >> 1) ^ (0xEDB8_8320 & mask); + } + } + !crc +} + +/// Which kind of uImage to build. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// ARM Linux kernel, uncompressed, load/entry 0x8000 (what the stock S17 + /// kernel uImage uses). + Kernel, + /// ARM Linux ramdisk, gzip, load/entry 0 (what the stock S17 ramdisk uImage + /// uses). + Ramdisk, +} + +impl Kind { + fn ih_type(self) -> u8 { + match self { + Kind::Kernel => IH_TYPE_KERNEL, + Kind::Ramdisk => IH_TYPE_RAMDISK, + } + } + fn ih_comp(self) -> u8 { + match self { + Kind::Kernel => IH_COMP_NONE, + Kind::Ramdisk => IH_COMP_GZIP, + } + } + fn load_entry(self) -> u32 { + match self { + Kind::Kernel => 0x8000, + Kind::Ramdisk => 0, + } + } +} + +/// Wrap `payload` in a legacy uImage header of the given `kind` and return the +/// full image (header followed by payload). `time` is the header timestamp; pass +/// a fixed value for a reproducible image. `name` is truncated to 31 bytes. +pub fn wrap(kind: Kind, payload: &[u8], time: u32, name: &str) -> Vec { + let mut hdr = [0u8; HEADER_LEN]; + hdr[0..4].copy_from_slice(&IH_MAGIC.to_be_bytes()); + // hdr[4..8] header CRC: filled in last, over the header with this field zero. + hdr[8..12].copy_from_slice(&time.to_be_bytes()); + hdr[12..16].copy_from_slice(&(payload.len() as u32).to_be_bytes()); + hdr[16..20].copy_from_slice(&kind.load_entry().to_be_bytes()); + hdr[20..24].copy_from_slice(&kind.load_entry().to_be_bytes()); + hdr[24..28].copy_from_slice(&crc32(payload).to_be_bytes()); + hdr[28] = IH_OS_LINUX; + hdr[29] = IH_ARCH_ARM; + hdr[30] = kind.ih_type(); + hdr[31] = kind.ih_comp(); + let name_bytes = name.as_bytes(); + let n = name_bytes.len().min(31); + hdr[32..32 + n].copy_from_slice(&name_bytes[..n]); + // Header CRC over the 64-byte header with the hcrc field (4..8) zeroed. + let hcrc = crc32(&hdr); + hdr[4..8].copy_from_slice(&hcrc.to_be_bytes()); + + let mut out = Vec::with_capacity(HEADER_LEN + payload.len()); + out.extend_from_slice(&hdr); + out.extend_from_slice(payload); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crc32_known_vector() { + // CRC-32/ISO-HDLC of "123456789" is 0xCBF43926. + assert_eq!(crc32(b"123456789"), 0xCBF4_3926); + assert_eq!(crc32(b""), 0); + } + + #[test] + fn header_shape_and_fields() { + let img = wrap(Kind::Kernel, b"payload-bytes", 0, "alkane"); + assert_eq!(img.len(), HEADER_LEN + 13); + assert_eq!(&img[0..4], &IH_MAGIC.to_be_bytes()); + assert_eq!(u32::from_be_bytes([img[12], img[13], img[14], img[15]]), 13); + // kernel: load/entry 0x8000, type kernel, comp none + assert_eq!(&img[16..20], &0x8000u32.to_be_bytes()); + assert_eq!(&img[20..24], &0x8000u32.to_be_bytes()); + assert_eq!(img[28], IH_OS_LINUX); + assert_eq!(img[29], IH_ARCH_ARM); + assert_eq!(img[30], IH_TYPE_KERNEL); + assert_eq!(img[31], IH_COMP_NONE); + assert_eq!(&img[64..], b"payload-bytes"); + } + + #[test] + fn ramdisk_fields() { + let img = wrap(Kind::Ramdisk, b"rd", 0, "rd"); + assert_eq!(&img[16..20], &0u32.to_be_bytes()); + assert_eq!(img[30], IH_TYPE_RAMDISK); + assert_eq!(img[31], IH_COMP_GZIP); + } + + #[test] + fn header_crc_validates() { + let img = wrap(Kind::Kernel, b"abc", 0x1234, "n"); + let mut hdr = [0u8; HEADER_LEN]; + hdr.copy_from_slice(&img[..HEADER_LEN]); + let stored = u32::from_be_bytes([hdr[4], hdr[5], hdr[6], hdr[7]]); + hdr[4..8].copy_from_slice(&[0, 0, 0, 0]); + assert_eq!(crc32(&hdr), stored); + // data CRC over payload + let dcrc = u32::from_be_bytes([img[24], img[25], img[26], img[27]]); + assert_eq!(crc32(b"abc"), dcrc); + } +} diff --git a/crates/alkane-flash/src/zynq_nand.rs b/crates/alkane-flash/src/zynq_nand.rs new file mode 100644 index 00000000..7abf9f0f --- /dev/null +++ b/crates/alkane-flash/src/zynq_nand.rs @@ -0,0 +1,809 @@ +// SPDX-License-Identifier: MIT +//! Readable Zynq-7010 NAND install / restore / on-board-backup, driven entirely +//! over the network through two small root shells: +//! +//! * a board on **stock** is reached with the DSH root-on-stock primitives +//! (`crate::stock::root_exec` / `root_put`): this is the only compartmentalised +//! piece, and it is used only to get a root shell; +//! * a board on **alkane** is reached with ordinary SSH (`crate::transport`). +//! +//! Everything else -- what to write, where, in what form, and the read-back +//! verification -- lives here in plain, auditable Rust. The NAND writes +//! themselves are the same `flash_erase` + `nandwrite` MTD operations on both +//! sides; only the way we obtain the root shell differs. +//! +//! Absolute NAND map (Micron MT29F2G08, 256 MiB, 128 KiB erase, 2 KiB page), +//! confirmed on a genuine stock S17 and mirrored by the alkane board DT: +//! ```text +//! 0x00000000 BOOT.bin (FSBL + bitstream + stock U-Boot + env) NEVER written +//! 0x01a00000 device tree (raw fdt) +//! 0x02000000 kernel (legacy uImage) +//! 0x02800000 rootfs (legacy uImage ramdisk) +//! 0x04800000 stock `configs` (UBI) exposed read-only on alkane +//! 0x05000000 alkane-cfg (persisted MAC) +//! 0x06000000 on-board genuine-stock backup (stock `ramfs-bak` region) +//! 0x08000000 stock `reserve1` / nvdata (UBI) left untouched +//! ``` +//! On a board running alkane the boot slots are exposed as the named partitions +//! `boot-dtb` / `boot-kernel` / `boot-rootfs` / `stock-backup` (see the board +//! DT); on stock they fall inside `mtd0` / `mtd1` / `ramfs-bak`. Because we map +//! an absolute offset to whichever MTD partition contains it, the same code +//! writes the same physical NAND on both sides. + +use crate::md5::md5_hex; +use crate::stock::StockError; +use crate::transport::{Remote, SshOptions, SshTransport}; +use crate::uimage::{self, Kind}; +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +/// NAND erase-block size (128 KiB). +const ERASE: u64 = 0x20000; +/// NAND page size (2 KiB); `nandwrite -p` pads the final page with 0xFF. +const PAGE: u64 = 0x800; + +/// Absolute boot-slot offsets (see the module map). +const OFF_DTB: u64 = 0x1a00000; +const OFF_KERNEL: u64 = 0x2000000; +const OFF_ROOTFS: u64 = 0x2800000; +const OFF_STOCK_BACKUP: u64 = 0x6000000; +/// BOOT.bin occupies 0x0..0x1a00000 and is never written. +const BOOTBIN_PRESERVE: u64 = 0x1a00000; + +/// Slot ceilings (so a too-large image is refused before any erase). +const SLOT_DTB: u64 = 0x600000; +const SLOT_KERNEL: u64 = 0x800000; +const SLOT_ROOTFS: u64 = 0x2000000; +const SLOT_STOCK_BACKUP: u64 = 0x2000000; + +/// Where the backup data lives inside the 32 MiB stock-backup region: the first +/// erase block holds the manifest, the images follow, each erase-block aligned. +const BK_MANIFEST: u64 = OFF_STOCK_BACKUP; // 0x6000000 +const BK_MAGIC: &[u8; 8] = b"ALKSTKB1"; + +fn round_up(value: u64, to: u64) -> u64 { + value.div_ceil(to) * to +} + +// --------------------------------------------------------------------------- +// Root shells +// --------------------------------------------------------------------------- + +/// A root shell on the target board: run a `/bin/sh` command as root and stream +/// a byte payload to a file as root. Both sides implement this; the NAND code +/// below is written once against it. +trait Shell { + fn exec(&mut self, cmd: &str) -> Result; + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError>; + /// Longer-running command (large nandwrite / nanddump). + fn exec_long(&mut self, cmd: &str) -> Result; +} + +/// Stock board: root obtained through the compartmentalised DSH primitive. +struct StockShell { + host: String, + password: Option, +} + +impl Shell for StockShell { + fn exec(&mut self, cmd: &str) -> Result { + crate::stock::root_exec(&self.host, self.password.as_deref(), cmd) + } + fn exec_long(&mut self, cmd: &str) -> Result { + crate::stock::root_exec(&self.host, self.password.as_deref(), cmd) + } + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> { + crate::stock::root_put(&self.host, self.password.as_deref(), data, remote_path) + } +} + +/// Alkane board: root over ordinary SSH. A throwaway known-hosts file is used +/// so a board whose SSH host key legitimately changed across an install still +/// connects (accept-new), which is the norm on the bench. +struct AlkaneShell { + transport: SshTransport, + _secret: TempFile, +} + +static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); + +fn temp_path(tag: &str) -> std::path::PathBuf { + let n = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); + std::env::temp_dir().join(format!("alkane-{}-{}-{}", std::process::id(), tag, n)) +} + +/// A 0600 temp file removed on drop. +struct TempFile(std::path::PathBuf); +impl TempFile { + fn with(contents: &[u8], tag: &str) -> Result { + let path = temp_path(tag); + write_private(&path, contents).map_err(|e| StockError::Io(e.to_string()))?; + Ok(TempFile(path)) + } +} +impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +#[cfg(unix)] +fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> { + use std::io::Write as _; + use std::os::unix::fs::OpenOptionsExt; + let mut f = std::fs::OpenOptions::new() + .create(true) + .truncate(true) + .write(true) + .mode(0o600) + .open(path)?; + f.write_all(contents)?; + f.flush() +} + +#[cfg(not(unix))] +fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> { + std::fs::write(path, contents) +} + +impl AlkaneShell { + fn connect(host: &str, password: Option<&str>) -> Result { + let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?; + let known = temp_path("kh"); + let _ = std::fs::File::create(&known); // empty -> accept-new always accepts + let options = SshOptions { + host: host.to_owned(), + port: 22, + user: "root".to_owned(), + identity_file: None, + password_file: Some(secret.0.clone()), + known_hosts: Some(known), + root_method: crate::transport::RootMethod::Auto, + update_daemon_port: None, + }; + let transport = + SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?; + Ok(AlkaneShell { + transport, + _secret: secret, + }) + } +} + +impl Shell for AlkaneShell { + fn exec(&mut self, cmd: &str) -> Result { + self.transport + .root_command(cmd, Duration::from_secs(120)) + .map(|o| String::from_utf8_lossy(&o).into_owned()) + .map_err(|e| StockError::Method(e.to_string())) + } + fn exec_long(&mut self, cmd: &str) -> Result { + self.transport + .root_command(cmd, Duration::from_secs(900)) + .map(|o| String::from_utf8_lossy(&o).into_owned()) + .map_err(|e| StockError::Method(e.to_string())) + } + fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> { + let tmp = TempFile::with(data, "put")?; + self.transport + .push(&tmp.0, remote_path, Duration::from_secs(900)) + .map_err(|e| StockError::Method(e.to_string())) + } +} + +// --------------------------------------------------------------------------- +// MTD table: map an absolute NAND offset to (device, relative offset) +// --------------------------------------------------------------------------- + +#[derive(Clone, Debug)] +struct Mtd { + dev: String, // e.g. "mtd2" + base: u64, // absolute NAND offset of the partition start + size: u64, + #[allow(dead_code)] + name: String, +} + +/// Read the MTD partition table. Each partition's absolute base comes from +/// `/sys/class/mtd//offset` when present (alkane, where partitions are not +/// contiguous), falling back to the cumulative sum of sizes in `/proc/mtd` +/// order (stock, where they are contiguous from 0). +fn read_mtd_table(sh: &mut dyn Shell) -> Result, StockError> { + // name + size from /proc/mtd (always present); offset from sysfs if present. + let proc = sh.exec("cat /proc/mtd")?; + let mut out = Vec::new(); + let mut cursor = 0u64; + for line in proc.lines() { + let line = line.trim(); + if !line.starts_with("mtd") { + continue; + } + // "mtd0: 02800000 00020000 \"name\"" + let (dev, rest) = match line.split_once(':') { + Some(v) => v, + None => continue, + }; + let mut it = rest.split_whitespace(); + let size = it + .next() + .and_then(|h| u64::from_str_radix(h, 16).ok()) + .ok_or_else(|| StockError::Method(format!("bad /proc/mtd line: {line}")))?; + let _erase = it.next(); + let name = line.split('"').nth(1).unwrap_or("").to_owned(); + let base = match sysfs_offset(sh, dev) { + Some(off) => off, + None => cursor, + }; + cursor = cursor.max(base) + size; + out.push(Mtd { + dev: dev.to_owned(), + base, + size, + name, + }); + } + if out.is_empty() { + return Err(StockError::Method("no MTD partitions found".into())); + } + Ok(out) +} + +fn sysfs_offset(sh: &mut dyn Shell, dev: &str) -> Option { + let out = sh + .exec(&format!("cat /sys/class/mtd/{dev}/offset 2>/dev/null")) + .ok()?; + out.trim().parse::().ok() +} + +/// Find the partition that contains `abs` and holding at least `len` bytes from +/// there; return (device, relative offset). +fn locate(table: &[Mtd], abs: u64, len: u64) -> Result<(&str, u64), StockError> { + for m in table { + if abs >= m.base && abs < m.base + m.size { + let rel = abs - m.base; + if rel + len > m.size { + return Err(StockError::Method(format!( + "write of {len} B at abs 0x{abs:x} overruns {} (rel 0x{rel:x}, size 0x{:x})", + m.dev, m.size + ))); + } + return Ok((&m.dev, rel)); + } + } + Err(StockError::Method(format!( + "no MTD partition exposes absolute offset 0x{abs:x} (is the boot region mapped?)" + ))) +} + +// --------------------------------------------------------------------------- +// NAND primitives +// --------------------------------------------------------------------------- + +/// MD5 of `data` padded with 0xFF up to the next page boundary -- what a +/// `nandwrite -p` of `data` leaves on flash and what `nanddump -l ` +/// reads back. +fn padded_md5(data: &[u8]) -> String { + let rounded = round_up(data.len() as u64, PAGE) as usize; + let mut buf = data.to_vec(); + buf.resize(rounded, 0xFF); + md5_hex(&buf) +} + +/// Write `data` to absolute NAND offset `abs`, staging it in `/tmp/alk`, erasing +/// the covering erase blocks, writing with `nandwrite -p`, and verifying the +/// read-back against the padded MD5. `abs` must be erase-block aligned. +fn write_abs( + sh: &mut dyn Shell, + table: &[Mtd], + abs: u64, + data: &[u8], + label: &str, +) -> Result<(), StockError> { + if abs < BOOTBIN_PRESERVE { + return Err(StockError::Method(format!( + "refusing to write {label} at 0x{abs:x}: inside preserved BOOT.bin" + ))); + } + if !abs.is_multiple_of(ERASE) { + return Err(StockError::Method(format!( + "{label} offset 0x{abs:x} is not erase-block aligned" + ))); + } + let (dev, rel) = locate(table, abs, data.len() as u64)?; + let dev = dev.to_owned(); + let blocks = round_up(data.len() as u64, ERASE) / ERASE; + let remote = format!("/tmp/alk/{label}.img"); + sh.exec("mkdir -p /tmp/alk")?; + sh.put(data, &remote)?; + // Confirm the staged payload arrived intact before we erase anything. + let put_md5 = first_token(&sh.exec(&format!("md5sum {remote}"))?); + if put_md5 != md5_hex(data) { + return Err(StockError::Method(format!( + "{label}: staged copy md5 {put_md5} != {} (transfer corrupted)", + md5_hex(data) + ))); + } + sh.exec_long(&format!( + "flash_erase /dev/{dev} 0x{rel:x} {blocks} >/dev/null 2>&1 && \ + nandwrite -p -s 0x{rel:x} /dev/{dev} {remote} >/dev/null 2>&1 && echo WROTE" + )) + .and_then(|o| { + if o.contains("WROTE") { + Ok(()) + } else { + Err(StockError::Method(format!( + "{label}: erase/write failed: {o}" + ))) + } + })?; + let readlen = round_up(data.len() as u64, PAGE); + let back = first_token(&sh.exec_long(&format!( + "nanddump -s 0x{rel:x} -l {readlen} /dev/{dev} 2>/dev/null | md5sum" + ))?); + let want = padded_md5(data); + if back != want { + return Err(StockError::Method(format!( + "{label}: read-back md5 {back} != {want} at /dev/{dev} rel 0x{rel:x} \ + (write did not persist)" + ))); + } + sh.exec(&format!("rm -f {remote}"))?; + Ok(()) +} + +/// Copy `len` bytes already on NAND from absolute `src` to absolute `dst` +/// (used when carving the on-board stock backup). `dst` must be erase aligned. +fn copy_abs( + sh: &mut dyn Shell, + table: &[Mtd], + src: u64, + dst: u64, + len: u64, + label: &str, +) -> Result<(), StockError> { + let (sdev, srel) = locate(table, src, len)?; + let sdev = sdev.to_owned(); + let (ddev, drel) = locate(table, dst, len)?; + let ddev = ddev.to_owned(); + let blocks = round_up(len, ERASE) / ERASE; + let tmp = format!("/tmp/alk/{label}.bak"); + sh.exec("mkdir -p /tmp/alk")?; + let out = sh.exec_long(&format!( + "nanddump -s 0x{srel:x} -l {len} /dev/{sdev} -f {tmp} >/dev/null 2>&1 && \ + flash_erase /dev/{ddev} 0x{drel:x} {blocks} >/dev/null 2>&1 && \ + nandwrite -p -s 0x{drel:x} /dev/{ddev} {tmp} >/dev/null 2>&1 && \ + rm -f {tmp} && echo COPIED" + ))?; + if !out.contains("COPIED") { + return Err(StockError::Method(format!( + "{label}: backup copy failed: {out}" + ))); + } + Ok(()) +} + +/// Read `len` (even) bytes from NAND at (dev, rel) as raw bytes, via +/// `od -v -x`, which is the only `od` form the stock busybox understands (no +/// `-A`/`-t`). The leading octal address column and trailing byte-count line are +/// discarded by [`parse_od`]. +fn read_small(sh: &mut dyn Shell, dev: &str, rel: u64, len: u64) -> Result, StockError> { + let out = sh.exec(&format!( + "nanddump -s 0x{rel:x} -l {len} /dev/{dev} 2>/dev/null | od -v -x" + ))?; + Ok(parse_od(&out)) +} + +/// Read a big-endian u32 at byte `field_off` within the image whose header +/// starts at the (page-aligned) absolute NAND offset `region_abs`. `nanddump` +/// needs a page-aligned `-s`, so we read the first 64 bytes of the region and +/// slice the field in Rust (used to size the genuine stock images from their +/// uImage / fdt headers before backing up). +fn read_header_u32_be( + sh: &mut dyn Shell, + table: &[Mtd], + region_abs: u64, + field_off: usize, +) -> Result { + let (dev, rel) = locate(table, region_abs, 64)?; + let dev = dev.to_owned(); + let b = read_small(sh, &dev, rel, 64)?; + if b.len() < field_off + 4 { + return Err(StockError::Method(format!( + "short header read at 0x{region_abs:x} ({} bytes)", + b.len() + ))); + } + Ok(u32::from_be_bytes([ + b[field_off], + b[field_off + 1], + b[field_off + 2], + b[field_off + 3], + ])) +} + +fn first_token(s: &str) -> String { + s.split_whitespace().next().unwrap_or("").to_owned() +} + +// --------------------------------------------------------------------------- +// On-board stock backup manifest +// --------------------------------------------------------------------------- + +#[derive(Clone, Debug)] +struct BackupManifest { + kernel_abs: u64, + kernel_len: u64, + dtb_abs: u64, + dtb_len: u64, + rootfs_abs: u64, + rootfs_len: u64, +} + +impl BackupManifest { + fn encode(&self) -> Vec { + let mut v = Vec::with_capacity(64); + v.extend_from_slice(BK_MAGIC); + for n in [ + self.kernel_abs, + self.kernel_len, + self.dtb_abs, + self.dtb_len, + self.rootfs_abs, + self.rootfs_len, + ] { + v.extend_from_slice(&n.to_be_bytes()); + } + v + } + fn decode(b: &[u8]) -> Option { + if b.len() < 8 + 6 * 8 || &b[..8] != BK_MAGIC { + return None; + } + let g = |i: usize| { + let mut a = [0u8; 8]; + a.copy_from_slice(&b[8 + i * 8..8 + i * 8 + 8]); + u64::from_be_bytes(a) + }; + Some(BackupManifest { + kernel_abs: g(0), + kernel_len: g(1), + dtb_abs: g(2), + dtb_len: g(3), + rootfs_abs: g(4), + rootfs_len: g(5), + }) + } +} + +/// Carve the genuine stock kernel + dtb + ramdisk (still on NAND) into the +/// stock-backup region, with a manifest in its first block, so the board can be +/// returned to its own factory stock later with no vendor file. Called on the +/// stock side during a from-stock install, before the boot slots are overwritten. +fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result { + // Size the genuine images from their on-NAND headers (uImage data size at + // header offset 12; fdt totalsize at offset 4). + let kernel_len = 64 + read_header_u32_be(sh, table, OFF_KERNEL, 12)? as u64; + let dtb_len = read_header_u32_be(sh, table, OFF_DTB, 4)? as u64; + let rootfs_len = 64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64; + // Sanity: headers must look like a uImage/fdt, sizes within slots. + if !(64..=SLOT_KERNEL).contains(&kernel_len) || !(64..=SLOT_ROOTFS).contains(&rootfs_len) { + return Err(StockError::Method(format!( + "stock image sizes implausible (kernel {kernel_len}, rootfs {rootfs_len}); \ + refusing to back up" + ))); + } + let k_dst = BK_MANIFEST + ERASE; // images follow the manifest block + let d_dst = k_dst + round_up(kernel_len, ERASE); + let r_dst = d_dst + round_up(dtb_len, ERASE); + if r_dst + round_up(rootfs_len, ERASE) > OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP { + return Err(StockError::Method( + "stock backup does not fit in the 32 MiB backup region".into(), + )); + } + copy_abs(sh, table, OFF_KERNEL, k_dst, kernel_len, "stock-kernel")?; + copy_abs(sh, table, OFF_DTB, d_dst, dtb_len, "stock-dtb")?; + copy_abs(sh, table, OFF_ROOTFS, r_dst, rootfs_len, "stock-rootfs")?; + let manifest = BackupManifest { + kernel_abs: k_dst, + kernel_len, + dtb_abs: d_dst, + dtb_len, + rootfs_abs: r_dst, + rootfs_len, + }; + write_abs( + sh, + table, + BK_MANIFEST, + &manifest.encode(), + "stock-backup-manifest", + )?; + Ok(manifest) +} + +/// Read and validate the on-board backup manifest, if present. +fn read_backup_manifest( + sh: &mut dyn Shell, + table: &[Mtd], +) -> Result, StockError> { + let (dev, rel) = match locate(table, BK_MANIFEST, 64) { + Ok(v) => v, + Err(_) => return Ok(None), // region not mapped -> treat as absent + }; + let dev = dev.to_owned(); + // Pull the 64-byte manifest off NAND via `od -v -x` (busybox-safe) and parse. + let bytes = read_small(sh, &dev, rel, 64)?; + Ok(BackupManifest::decode(&bytes)) +} + +/// Parse `od` hex output into bytes. Accepts both `-tx1` (byte hex) and `-x` +/// (little-endian 16-bit words). +fn parse_od(s: &str) -> Vec { + let toks: Vec<&str> = s.split_whitespace().collect(); + // Heuristic: 2-char tokens are bytes (-tx1); 4-char tokens are LE words (-x). + let mut out = Vec::new(); + for t in &toks { + match t.len() { + 2 => { + if let Ok(b) = u8::from_str_radix(t, 16) { + out.push(b); + } + } + 4 => { + if let Ok(w) = u16::from_str_radix(t, 16) { + out.push((w & 0xff) as u8); + out.push((w >> 8) as u8); + } + } + _ => {} + } + } + out +} + +// --------------------------------------------------------------------------- +// Operations +// --------------------------------------------------------------------------- + +/// What to write to the three boot slots (already in the exact on-NAND form: +/// kernel and rootfs as legacy uImages, dtb as a raw fdt). +struct BootImages { + kernel_uimage: Vec, + dtb: Vec, + rootfs_uimage: Vec, +} + +fn write_boot_slots(sh: &mut dyn Shell, table: &[Mtd], img: &BootImages) -> Result<(), StockError> { + // rootfs, dtb, kernel order: an interrupted run never leaves a new rootfs + // under an old kernel. + if img.rootfs_uimage.len() as u64 > SLOT_ROOTFS { + return Err(StockError::Method("rootfs over slot ceiling".into())); + } + if img.dtb.len() as u64 > SLOT_DTB { + return Err(StockError::Method("dtb over slot ceiling".into())); + } + if img.kernel_uimage.len() as u64 > SLOT_KERNEL { + return Err(StockError::Method("kernel over slot ceiling".into())); + } + write_abs(sh, table, OFF_ROOTFS, &img.rootfs_uimage, "rootfs")?; + write_abs(sh, table, OFF_DTB, &img.dtb, "dtb")?; + write_abs(sh, table, OFF_KERNEL, &img.kernel_uimage, "kernel")?; + Ok(()) +} + +/// Whether the connected board is a Zynq, so the readable boot-slot path +/// applies. Other boards fall back to the compiled-in method. +fn shell_is_zynq(sh: &mut dyn Shell) -> bool { + sh.exec( + "(grep -qi zynq /proc/cpuinfo 2>/dev/null || \ + grep -qai zynq /proc/device-tree/compatible 2>/dev/null) && echo yes || true", + ) + .map(|o| o.contains("yes")) + .unwrap_or(false) +} + +fn reboot(sh: &mut dyn Shell) { + // Best-effort: the reboot drops the shell, so ignore the result. + let _ = sh.exec("sync; (sleep 1; reboot) >/dev/null 2>&1 &"); +} + +/// Install alkane onto a board currently on stock, over the network. The afw +/// ships a raw `zImage`, a raw fdt and a gzipped cpio rootfs; we wrap the kernel +/// and rootfs as the legacy uImages the preserved stock U-Boot boots, carve the +/// genuine stock backup first, then write the boot slots and reboot. +pub fn install_from_stock( + host: &str, + kernel_zimage: &[u8], + dtb: &[u8], + rootfs_cpio_gz: &[u8], + password: Option<&str>, +) -> Result<(), StockError> { + let mut sh = StockShell { + host: host.to_owned(), + password: password.map(str::to_owned), + }; + if first_token(&sh.exec("id -u")?) != "0" { + return Err(StockError::Auth( + "did not obtain root on the stock board".into(), + )); + } + let table = read_mtd_table(&mut sh)?; + // Carve the genuine-stock backup from the live stock NAND before any write. + carve_backup(&mut sh, &table)?; + let img = BootImages { + kernel_uimage: uimage::wrap(Kind::Kernel, kernel_zimage, 0, "alkane-kernel"), + dtb: dtb.to_vec(), + rootfs_uimage: uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, 0, "alkane-rootfs"), + }; + write_boot_slots(&mut sh, &table, &img)?; + reboot(&mut sh); + Ok(()) +} + +/// Return an alkane board to genuine stock by writing the vendor images back to +/// the boot slots over SSH. `dtb` is the genuine per-board device tree (from the +/// vendor package); if `None`, the stock dtb saved in the on-board backup is +/// used. `kernel`/`rootfs` are the vendor legacy uImages, written as-is. +pub fn restore_to_stock( + host: &str, + kernel_uimage: &[u8], + rootfs_uimage: &[u8], + dtb: Option<&[u8]>, + password: Option<&str>, +) -> Result<(), StockError> { + let mut sh = AlkaneShell::connect(host, password)?; + if !shell_is_zynq(&mut sh) { + return Err(StockError::NotApplicable); + } + let table = read_mtd_table(&mut sh)?; + if rootfs_uimage.len() as u64 > SLOT_ROOTFS || kernel_uimage.len() as u64 > SLOT_KERNEL { + return Err(StockError::Method("vendor image over slot ceiling".into())); + } + // rootfs, dtb, kernel order (same safety ordering as install). + write_abs(&mut sh, &table, OFF_ROOTFS, rootfs_uimage, "rootfs")?; + match dtb { + Some(d) => { + if d.len() as u64 > SLOT_DTB { + return Err(StockError::Method("dtb over slot ceiling".into())); + } + write_abs(&mut sh, &table, OFF_DTB, d, "dtb")?; + } + None => { + // No vendor dtb (an OTA package omits it): restore the genuine + // per-board dtb from the on-board backup by copying within NAND. + let manifest = read_backup_manifest(&mut sh, &table)?.ok_or_else(|| { + StockError::Method( + "no stock dtb supplied and no on-board backup to take one from".into(), + ) + })?; + copy_abs( + &mut sh, + &table, + manifest.dtb_abs, + OFF_DTB, + manifest.dtb_len, + "dtb", + )?; + } + } + write_abs(&mut sh, &table, OFF_KERNEL, kernel_uimage, "kernel")?; + reboot(&mut sh); + Ok(()) +} + +/// Whether the board holds a complete, restorable on-board stock backup. +pub fn onboard_backup_present(host: &str, password: Option<&str>) -> Result { + let mut sh = AlkaneShell::connect(host, password)?; + if !shell_is_zynq(&mut sh) { + return Err(StockError::NotApplicable); + } + let table = read_mtd_table(&mut sh)?; + Ok(read_backup_manifest(&mut sh, &table)?.is_some()) +} + +/// Return an alkane board to stock using only the on-board backup (no vendor +/// file): copy the saved stock kernel, dtb and rootfs back to the boot slots. +pub fn restore_from_onboard(host: &str, password: Option<&str>) -> Result<(), StockError> { + let mut sh = AlkaneShell::connect(host, password)?; + if !shell_is_zynq(&mut sh) { + return Err(StockError::NotApplicable); + } + let table = read_mtd_table(&mut sh)?; + let manifest = read_backup_manifest(&mut sh, &table)? + .ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))?; + // Copy within NAND: backup region -> boot slots. + copy_abs( + &mut sh, + &table, + manifest.rootfs_abs, + OFF_ROOTFS, + manifest.rootfs_len, + "rootfs", + )?; + copy_abs( + &mut sh, + &table, + manifest.dtb_abs, + OFF_DTB, + manifest.dtb_len, + "dtb", + )?; + copy_abs( + &mut sh, + &table, + manifest.kernel_abs, + OFF_KERNEL, + manifest.kernel_len, + "kernel", + )?; + reboot(&mut sh); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_up_works() { + assert_eq!(round_up(1, PAGE), PAGE); + assert_eq!(round_up(PAGE, PAGE), PAGE); + assert_eq!(round_up(PAGE + 1, PAGE), 2 * PAGE); + assert_eq!(round_up(0, ERASE), 0); + } + + #[test] + fn padded_md5_matches_manual_pad() { + let data = b"hello"; + let mut padded = data.to_vec(); + padded.resize(PAGE as usize, 0xFF); + assert_eq!(padded_md5(data), md5_hex(&padded)); + } + + #[test] + fn manifest_roundtrips() { + let m = BackupManifest { + kernel_abs: 0x6020000, + kernel_len: 4006832, + dtb_abs: 0x6420000, + dtb_len: 7650, + rootfs_abs: 0x6440000, + rootfs_len: 26620582, + }; + let enc = m.encode(); + let dec = BackupManifest::decode(&enc).unwrap(); + assert_eq!(dec.kernel_abs, m.kernel_abs); + assert_eq!(dec.rootfs_len, m.rootfs_len); + assert!(BackupManifest::decode(b"nope").is_none()); + } + + #[test] + fn locate_maps_absolute_to_partition() { + let table = vec![ + Mtd { + dev: "mtd0".into(), + base: 0x0, + size: 0x2800000, + name: "x".into(), + }, + Mtd { + dev: "mtd1".into(), + base: 0x2800000, + size: 0x2000000, + name: "y".into(), + }, + ]; + assert_eq!(locate(&table, 0x2000000, 100).unwrap(), ("mtd0", 0x2000000)); + assert_eq!(locate(&table, 0x2800000, 100).unwrap(), ("mtd1", 0)); + assert!(locate(&table, 0x9000000, 1).is_err()); + } + + #[test] + fn parse_od_both_forms() { + // -tx1 byte form + assert_eq!(parse_od("41 42 43"), vec![0x41, 0x42, 0x43]); + // -x little-endian word form -> bytes + assert_eq!(parse_od("4241"), vec![0x41, 0x42]); + } +} diff --git a/crates/alkane-gui/src/credentials.rs b/crates/alkane-gui/src/credentials.rs index 99803c41..f0a6fe51 100644 --- a/crates/alkane-gui/src/credentials.rs +++ b/crates/alkane-gui/src/credentials.rs @@ -106,6 +106,9 @@ pub fn clear_credentials() -> std::io::Result<()> { /// duplicated here; a firmware absent from this table defaults to blank. pub fn firmware_default_creds() -> &'static [(&'static str, &'static str, &'static str)] { &[ + // Alkane OS ships with this control-board login, so restore-to-stock on + // an alkane board authenticates with no operator setup (issue #51). + ("Alkane", "root", "alkane"), ("AntMiner Stock", "root", "root"), ("WhatsMiner Stock", "admin", "admin"), ("Braiins", "root", "root"), @@ -134,6 +137,18 @@ pub fn firmware_default_for(name: &str) -> (String, String) { .unwrap_or_default() } +/// The login to use for a board running `firmware`: the operator's saved +/// per-firmware override if any, else the shipped default. This is how install +/// (a stock target) and restore (an alkane target) each pick the right login +/// automatically, without a password field in the dialog (issues #46, #51). +pub fn cred_for(firmware: &str) -> (String, String) { + load_firmware_credentials() + .get(firmware) + .cloned() + .filter(|(_, p)| !p.is_empty()) + .unwrap_or_else(|| firmware_default_for(firmware)) +} + /// Load the operator's per-firmware credential overrides, keyed by firmware /// Display name. Malformed lines are skipped. pub fn load_firmware_credentials() -> HashMap { diff --git a/crates/alkane-gui/src/model.rs b/crates/alkane-gui/src/model.rs index 49157790..a87f9052 100644 --- a/crates/alkane-gui/src/model.rs +++ b/crates/alkane-gui/src/model.rs @@ -692,9 +692,18 @@ impl MinerRow { /// live); grey (unknown) otherwise -- asic-rs has no direct PSU-fault flag, so /// a missing wattage reading is treated as unknown, never a false "down". pub fn power_health(&self) -> CompHealth { - // A miner drawing power / spinning its PSU fan / actively mining has a live - // PSU regardless of any warning flag. - let delivering = self.power_w > 0.0 || self.psu_fan_rpm > 0.0 || self.is_mining; + // A live PSU shows real evidence: measured draw, a spinning PSU fan, or + // reported PSU output. A stock control board can assert a cgminer "mining" + // status with no PSU and no hashboards attached (issue #39: a bare S17 + // control board showed a green PSU), so is_mining counts only when the + // miner is actually hashing (hashrate, or at least one healthy board). + let actually_hashing = + self.hashrate_ths > 0.0 || self.board_status.contains(&BoardHealth::Ok); + let delivering = self.power_w > 0.0 + || self.psu_fan_rpm > 0.0 + || self.psu_out_voltage_v.is_some() + || self.psu_out_current_a.is_some() + || (self.is_mining && actually_hashing); // A reported PSU fault while the miner is actually mining is a warning, not // a failure -- yellow, not red (round 18 #2: some WhatsMiners flag a PSU // error while running fine). A fault on a miner that is not mining is a real @@ -2476,6 +2485,52 @@ mod tests { ); } + #[test] + fn stock_board_with_nothing_attached_shows_grey_psu() { + // Issue #39: a stock S17 control board with no PSU and no hashboards + // attached asserts a cgminer "mining" status (is_mining = true) while + // reporting zero watts, no PSU fan, and no PSU output. That is not + // evidence of a live PSU, so the bolt must read grey (Unreachable). + let bare = MinerRow { + is_mining: true, + power_w: 0.0, + psu_fan_rpm: 0.0, + hashrate_ths: 0.0, + board_status: vec![BoardHealth::Missing, BoardHealth::Missing], + ..Default::default() + }; + assert_eq!(bare.power_health(), CompHealth::Unreachable); + + // A genuinely-running miner still greens: is_mining with real hashing is + // evidence enough even when the firmware reports no watts. + let hashing = MinerRow { + is_mining: true, + power_w: 0.0, + psu_fan_rpm: 0.0, + hashrate_ths: 90.0, + board_status: vec![BoardHealth::Ok, BoardHealth::Ok], + ..Default::default() + }; + assert_eq!(hashing.power_health(), CompHealth::Ok); + + // Measured draw alone is always enough. + let drawing = MinerRow { + is_mining: false, + power_w: 19.0, + ..Default::default() + }; + assert_eq!(drawing.power_health(), CompHealth::Ok); + + // Reported PSU output alone is enough even with zero measured watts. + let psu_out = MinerRow { + is_mining: false, + power_w: 0.0, + psu_out_voltage_v: Some(12.0), + ..Default::default() + }; + assert_eq!(psu_out.power_health(), CompHealth::Ok); + } + #[test] fn warning_fault_degrades_board_to_yellow_not_red() { // Round 21 #1: a board still mining near full hashrate with some failed/ diff --git a/crates/alkane-gui/src/scan.rs b/crates/alkane-gui/src/scan.rs index 352786a3..c4e06f5e 100644 --- a/crates/alkane-gui/src/scan.rs +++ b/crates/alkane-gui/src/scan.rs @@ -674,6 +674,62 @@ fn messages_to_faults( .collect() } +/// A hashboard's health dot from its reported activity. `active` is the firmware's +/// active flag; `working_chips` its working-chip count. Green needs positive +/// evidence (active, or a nonzero chip count); a board with neither flag nor count +/// reads grey ("not detected") rather than green (issue #39: an S17 control board +/// with no hashboards attached showed its boards green). A board that is present +/// but idle or has zero working chips reads as a fault (red). +fn board_health( + active: Option, + working_chips: Option, + miner_active: bool, +) -> crate::model::BoardHealth { + use crate::model::BoardHealth; + match (active, working_chips) { + (Some(true), _) => BoardHealth::Ok, + (Some(false), _) => BoardHealth::Fault, + (None, Some(c)) if c > 0 => BoardHealth::Ok, + (None, Some(_)) => BoardHealth::Fault, + // No per-board evidence. If the miner shows overall activity (hashing), + // the board is clearly present and working -> green; only an idle miner + // with no board telemetry reads grey (issue #39: bare S17; review #3: do + // not grey a genuinely-mining miner whose backend omits per-board fields). + (None, None) => { + if miner_active { + BoardHealth::Ok + } else { + BoardHealth::Missing + } + } + } +} + +#[cfg(test)] +mod board_health_tests { + use super::board_health; + use crate::model::BoardHealth; + + #[test] + fn no_activity_evidence_reads_grey_not_green() { + // Issue #39: the firmware lists a board but reports no active flag and no + // working-chip count -> not detected (grey), not green. + // Idle miner, no per-board evidence -> not detected (grey). + assert_eq!(board_health(None, None, false), BoardHealth::Missing); + // Mining miner, no per-board evidence -> still green (review #3). + assert_eq!(board_health(None, None, true), BoardHealth::Ok); + // Positive evidence still greens regardless of miner activity. + assert_eq!(board_health(Some(true), None, false), BoardHealth::Ok); + assert_eq!(board_health(None, Some(63), false), BoardHealth::Ok); + // Present but idle / zero working chips -> fault (red). + assert_eq!( + board_health(Some(false), Some(63), false), + BoardHealth::Fault + ); + assert_eq!(board_health(None, Some(0), false), BoardHealth::Fault); + } +} + #[cfg(test)] mod board_index_tests { use super::board_index_from_text; @@ -1189,18 +1245,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow { let mut board_status: Vec = data .hashboards .iter() - .map(|b| { - let ok = match (b.active, b.working_chips) { - (Some(a), _) => a, - (None, Some(c)) => c > 0, - (None, None) => true, - }; - if ok { - crate::model::BoardHealth::Ok - } else { - crate::model::BoardHealth::Fault - } - }) + .map(|b| board_health(b.active, b.working_chips, is_mining || hashrate_ths > 0.0)) .collect(); if let Some(exp) = data.expected_hashboards { while board_status.len() < exp as usize { diff --git a/crates/alkane-gui/src/stock_ops.rs b/crates/alkane-gui/src/stock_ops.rs index 69a53d6d..abb37cd7 100644 --- a/crates/alkane-gui/src/stock_ops.rs +++ b/crates/alkane-gui/src/stock_ops.rs @@ -34,12 +34,26 @@ pub fn is_supported_board(board: &str) -> bool { SUPPORTED_BOARDS.iter().any(|(b, _)| *b == board) } -/// The release asset to install: its filename and download URL, resolved to a -/// local path on the worker thread so the download never blocks the UI. (Local- -/// file install is a CLI feature; the GUI installs from scanned releases.) -pub struct AfwChoice { - pub name: String, - pub url: String, +/// Where the `.afw` to install comes from. `Release` is a scanned Gitea asset +/// (its filename and download URL), fetched on the worker thread so the download +/// never blocks the UI. `Local` is a file the operator picked with the Browse +/// button -- the same local-file install the CLI offers, now in the GUI too. +pub enum AfwSource { + Release { name: String, url: String }, + Local(PathBuf), +} + +impl AfwSource { + /// A short human label for the status line (the filename in both cases). + fn label(&self) -> String { + match self { + AfwSource::Release { name, .. } => name.clone(), + AfwSource::Local(p) => p + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| p.to_string_lossy().into_owned()), + } + } } /// Progress + results streamed from the background worker to the UI. @@ -81,9 +95,10 @@ fn download_dir() -> PathBuf { pub fn start_install( ips: Vec, board: String, - source: AfwChoice, + source: AfwSource, allow_unsigned: bool, password: Option, + is_update: bool, ) -> StockHandle { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); @@ -111,26 +126,49 @@ pub fn start_install( .spawn(move || { let _ = tx.send(StockMsg::Started); - // 1. Download the chosen release asset (on this worker thread). - let _ = tx.send(StockMsg::Progress("acquiring .afw...".into())); - let afw_path = match fetch::fetch_afw_url( - &ReleaseSource::alkane_os(), - &source.name, - &source.url, - &download_dir(), - ) { - Ok(p) => p, - Err(e) => { - // One failure line per target so the UI clears its op-status. - for ip in &ips { - let _ = tx.send(StockMsg::Result { - ip: ip.clone(), - ok: false, - detail: format!("could not fetch .afw: {e}"), - }); + // 1. Acquire the .afw: a local file is used in place; a release asset + // is downloaded on this worker thread (never blocking the UI). + let afw_path = match source { + AfwSource::Local(path) => { + let _ = tx.send(StockMsg::Progress(format!( + "using local {}...", + AfwSource::Local(path.clone()).label() + ))); + if !path.is_file() { + for ip in &ips { + let _ = tx.send(StockMsg::Result { + ip: ip.clone(), + ok: false, + detail: format!("local .afw not found: {}", path.display()), + }); + } + let _ = tx.send(StockMsg::Done); + return; + } + path + } + AfwSource::Release { name, url } => { + let _ = tx.send(StockMsg::Progress("acquiring .afw...".into())); + match fetch::fetch_afw_url( + &ReleaseSource::alkane_os(), + &name, + &url, + &download_dir(), + ) { + Ok(p) => p, + Err(e) => { + // One failure line per target so the UI clears its op-status. + for ip in &ips { + let _ = tx.send(StockMsg::Result { + ip: ip.clone(), + ok: false, + detail: format!("could not fetch .afw: {e}"), + }); + } + let _ = tx.send(StockMsg::Done); + return; + } } - let _ = tx.send(StockMsg::Done); - return; } }; @@ -170,6 +208,22 @@ pub fn start_install( let _ = tx.send(StockMsg::Done); return; } + // An in-place Update must never rewrite the bootloader (review #1): + // refuse a tier-3 (bootloader-writing) bundle so the "BOOT.bin is + // never written" guarantee holds for an already-alkane board. + if is_update && verified.manifest.flash_plan().writes_uboot { + for ip in &ips { + let _ = tx.send(StockMsg::Result { + ip: ip.clone(), + ok: false, + detail: "update refused: this release reflashes the bootloader (tier 3); \ + pick a tier-1/2 release or use Install" + .to_string(), + }); + } + let _ = tx.send(StockMsg::Done); + return; + } // 3. Install onto each board via the network-only from-stock method. for ip in ips { @@ -220,6 +274,7 @@ fn restore_one(ip: &str, firmware: &Path, password: Option<&str>) -> (bool, Stri let images = RestoreImages { kernel: &fw.kernel, rootfs: &fw.rootfs, + dtb: fw.dtb.as_deref(), }; match stock::restore_to_stock(ip, &images, password) { Ok(()) => ( @@ -282,3 +337,74 @@ pub fn start_restore(ips: Vec, firmware: PathBuf, password: Option) -> bool { + if fake_scan_enabled() { + return true; + } + stock::onboard_stock_backup_present(ip, password).unwrap_or(false) +} + +/// Restore the given alkane boards to genuine stock, over the network, from each +/// board's own on-board stock backup (no vendor firmware file). `password`, if +/// set, is the board's alkane root credential. +pub fn start_restore_onboard(ips: Vec, password: Option) -> StockHandle { + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + + if fake_scan_enabled() { + let _ = tx.send(StockMsg::Started); + for ip in ips { + let _ = tx.send(StockMsg::Result { + ip, + ok: true, + detail: "restored to stock from on-board backup (demo)".into(), + }); + } + let _ = tx.send(StockMsg::Done); + return StockHandle { rx, cancel }; + } + + let tc = cancel.clone(); + let err_tx = tx.clone(); + let spawned = std::thread::Builder::new() + .name("restore-onboard".into()) + .spawn(move || { + let _ = tx.send(StockMsg::Started); + let timeout = std::time::Duration::from_secs(300); + for ip in ips { + if tc.load(Ordering::Relaxed) { + break; + } + let _ = tx.send(StockMsg::Progress(format!( + "restoring {ip} to stock from its on-board backup..." + ))); + let (ok, detail) = + match stock::restore_from_onboard_backup(&ip, password.as_deref(), timeout) { + Ok(()) => ( + true, + "restored to stock from on-board backup (verify over the network)" + .to_string(), + ), + Err(e) => (false, format!("restore failed: {e}")), + }; + if tx.send(StockMsg::Result { ip, ok, detail }).is_err() { + return; + } + } + 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 restore worker thread".into(), + }); + let _ = err_tx.send(StockMsg::Done); + } + StockHandle { rx, cancel } +} diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index a38750dd..2de48f3a 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -6,7 +6,7 @@ use crate::credentials; use crate::model::*; use crate::restore; use crate::scan::{self, ScanMsg}; -use crate::stock_ops::{self, AfwChoice, StockMsg}; +use crate::stock_ops::{self, AfwSource, StockMsg}; use alkane_artifacts::fetch::{self, ReleaseInfo, ReleaseSource}; use asic_rs::core::data::firmware::FirmwareImage; use std::cell::RefCell; @@ -108,8 +108,16 @@ const ID_CTX_UPDATE_ALKANE: i32 = 772; const ID_INSTALL_OK: i32 = 1006; const ID_INSTALL_CANCEL: i32 = 1007; const ID_INSTALL_RELEASE_CHOICE: i32 = 1008; +// Browse for a local .afw to install instead of a scanned Gitea release. +const ID_INSTALL_BROWSE: i32 = 1011; +// Reload the release picker from the repo typed in the install dialog. +const ID_INSTALL_RELOAD: i32 = 1012; +// Toolbar toggle between the fleet table and the live activity-log view. +const ID_LOG_TOGGLE: i32 = 1013; const ID_UNINSTALL_OK: i32 = 1009; const ID_UNINSTALL_CANCEL: i32 = 1010; +// Browse for a stock firmware file in the uninstall/restore dialog. +const ID_UNINSTALL_BROWSE: i32 = 1014; // Pool-preset manager dialog (round 18 #8b): edit the whole saved list at once. // NB: 790-795 belong to the language menu (ID_LANG_BASE + Lang index), so these // live in a separate high block to avoid an id collision (round 18 #12). @@ -510,6 +518,64 @@ fn encode_status_icon(pal: &Palette, status: &str) -> String { encode_segments(&[(Some(status_kind_color(pal, status)), shape.to_string())]) } +/// An indicative percent for an install/restore phase line, so the Health cell +/// can show a progress bar instead of a static "installing...". Phase-based (the +/// engine streams named phases, not a true byte count), monotonic within a run. +fn stock_progress_pct(msg: &str) -> u8 { + let m = msg.to_ascii_lowercase(); + if m.contains("acquir") || m.contains("using local") { + 15 + } else if m.contains("verify") { + 35 + } else if m.contains("install") || m.contains("restor") || m.contains("writ") { + 70 + } else { + 50 + } +} + +/// A fixed-width ASCII progress bar, e.g. "[######----]", for a 0..=100 percent. +fn ascii_bar(pct: u8) -> String { + let width = 10usize; + let filled = (pct as usize * width / 100).min(width); + 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) { @@ -773,6 +839,12 @@ pub struct App { // rather than render against stale columns (round 18 #12). built_columns: Vec, table_parent: Widget, + // Live log view: a multiline control that fills the table area when toggled + // on, showing the toolkit activity log. The toggle button flips its label. + log_view: Widget, + log_toggle_btn: Widget, + showing_log: bool, + log_shown_len: usize, root_sizer: Widget, pub scan: Option, pub scanning: bool, @@ -840,6 +912,19 @@ pub struct App { // operation running (refresh, config action, light, firmware, restore, access // check), its Health cell shows this text instead of the component icons. op_status: std::collections::HashMap, + // IPs of the install currently in flight, so a successful install can arm a + // post-install alkane verification for exactly those boards. + install_targets: HashSet, + // Ticks (1 s each) until the next post-install alkane re-probe, so boards are + // verified on a fixed cadence even when auto-scan is off (review #2). + verify_cooldown: u16, + // After a successful install a board reboots into alkane; the next scan can + // still catch it mid-reboot answering as stock. Each awaited IP maps to the + // number of scan rounds left to confirm alkane before giving up; while an IP + // waits, a non-alkane row for it is suppressed so the table never flickers to + // stock (the operator sees "verifying alkane..." instead). Issue: post-install + // the row re-scanned as stock before finally showing alkane. + installed_awaiting: HashMap, // A confirmation dialog for disruptive actions, plus its pending target. confirm_dialog: Widget, pending_confirm: Option<(Vec, scan::ConfigAction)>, @@ -890,6 +975,9 @@ pub struct App { report_text: Widget, report_log: Widget, report_status: Widget, + // After a report is filed this button becomes the clickable "issue #N" link; + // hidden until then (issue #50: no always-present Open-issue button). + report_open_btn: Widget, report_rx: Option>>, report_url: Option, // Restore-to-stock (round 12 #8a): background job + its typed-confirm dialog. @@ -902,16 +990,31 @@ pub struct App { stock_op: Option, install_dialog: Widget, install_release_choice: Widget, - install_pass_input: Widget, install_unsigned_check: Widget, - install_confirm_input: Widget, install_releases: Vec, install_ips: Vec, install_board: String, + // True when the open install dialog is an in-place Update (an already-alkane + // board) rather than a from-stock install: the worker then refuses a + // bootloader-writing (tier-3) bundle so "BOOT.bin is never written" holds + // (review #1). + install_is_update: bool, + // A local .afw picked with the Browse button, used in place of a Gitea + // release when set; the read-only label beside the button shows it. + install_local_path: Option, + 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, uninstall_dialog: Widget, - uninstall_pass_input: Widget, uninstall_firmware_input: Widget, - uninstall_confirm_input: Widget, + // Restore-to-stock source: the board's on-board stock backup (checkbox, + // greyed when absent) vs the firmware file below. + uninstall_onboard_check: Widget, + uninstall_onboard_available: bool, uninstall_ips: Vec, // Configure-pools dialog (round 14 #7, expanded round 15 #1): 3 pool rows x 4 // fields (address, account, worker, password) = 12 text controls, indexed @@ -1154,6 +1257,8 @@ pub fn build(frame: Widget) -> App { 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); 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). @@ -1187,6 +1292,13 @@ pub fn build(frame: Widget) -> App { // The table is created in rebuild_table and added to `root` there. let table_parent = panel; + // Live activity-log view: fills the table area when toggled on (hidden until + // then). Added before the table in the sizer; whichever is shown takes the + // space while the other is hidden to zero. + let log_view = Widget::text_ctrl(panel, true); + root.add(log_view, 1, sf::EXPAND | sf::BORDER_ALL, 4); + log_view.show(false); + root.set_sizer_on(panel); // Collapse the two wide KPI cards when the window is too narrow to fit all // seven (round 11 #2): listen for panel resizes. @@ -1227,6 +1339,10 @@ pub fn build(frame: Widget) -> App { rows_dirty: false, built_columns: Vec::new(), table_parent, + log_view, + log_toggle_btn, + showing_log: false, + log_shown_len: 0, root_sizer: root, scan: Some(scan::start_scan(ranges.clone(), scan::load_scan_timeout())), scanning: true, @@ -1259,6 +1375,9 @@ pub fn build(frame: Widget) -> App { action_targets: Vec::new(), pending_password_update: None, op_status: std::collections::HashMap::new(), + install_targets: HashSet::new(), + verify_cooldown: 0, + installed_awaiting: HashMap::new(), confirm_dialog: frame, pending_confirm: None, flash_confirm_dialog: frame, @@ -1282,6 +1401,7 @@ pub fn build(frame: Widget) -> App { report_text: frame, report_log: frame, report_status: frame, + report_open_btn: frame, report_rx: None, report_url: None, restore: None, @@ -1290,16 +1410,19 @@ pub fn build(frame: Widget) -> App { stock_op: None, install_dialog: frame, install_release_choice: frame, - install_pass_input: frame, install_unsigned_check: frame, - install_confirm_input: frame, install_releases: Vec::new(), install_ips: Vec::new(), install_board: stock_ops::DEFAULT_BOARD.to_string(), + install_is_update: false, + install_local_path: None, + install_local_label: frame, + install_plan_label: frame, + install_repo_input: frame, uninstall_dialog: frame, - uninstall_pass_input: frame, uninstall_firmware_input: frame, - uninstall_confirm_input: frame, + uninstall_onboard_check: frame, + uninstall_onboard_available: false, uninstall_ips: Vec::new(), pools_dialog: frame, pool_fields: Vec::new(), @@ -1468,6 +1591,11 @@ impl App { // the KPI + controls rows) and re-run the panel's layout so it is // positioned, not left floating at (0,0). self.root_sizer.add(t, 1, sf::EXPAND | sf::BORDER_ALL, 4); + // Keep the table hidden if the log view is currently showing (a rebuild + // would otherwise re-reveal it). + if self.showing_log { + t.show(false); + } self.table = Some(t); self.table_parent.layout(); // Re-apply the table zoom so a non-100% zoom survives this rebuild @@ -1896,7 +2024,7 @@ impl App { // place); // - 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 and a typed FLASH confirmation. + // engine still gates on compatibility. let supported = selected.iter().all(|r| alkane_detect::install_supported(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)); @@ -2609,22 +2737,101 @@ impl App { /// True when any hardware-touching job is in flight. A new install/uninstall /// must not start while a scan, config action, refresh, flash, restore, or /// another stock op is running (they would race on the same boards). - fn hardware_busy(&self) -> bool { + /// True when a flash/restore-level operation is in flight (ignores an + /// in-flight scan, which an install/uninstall + /// dialog may be opened and prepared while a scan runs (issue #43). The scan + /// is stopped by `stop_scan_for_op` only when the operation actually starts. + fn flash_busy(&self) -> bool { self.flashing - || self.scanning || self.action.is_some() || self.refresh.is_some() || self.restore.is_some() || self.stock_op.is_some() } + /// Cancel any in-flight scan before a flash/restore starts, so the two never + /// probe/write the same board at once (issue #43). + fn stop_scan_for_op(&mut self) { + if self.scanning || self.scan.is_some() { + self.playing = false; + self.scan_stopped = true; + self.countdown = 0; + self.scanning = false; + if let Some(old) = self.scan.take() { + old.stop(); + } + wx_rs::set_status_text("scan stopped for the flash operation"); + } + } + /// Build the "Install alkane OS" dialog (or, with `update`, the "Update /// alkane OS" dialog for boards already running it): a scanned list of /// alkane-os releases to pick from, an optional board credential, the - /// allow-unsigned (bench) toggle, and a typed FLASH confirmation. The install - /// runs over the network via the toolkit's own compiled-in from-stock engine. + /// allow-unsigned (bench) toggle. The install runs over the network via the + /// toolkit's own compiled-in from-stock engine. + /// Scan `owner/repo`'s releases and fill the install picker with the ones + /// 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) { + 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() + } + }; + 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})" + )); + } else { + for (i, r) in self.install_releases.iter().enumerate() { + let tag = if r.tag.is_empty() { + r.name.as_str() + } else { + r.tag.as_str() + }; + let kind = if r.prerelease { " [pre-release]" } else { "" }; + let latest = if i == 0 { " (latest)" } else { "" }; + let date = r.published_at.split('T').next().unwrap_or(""); + choice.choice_append(&format!("{tag}{kind} {date}{latest}")); + } + choice.choice_set_selection(0); + } + wx_rs::set_status_text(&format!( + "{} release(s) for {board} in {owner}/{repo}", + 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). + 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); + } + self.install_dialog.layout(); + } + fn build_install_dialog(&mut self, update: bool) -> Option { - if self.hardware_busy() { + if self.flash_busy() { wx_rs::set_status_text("busy -- try again once the current operation finishes"); return None; } @@ -2633,24 +2840,24 @@ impl App { wx_rs::set_status_text("select a board to install onto"); return None; } - let board = self.install_board.clone(); + // Target board family comes from the selected board(s), not a fixed + // default (review #7). Install/Update is only offered when every selected + // board is install-supported, so their board_family is consistent; fall + // back to the default only if none resolves. + let board = self + .selected_rows() + .into_iter() + .find_map(crate::alkane_detect::board_family) + .unwrap_or_else(|| stock_ops::DEFAULT_BOARD.to_string()); + self.install_board = board.clone(); + self.install_is_update = update; - // Scan alkane-os releases from Gitea (newest first), keeping those that - // carry an .afw for this board. One quick API call, done synchronously so - // the picker is populated when the dialog opens. - wx_rs::set_status_text("scanning alkane-os releases..."); - let releases: Vec = match fetch::list_releases(&ReleaseSource::alkane_os()) { - Ok(list) => list - .into_iter() - .filter(|r| !r.draft && r.asset_for_board(&board).is_some()) - .collect(), - Err(e) => { - wx_rs::set_status_text(&format!("could not list releases: {e}")); - Vec::new() - } - }; - self.install_releases = releases; + // Releases are scanned after the picker widget exists, from the repo in + // the repo field (default blueflare/alkane-os); see + // populate_install_releases, which the Reload button also calls. + self.install_releases = Vec::new(); self.install_ips = ips.clone(); + self.install_local_path = None; let frame = Widget::main_frame(); let title = if update { @@ -2700,22 +2907,6 @@ impl App { 12, ); let choice = Widget::choice(dlg, ID_INSTALL_RELEASE_CHOICE); - if self.install_releases.is_empty() { - choice.choice_append("(no release with an .afw for this board was found)"); - } else { - for (i, r) in self.install_releases.iter().enumerate() { - let tag = if r.tag.is_empty() { - r.name.as_str() - } else { - r.tag.as_str() - }; - let kind = if r.prerelease { " [pre-release]" } else { "" }; - let latest = if i == 0 { " (latest)" } else { "" }; - let date = r.published_at.split('T').next().unwrap_or(""); - choice.choice_append(&format!("{tag}{kind} {date}{latest}")); - } - choice.choice_set_selection(0); - } root.add( choice, 0, @@ -2724,15 +2915,72 @@ impl App { ); self.install_release_choice = choice; + // Release repo: any Gitea owner/repo that publishes the same .afw release + // 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, "Board password (optional):"), + Widget::static_text(dlg, "Release repo (owner/repo), then Reload:"), 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 12, ); - let pass = Widget::text_ctrl(dlg, false); - root.add(pass, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12); - self.install_pass_input = pass; + let repo_row = Widget::box_sizer(false); + let repo_input = Widget::text_ctrl(dlg, false); + repo_input.set_value("blueflare/alkane-os"); + repo_row.add( + repo_input, + 1, + sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_RIGHT, + 6, + ); + repo_row.add(Widget::button(dlg, "Reload", ID_INSTALL_RELOAD), 0, 0, 0); + self.install_repo_input = repo_input; + root.add_sizer( + repo_row, + 0, + sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, + 12, + ); + // Initial population from the default repo. + self.populate_install_releases("blueflare", "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:"), + 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)"); + browse_row.add(local_label, 1, sf::ALIGN_CENTRE_VERTICAL, 0); + self.install_local_label = local_label; + root.add_sizer( + browse_row, + 0, + sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, + 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)"); @@ -2740,23 +2988,17 @@ impl App { 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. Type FLASH to confirm:", + "This reflashes the control board. Click Install to start.", ), 0, - sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, + sf::BORDER_ALL, 12, ); - let confirm = Widget::text_ctrl(dlg, false); - root.add( - confirm, - 0, - sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, - 12, - ); - self.install_confirm_input = confirm; let btns = Widget::box_sizer(false); btns.add_stretch(1); @@ -2787,45 +3029,59 @@ impl App { /// 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) { - if self.hardware_busy() { + if self.flash_busy() { wx_rs::set_status_text("busy -- try again once the current operation finishes"); self.install_dialog.close(0); return; } - if !flash_confirmed(&self.install_confirm_input.get_value()) { - wx_rs::set_status_text("type FLASH to confirm the install"); - return; - } - let idx = self.install_release_choice.choice_get_selection(); - if idx < 0 || self.install_releases.is_empty() { - wx_rs::set_status_text("no release selected"); - return; - } let board = self.install_board.clone(); - let Some(release) = self.install_releases.get(idx as usize) else { - wx_rs::set_status_text("no release selected"); - return; - }; - let Some(asset) = release.asset_for_board(&board) else { - wx_rs::set_status_text("the selected release has no .afw for this board"); - return; - }; - let source = AfwChoice { - name: asset.name.clone(), - url: asset.url.clone(), - }; - let asset_name = asset.name.clone(); - let allow_unsigned = self.install_unsigned_check.is_checked(); - let password = { - let p = self.install_pass_input.get_value(); - if p.is_empty() { - None - } else { - Some(p) + // 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() { + let name = std::path::Path::new(&path) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| path.clone()); + (AfwSource::Local(std::path::PathBuf::from(path)), name) + } else { + let idx = self.install_release_choice.choice_get_selection(); + if idx < 0 || self.install_releases.is_empty() { + self.set_error_indicator( + "pick a Gitea release or Browse for a local .afw, then start the install", + ); + return; } + let Some(release) = self.install_releases.get(idx as usize) else { + self.set_error_indicator("the selected release is no longer available; rescan"); + return; + }; + let Some(asset) = release.asset_for_board(&board) else { + self.set_error_indicator(&format!( + "the selected release has no .afw for {board}; pick another or Browse for a file" + )); + return; + }; + ( + AfwSource::Release { + name: asset.name.clone(), + url: asset.url.clone(), + }, + asset.name.clone(), + ) }; + let allow_unsigned = self.install_unsigned_check.is_checked(); + // The STOCK board's shipped login (overridable per-firmware in Settings), + // so install authenticates with no password field (issues #46, #51). The + // target is on stock, so its firmware's default (e.g. AntMiner root/root) + // is correct -- not a saved alkane login. + let password = self + .selected_rows() + .first() + .map(|r| credentials::cred_for(&r.firmware).1) + .filter(|p| !p.is_empty()); let ips = std::mem::take(&mut self.install_ips); if ips.is_empty() { + self.set_error_indicator("no board selected to install onto; close this and reselect"); self.install_dialog.close(0); return; } @@ -2833,22 +3089,31 @@ impl App { crate::logs::log(format!( "install alkane OS onto {} board(s) from {}", ips.len(), - asset_name + source_name )); + wx_rs::set_status_text(&format!( + "installing alkane OS onto {} board(s) from {source_name}...", + ips.len() + )); + self.stop_scan_for_op(); self.set_op_status(&ips, "installing..."); + // Remember these targets so a successful install arms the post-install + // alkane verification (prevents the stock->alkane re-scan flicker). + self.install_targets = ips.iter().cloned().collect(); self.stock_op = Some(stock_ops::start_install( ips, board, source, allow_unsigned, password, + self.install_is_update, )); } /// Build the "Uninstall alkane OS (restore to stock)" dialog: the board's - /// alkane root credential and a typed FLASH confirmation. + /// alkane root credential and a genuine Bitmain firmware file. fn build_uninstall_dialog(&mut self) -> Option { - if self.hardware_busy() { + if self.flash_busy() { wx_rs::set_status_text("busy -- try again once the current operation finishes"); return None; } @@ -2874,46 +3139,81 @@ impl App { sf::BORDER_ALL, 12, ); + // Credentials come from Settings (the alkane root login), not this dialog + // (issue #46). Probe each selected board for a restorable on-board stock + // backup so the on-board option can be offered or greyed out (#48). + let cred = { + let p = credentials::cred_for(crate::alkane_detect::FIRMWARE).1; + (!p.is_empty()).then_some(p) + }; + let onboard_ok = ips + .iter() + .all(|ip| stock_ops::onboard_backup_present(ip, cred.as_deref())); + self.uninstall_onboard_available = onboard_ok; + + // Source 1: the board's own on-board stock backup (always shown; greyed + // when no backup is present) (#48). + let onboard = Widget::check_box( + dlg, + "Restore from the board's on-board stock backup (left by the install)", + ); + onboard.set_checked(onboard_ok); + onboard.set_enabled(onboard_ok); + root.add(onboard, 0, sf::BORDER_ALL, 12); + self.uninstall_onboard_check = onboard; root.add( Widget::static_text( dlg, - "Genuine Bitmain stock firmware file for this board\n(an OTA update .tar.gz or an SD recovery .zip):", + if onboard_ok { + "An on-board stock backup was detected -- this is the default." + } else { + "No on-board stock backup detected; restore from a file below." + }, + ), + 0, + sf::BORDER_LEFT | sf::BORDER_RIGHT, + 12, + ); + + // Source 2: a genuine Bitmain stock firmware file (any X17-series model); + // Browse to pick it (#47). + root.add( + Widget::static_text( + dlg, + "Or restore from a Bitmain stock firmware file\n(OTA update .tar.gz or SD recovery .zip, any X17-series model):", ), 0, sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, 12, ); + let fw_row = Widget::box_sizer(false); + fw_row.add( + Widget::button(dlg, "Browse firmware file...", ID_UNINSTALL_BROWSE), + 0, + sf::BORDER_RIGHT, + 6, + ); let fw = Widget::text_ctrl(dlg, false); - root.add(fw, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12); + fw_row.add(fw, 1, sf::ALIGN_CENTRE_VERTICAL, 0); self.uninstall_firmware_input = fw; - - root.add( - Widget::static_text(dlg, "Board (alkane root) password (optional):"), - 0, - sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, - 12, - ); - let pass = Widget::text_ctrl(dlg, false); - root.add(pass, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12); - self.uninstall_pass_input = pass; - - root.add( - Widget::static_text( - dlg, - "This reflashes the board back to stock (BOOT.bin preserved).\nType FLASH to confirm:", - ), - 0, - sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP, - 12, - ); - let confirm = Widget::text_ctrl(dlg, false); - root.add( - confirm, + root.add_sizer( + fw_row, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12, ); - self.uninstall_confirm_input = confirm; + + // No typed-FLASH step (issue #41): the dialog and the Restore button are + // the confirmation. + root.add( + Widget::static_text( + dlg, + "This reflashes the board back to stock (BOOT.bin preserved). Click Restore to start.", + ), + 0, + sf::BORDER_ALL, + 12, + ); let btns = Widget::box_sizer(false); btns.add_stretch(1); btns.add( @@ -2937,32 +3237,34 @@ impl App { } fn apply_uninstall_confirm(&mut self) { - if self.hardware_busy() { + if self.flash_busy() { wx_rs::set_status_text("busy -- try again once the current operation finishes"); self.uninstall_dialog.close(0); return; } - if !flash_confirmed(&self.uninstall_confirm_input.get_value()) { - wx_rs::set_status_text("type FLASH to confirm the restore"); - return; - } + // On-board backup restore takes precedence when its box is checked and a + // backup was detected; otherwise restore from the chosen firmware file. + let use_onboard = + self.uninstall_onboard_available && self.uninstall_onboard_check.is_checked(); let firmware = self.uninstall_firmware_input.get_value(); - let firmware = firmware.trim(); - if firmware.is_empty() { - wx_rs::set_status_text("a genuine Bitmain stock firmware file is required"); - return; - } - if !std::path::Path::new(firmware).is_file() { - wx_rs::set_status_text(&format!("firmware file not found: {firmware}")); - return; - } - let password = { - let p = self.uninstall_pass_input.get_value(); - if p.is_empty() { - None - } else { - Some(p) + let firmware = firmware.trim().to_string(); + if !use_onboard { + if firmware.is_empty() { + self.set_error_indicator( + "pick a stock firmware file (Browse), or check the on-board backup option", + ); + return; } + if !std::path::Path::new(&firmware).is_file() { + self.set_error_indicator(&format!("firmware file not found: {firmware}")); + return; + } + } + // The ALKANE board's shipped login (overridable per-firmware in + // Settings), so restore authenticates with no password field (#46, #51). + let password = { + let p = credentials::cred_for(crate::alkane_detect::FIRMWARE).1; + (!p.is_empty()).then_some(p) }; let ips = std::mem::take(&mut self.uninstall_ips); if ips.is_empty() { @@ -2970,13 +3272,26 @@ impl App { return; } self.uninstall_dialog.close(1); - crate::logs::log(format!("restore {} alkane board(s) to stock", ips.len())); + self.stop_scan_for_op(); self.set_op_status(&ips, "restoring..."); - self.stock_op = Some(stock_ops::start_restore( - ips, - std::path::PathBuf::from(firmware), - password, - )); + if use_onboard { + crate::logs::log(format!( + "restore {} alkane board(s) to stock from on-board backup", + ips.len() + )); + self.stock_op = Some(stock_ops::start_restore_onboard(ips, password)); + } else { + crate::logs::log(format!( + "restore {} alkane board(s) to stock from {}", + ips.len(), + firmware + )); + self.stock_op = Some(stock_ops::start_restore( + ips, + std::path::PathBuf::from(firmware), + password, + )); + } } /// Drain the alkane install/uninstall job: progress onto the status bar, @@ -2987,18 +3302,25 @@ impl App { let mut oks = 0usize; let mut fails: Vec = Vec::new(); let mut op_clear: Vec = Vec::new(); + // Successfully-installed IPs whose boards should now come up as alkane. + let mut verify_ips: Vec = Vec::new(); let mut progress: Option = None; loop { match h.rx.try_recv() { Ok(StockMsg::Started) => {} Ok(StockMsg::Progress(s)) => progress = Some(s), Ok(StockMsg::Result { ip, ok, detail }) => { - if !ip.is_empty() { - op_clear.push(ip.clone()); - } if ok { oks += 1; + if !ip.is_empty() && self.install_targets.contains(&ip) { + verify_ips.push(ip.clone()); + } else if !ip.is_empty() { + op_clear.push(ip.clone()); + } } else { + if !ip.is_empty() { + op_clear.push(ip.clone()); + } fails.push(format!("{ip}: {detail}")); } } @@ -3016,22 +3338,72 @@ impl App { for ip in &op_clear { self.op_status.remove(ip); } + // Arm post-install alkane verification for the boards that installed OK: + // keep a "verifying" status on them and suppress stock re-scan rows until + // they answer as alkane (prevents the stock->alkane flicker). + for ip in &verify_ips { + self.installed_awaiting.insert(ip.clone(), 8); + self.op_status + .insert(ip.clone(), "installed; verifying alkane...".into()); + } if let Some(p) = progress { wx_rs::set_status_text(&p); + // Show a progress bar in the Health cell of each in-flight board + // (issue #42: "installing" alone was not enough feedback). + let pct = stock_progress_pct(&p); + let bar = ascii_bar(pct); + let updates: Vec<(String, String)> = self + .op_status + .iter() + .filter(|(_, v)| v.starts_with("installing") || v.starts_with("restoring")) + .map(|(ip, v)| { + let verb = if v.starts_with("restoring") { + "restoring" + } else { + "installing" + }; + (ip.clone(), format!("{verb} {bar} {pct}%")) + }) + .collect(); + for (ip, s) in updates { + self.op_status.insert(ip, s); + } } if done { self.stock_op = None; + self.install_targets.clear(); + // Clear any in-progress "installing/restoring [bar] NN%" statuses, but + // keep "installed; verifying alkane..." (starts with "installed"). self.op_status - .retain(|_, v| v != "installing..." && v != "restoring..."); + .retain(|_, v| !v.starts_with("installing") && !v.starts_with("restoring")); } - if !op_clear.is_empty() || done { + if !op_clear.is_empty() || !verify_ips.is_empty() || done { self.fill_rows(); } + // Kick a dedicated re-probe of the just-installed boards; the row + // suppression below only accepts them once they answer as alkane. + if done && !verify_ips.is_empty() && self.refresh.is_none() && !self.scanning { + self.start_refresh(verify_ips.clone()); + } if done { if !fails.is_empty() { - self.set_error_indicator(&format!("stock op: {} failed", fails.len())); + // Surface the actual reason, not just a count (issue #38: a bare + // "1 failed" left the operator unable to tell what went wrong). + for f in &fails { + crate::logs::log(format!("install/restore failed -- {f}")); + } + let first = fails.first().cloned().unwrap_or_default(); + let more = if fails.len() > 1 { + format!(" (+{} more; see the log)", fails.len() - 1) + } else { + String::new() + }; + self.set_error_indicator(&format!("install/restore failed -- {first}{more}")); } else if oks > 0 { - wx_rs::set_status_text(&format!("stock op complete: {oks} ok")); + crate::logs::log(format!("install/restore complete: {oks} board(s) ok")); + wx_rs::set_status_text(&format!( + "install/restore complete: {oks} board(s) ok -- verify liveness over the network" + )); } } } @@ -4097,9 +4469,19 @@ impl App { status = Some(format!("refreshing 0/{total} miner(s)...")); } Ok(scan::RefreshMsg::Row(row)) => { - op_clear.push(row.ip.clone()); - row.upsert_into(&mut self.rows); - changed = true; + if self.installed_awaiting.contains_key(&row.ip) { + // Accept a just-installed board only once it is alkane. + if crate::alkane_detect::is_alkane(&row) { + self.installed_awaiting.remove(&row.ip); + op_clear.push(row.ip.clone()); + row.upsert_into(&mut self.rows); + changed = true; + } + } else { + op_clear.push(row.ip.clone()); + row.upsert_into(&mut self.rows); + changed = true; + } } Ok(scan::RefreshMsg::Failed { ip, detail }) => { op_clear.push(ip.clone()); @@ -4129,6 +4511,7 @@ impl App { self.refresh = None; // Any stragglers still marked "refreshing..." revert to icons. self.op_status.retain(|_, v| v != "refreshing..."); + Self::tick_installed_awaiting(&mut self.installed_awaiting, &mut self.op_status); } // Refresh progress stays in the Health column, not the scan line (#8). let _ = status; @@ -4137,6 +4520,34 @@ impl App { } } + /// Count down each board awaiting post-install alkane confirmation. When a + /// board's rounds run out, stop suppressing its row and clear the status: the + /// install finished but the board never came up answering as alkane. Takes the + /// two maps directly (not `&mut self`) so it can run while a scan/refresh + /// handle still borrows another field of `self`. + fn tick_installed_awaiting( + awaiting: &mut HashMap, + op_status: &mut HashMap, + ) { + if awaiting.is_empty() { + return; + } + let mut expired = Vec::new(); + for (ip, left) in awaiting.iter_mut() { + *left = left.saturating_sub(1); + if *left == 0 { + expired.push(ip.clone()); + } + } + for ip in expired { + awaiting.remove(&ip); + op_status.remove(&ip); + crate::logs::log(format!( + "{ip}: installed, but did not answer as alkane within the verify window" + )); + } + } + pub fn drain_scan(&mut self) { let Some(handle) = &self.scan else { return }; let mut changed = false; @@ -4175,8 +4586,19 @@ impl App { Ok(ScanMsg::Row(row)) => { // Ignore stray rows outside the current target set. if self.target_ips.is_empty() || self.target_ips.contains(&row.ip) { - row.upsert_into(&mut self.rows); - changed = true; + if self.installed_awaiting.contains_key(&row.ip) { + // Just installed: accept the row only once it answers as + // alkane; a stock mid-reboot answer is suppressed. + if crate::alkane_detect::is_alkane(&row) { + self.installed_awaiting.remove(&row.ip); + self.op_status.remove(&row.ip); + row.upsert_into(&mut self.rows); + changed = true; + } + } else { + row.upsert_into(&mut self.rows); + changed = true; + } } } Ok(ScanMsg::Done(_s)) => { @@ -4185,8 +4607,20 @@ impl App { self.progress.show(false); self.table_parent.layout(); crate::logs::log(format!("scan complete: {} miner(s) found", self.rows.len())); - // Arm the next automatic scan (if the loop is running). - self.countdown = if self.playing { self.auto_secs } else { 0 }; + Self::tick_installed_awaiting( + &mut self.installed_awaiting, + &mut self.op_status, + ); + // Arm the next automatic scan (if the loop is running). While + // boards are still being verified as alkane, re-probe soon + // instead of waiting the full interval. + self.countdown = if !self.installed_awaiting.is_empty() && self.playing { + self.auto_secs.min(12) + } else if self.playing { + self.auto_secs + } else { + 0 + }; } Ok(ScanMsg::Failed(e)) => { self.scanning = false; @@ -4245,8 +4679,76 @@ impl App { /// Called every second by the scan timer: drain scan messages, then run the /// scan-loop scheduler (countdown to the next automatic rescan, or idle). + /// Toggle the main window between the fleet table and the live activity log. + fn toggle_log_view(&mut self) { + self.showing_log = !self.showing_log; + if self.showing_log { + if let Some(t) = self.table { + t.show(false); + } + self.log_view.show(true); + self.log_view.set_value(""); + self.log_shown_len = 0; + self.refresh_log_view(); + self.log_toggle_btn.set_label("Table"); + } else { + self.log_view.show(false); + if let Some(t) = self.table { + t.show(true); + } + self.log_toggle_btn.set_label("Log"); + } + self.table_parent.layout(); + } + + /// Tail the activity log into the log view: append only the lines added since + /// last shown (so the view stays scrolled to the newest entry); on a shrink + /// (log cleared) reset. Cheap no-op when nothing changed. + fn refresh_log_view(&mut self) { + let text = crate::logs::dump(); + let total = if text.is_empty() { + 0 + } else { + text.lines().count() + }; + if total > self.log_shown_len { + let new: String = text + .lines() + .skip(self.log_shown_len) + .map(|l| format!("{l}\n")) + .collect(); + self.log_view.write_text(&new); + self.log_shown_len = total; + } else if total < self.log_shown_len { + self.log_view.set_value(&text); + self.log_shown_len = total; + } + } + fn tick(&mut self) -> Option { self.drain_scan(); + if self.showing_log { + self.refresh_log_view(); + } + // Keep verifying just-installed boards on a fixed cadence even when + // auto-scan is off (review #2): without this, a board could sit on + // "verifying alkane..." forever. Re-probes only when nothing else is in + // flight; each probe's Done decrements the give-up counter. + if self.installed_awaiting.is_empty() { + self.verify_cooldown = 0; + } else if self.scan.is_none() && self.refresh.is_none() && self.stock_op.is_none() { + if self.verify_cooldown == 0 { + let ips: Vec = self.installed_awaiting.keys().cloned().collect(); + self.start_refresh(ips.clone()); + for ip in ips { + self.op_status + .insert(ip, "installed; verifying alkane...".into()); + } + self.verify_cooldown = 10; + } else { + self.verify_cooldown -= 1; + } + } self.drain_action(); self.drain_refresh(); self.drain_access_probe(); @@ -5005,7 +5507,9 @@ impl App { sf::BORDER_LEFT | sf::BORDER_RIGHT, 8, ); - let text = Widget::text_ctrl(dlg, true); + // Word-wrap the report box so long lines wrap instead of running off the + // edge (issue #37). + let text = Widget::text_ctrl_wrapped(dlg); text.set_min_size(560, 220); root.add(text, 1, sf::EXPAND | sf::BORDER_ALL, 8); let log = Widget::check_box( @@ -5031,8 +5535,11 @@ impl App { 8, ); let btns = Widget::box_sizer(false); - let open = Widget::button(dlg, &t("Open issue"), ID_REPORT_OPEN); + // Hidden until a report is filed; then it becomes the "issue #N" link. + let open = Widget::button(dlg, "", ID_REPORT_OPEN); + open.show(false); btns.add(open, 0, sf::BORDER_ALL, 6); + self.report_open_btn = open; btns.add_stretch(1); btns.add( Widget::button(dlg, &t("Close"), ID_REPORT_CLOSE), @@ -5116,16 +5623,18 @@ impl App { match result { Ok(filed) => { crate::logs::log(format!("bug report filed as issue #{}", filed.number)); - self.report_status.set_label(&format!( - "{} #{}", - t("Thank you. Filed as issue"), - filed.number - )); + self.report_status + .set_label(&t("Thank you for the report.")); self.report_text.set_value(""); self.report_kind.choice_set_selection(0); if !filed.url.is_empty() { self.report_url = Some(filed.url); } + // Turn the filed issue into a clickable link (issue #50). + self.report_open_btn + .set_label(&format!("{} #{}", t("View issue"), filed.number)); + self.report_open_btn.show(true); + self.report_dialog.layout(); } Err(e) => { crate::logs::log(format!("bug report not sent: {e}")); @@ -5720,6 +6229,7 @@ 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_LOG_TOGGLE => self.toggle_log_view(), ID_BUG_REPORT => return Some(self.build_report_dialog()), ID_REPORT_SEND => self.send_report(), ID_REPORT_CLOSE => self.report_dialog.close(0), @@ -5779,11 +6289,48 @@ impl App { self.restore_dialog.close(0); } ID_INSTALL_OK => self.apply_install_confirm(), + ID_INSTALL_RELOAD => self.reload_install_repo(), + ID_INSTALL_BROWSE => { + if let Some(path) = Widget::file_dialog( + self.install_dialog, + "Choose a local .afw to install", + ) { + let name = std::path::Path::new(&path) + .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_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.", + ); + self.install_local_path = None; + } + } ID_INSTALL_CANCEL => { self.install_ips.clear(); self.install_dialog.close(0); } ID_UNINSTALL_OK => self.apply_uninstall_confirm(), + ID_UNINSTALL_BROWSE => { + if let Some(path) = Widget::file_dialog( + self.uninstall_dialog, + "Choose a Bitmain stock firmware file (.tar.gz or .zip)", + ) { + self.uninstall_firmware_input.set_value(&path); + // Picking a file means restoring from the file, not the + // on-board backup. + self.uninstall_onboard_check.set_checked(false); + } + } ID_UNINSTALL_CANCEL => { self.uninstall_ips.clear(); self.uninstall_dialog.close(0); @@ -6187,6 +6734,26 @@ mod tests { //! cell comparison deliberately strips out, so they need their own coverage. use super::*; + #[test] + fn progress_bar_fills_proportionally() { + assert_eq!(ascii_bar(0), "[----------]"); + assert_eq!(ascii_bar(50), "[#####-----]"); + assert_eq!(ascii_bar(100), "[##########]"); + assert_eq!(ascii_bar(70), "[#######---]"); + // Over-100 is clamped, never panics. + assert_eq!(ascii_bar(200), "[##########]"); + } + + #[test] + fn stock_phase_percents_are_monotonic() { + let acq = stock_progress_pct("acquiring .afw..."); + let ver = stock_progress_pct("verifying .afw..."); + let inst = stock_progress_pct("installing zynq-7010 onto 10.0.0.5 (from stock)..."); + assert!(acq < ver && ver < inst, "{acq} < {ver} < {inst}"); + assert_eq!(stock_progress_pct("using local t.afw..."), acq); + assert_eq!(stock_progress_pct("restoring 10.0.0.5 to stock..."), inst); + } + /// A palette with unambiguous sentinel colours so equality checks are exact. fn test_pal() -> Palette { Palette { diff --git a/docs/install.md b/docs/install.md index 3d001939..309957b6 100644 --- a/docs/install.md +++ b/docs/install.md @@ -142,15 +142,15 @@ selected board: for; today the Zynq-7010 Antminer S17/S17 Pro/T17) that is not running Alkane OS yet. Scans the alkane-os releases on Gitea, lets you pick one (newest first; pre-releases are marked), optionally takes a board password and an "allow - unsigned .afw (bench)" toggle, and - after you type FLASH to confirm - - downloads/verifies the `.afw` and installs it onto each selected board over the - network, via the same compiled-in engine the CLI uses. + unsigned .afw (bench)" toggle, then - when you click Install - downloads and + verifies the `.afw` and installs it onto each selected board over the network, + via the same compiled-in engine the CLI uses. - "Update alkane OS..." - for a supported board already running Alkane OS: the same release picker and confirmation; the board is updated in place (BOOT.bin is never written). - "Uninstall alkane OS (restore to stock)..." - for a board running Alkane OS: - takes the board's alkane root password, a genuine Bitmain firmware package and - a typed FLASH confirmation, then restores each selected board to genuine stock + takes the board's alkane root password and a genuine Bitmain firmware package, + then - when you click Restore - restores each selected board to genuine stock over the network. A stock board the scan identifies but cannot place on a supported control board diff --git a/thirdparty/wx-rs/patches/0012-text-ctrl-wrap.patch b/thirdparty/wx-rs/patches/0012-text-ctrl-wrap.patch new file mode 100644 index 00000000..010a87a6 --- /dev/null +++ b/thirdparty/wx-rs/patches/0012-text-ctrl-wrap.patch @@ -0,0 +1,43 @@ +Subject: [PATCH 0012] linux: word-wrapping multiline text control + +--- a/cpp_src/widgets_bridge.cpp ++++ b/cpp_src/widgets_bridge.cpp +@@ -890,6 +890,15 @@ + wxDefaultPosition, wxSize(-1, -1), style); + } + ++// A multiline text control that word-wraps at the control's width instead of ++// scrolling horizontally (no wxTE_DONTWRAP). For prose entry such as the bug ++// report box, where long lines should wrap rather than run off the edge. ++void* wxbr_text_ctrl_wrap(void* parent) { ++ return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""), ++ wxDefaultPosition, wxSize(-1, -1), ++ wxTE_MULTILINE | wxTE_BESTWRAP); ++} ++ + // A single-line text control that masks its content (wxTE_PASSWORD), for secret + // entry so a saved password is never rendered in the clear (round 18 #12). + void* wxbr_text_ctrl_password(void* parent) { +--- a/src/widgets.rs ++++ b/src/widgets.rs +@@ -41,6 +41,7 @@ + pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void; + pub fn wxbr_bind_click(win: *mut c_void, id: c_int); + pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void; ++ pub fn wxbr_text_ctrl_wrap(parent: *mut c_void) -> *mut c_void; + pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void; + pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int; + pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char); +@@ -463,6 +464,12 @@ + Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) }) + } + ++ /// A multiline text control that word-wraps at its width (no horizontal ++ /// scroll), for prose entry such as the bug-report box. ++ pub fn text_ctrl_wrapped(parent: Widget) -> Widget { ++ Widget(unsafe { notsafe::wxbr_text_ctrl_wrap(parent.0) }) ++ } ++ + /// A single-line text control that masks its content (for password entry). + pub fn password_ctrl(parent: Widget) -> Widget { + Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) }) diff --git a/thirdparty/wx-rs/patches/0013-enable-control.patch b/thirdparty/wx-rs/patches/0013-enable-control.patch new file mode 100644 index 00000000..fdd9998a --- /dev/null +++ b/thirdparty/wx-rs/patches/0013-enable-control.patch @@ -0,0 +1,38 @@ +Subject: [PATCH 0013] linux: Enable/disable (grey out) a control + +--- a/cpp_src/widgets_bridge.cpp ++++ b/cpp_src/widgets_bridge.cpp +@@ -945,6 +945,11 @@ + ((wxCheckBox*)win)->SetValue(v != 0); + } + ++// Enable or disable (grey out) any window/control. ++void wxbr_enable(void* win, int on) { ++ ((wxWindow*)win)->Enable(on != 0); ++} ++ + // ---- check list box --------------------------------------------------------- + + void* wxbr_check_list_box(void* parent) { +--- a/src/widgets.rs ++++ b/src/widgets.rs +@@ -49,6 +49,7 @@ + pub fn wxbr_check_box(parent: *mut c_void, label: *const c_char) -> *mut c_void; + pub fn wxbr_check_box_get(win: *mut c_void) -> c_int; + pub fn wxbr_check_box_set(win: *mut c_void, v: c_int); ++ pub fn wxbr_enable(win: *mut c_void, on: c_int); + pub fn wxbr_check_list_box(parent: *mut c_void) -> *mut c_void; + pub fn wxbr_clb_append(win: *mut c_void, label: *const c_char); + pub fn wxbr_clb_clear(win: *mut c_void); +@@ -508,6 +509,11 @@ + unsafe { notsafe::wxbr_check_box_set(self.0, v as c_int) } + } + ++ /// Enable or disable (grey out) this control. ++ pub fn set_enabled(&self, on: bool) { ++ unsafe { notsafe::wxbr_enable(self.0, on as c_int) } ++ } ++ + pub fn check_list_box(parent: Widget) -> Widget { + Widget(unsafe { notsafe::wxbr_check_list_box(parent.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 193ca2dd..02818d53 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 @@ -890,6 +890,15 @@ void* wxbr_text_ctrl(void* parent, int multiline) { wxDefaultPosition, wxSize(-1, -1), style); } +// A multiline text control that word-wraps at the control's width instead of +// scrolling horizontally (no wxTE_DONTWRAP). For prose entry such as the bug +// report box, where long lines should wrap rather than run off the edge. +void* wxbr_text_ctrl_wrap(void* parent) { + return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""), + wxDefaultPosition, wxSize(-1, -1), + wxTE_MULTILINE | wxTE_BESTWRAP); +} + // A single-line text control that masks its content (wxTE_PASSWORD), for secret // entry so a saved password is never rendered in the clear (round 18 #12). void* wxbr_text_ctrl_password(void* parent) { @@ -936,6 +945,11 @@ void wxbr_check_box_set(void* win, int v) { ((wxCheckBox*)win)->SetValue(v != 0); } +// Enable or disable (grey out) any window/control. +void wxbr_enable(void* win, int on) { + ((wxWindow*)win)->Enable(on != 0); +} + // ---- check list box --------------------------------------------------------- void* wxbr_check_list_box(void* parent) { 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 eada9414..2b89079e 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 @@ -41,6 +41,7 @@ mod notsafe { pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void; pub fn wxbr_bind_click(win: *mut c_void, id: c_int); pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void; + pub fn wxbr_text_ctrl_wrap(parent: *mut c_void) -> *mut c_void; pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void; pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int; pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char); @@ -48,6 +49,7 @@ mod notsafe { pub fn wxbr_check_box(parent: *mut c_void, label: *const c_char) -> *mut c_void; pub fn wxbr_check_box_get(win: *mut c_void) -> c_int; pub fn wxbr_check_box_set(win: *mut c_void, v: c_int); + pub fn wxbr_enable(win: *mut c_void, on: c_int); pub fn wxbr_check_list_box(parent: *mut c_void) -> *mut c_void; pub fn wxbr_clb_append(win: *mut c_void, label: *const c_char); pub fn wxbr_clb_clear(win: *mut c_void); @@ -463,6 +465,12 @@ impl Widget { Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) }) } + /// A multiline text control that word-wraps at its width (no horizontal + /// scroll), for prose entry such as the bug-report box. + pub fn text_ctrl_wrapped(parent: Widget) -> Widget { + Widget(unsafe { notsafe::wxbr_text_ctrl_wrap(parent.0) }) + } + /// A single-line text control that masks its content (for password entry). pub fn password_ctrl(parent: Widget) -> Widget { Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) }) @@ -501,6 +509,11 @@ impl Widget { unsafe { notsafe::wxbr_check_box_set(self.0, v as c_int) } } + /// Enable or disable (grey out) this control. + pub fn set_enabled(&self, on: bool) { + unsafe { notsafe::wxbr_enable(self.0, on as c_int) } + } + pub fn check_list_box(parent: Widget) -> Widget { Widget(unsafe { notsafe::wxbr_check_list_box(parent.0) }) } diff --git a/tools/report-relay/compose.yml b/tools/report-relay/compose.yml index ef542543..ed8b0965 100644 --- a/tools/report-relay/compose.yml +++ b/tools/report-relay/compose.yml @@ -15,8 +15,8 @@ services: GITEA_URL: http://gitea:3000 GITEA_REPO: blueflare/alkane-toolkit GITEA_TOKEN_FILE: /run/secrets/gitea_token - RATE_PER_IP: "5" - RATE_GLOBAL: "60" + RATE_PER_IP: "100" + RATE_GLOBAL: "300" volumes: - ./secrets/gitea_token:/run/secrets/gitea_token:ro networks: [proxy] diff --git a/tools/report-relay/test_relay.py b/tools/report-relay/test_relay.py index 07f53a10..bae361cc 100644 --- a/tools/report-relay/test_relay.py +++ b/tools/report-relay/test_relay.py @@ -7,6 +7,7 @@ import json import pathlib import sys import threading +import time import unittest import urllib.error import urllib.request @@ -16,6 +17,12 @@ import relay # noqa: E402 TOKEN = "test-token-123" +# The repository's labels, as the real Gitea /labels endpoint would return them. +# The mock serves these, and setUp seeds the relay client's label cache from the +# same list so label resolution is deterministic (see RelayTests.setUp). +REPO_LABELS = [{"name": "bug", "id": 1}, {"name": "ui", "id": 2}, + {"name": "feature", "id": 3}, {"name": "from-app", "id": 9}] + class FakeGitea: """Records issue creations; serves the repository's labels.""" @@ -40,9 +47,7 @@ class FakeGitea: def do_GET(self): assert self.headers["Authorization"] == f"token {TOKEN}" if self.path.startswith("/api/v1/repos/blueflare/alkane-toolkit/labels"): - return self._json(200, [{"name": "bug", "id": 1}, {"name": "ui", "id": 2}, - {"name": "feature", "id": 3}, - {"name": "from-app", "id": 9}]) + return self._json(200, REPO_LABELS) self._json(404, {}) def do_POST(self): @@ -58,6 +63,23 @@ class FakeGitea: self.server = ThreadingHTTPServer(("127.0.0.1", 0), H) threading.Thread(target=self.server.serve_forever, daemon=True).start() self.url = f"http://127.0.0.1:{self.server.server_address[1]}" + # Block until the serve_forever thread is actually handling requests, so + # the relay's first label fetch cannot race server startup. The socket + # listens from __init__, but under load the daemon thread can be starved + # past the relay's HTTP timeout, which silently drops labels to [] and + # made the first test flaky in CI. + probe = urllib.request.Request( + self.url + "/api/v1/repos/blueflare/alkane-toolkit/labels", + headers={"Authorization": f"token {TOKEN}"}) + deadline = time.monotonic() + 5 + while True: + try: + urllib.request.urlopen(probe, timeout=1).read() + break + except Exception: + if time.monotonic() >= deadline: + raise + time.sleep(0.02) def close(self): self.server.shutdown() @@ -70,8 +92,18 @@ class RelayTests(unittest.TestCase): self.now = [1000.0] self.limiter = relay.RateLimiter(2, 3, clock=lambda: self.now[0]) self.logs = [] - r = relay.Relay(relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN), - self.limiter, log=self.logs.append) + client = relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN) + # Seed the relay client's label cache directly from REPO_LABELS instead + # of letting a request handler fetch it live. Gitea.label_ids() caches + # for 10 minutes and silently falls back to [] on any fetch error; in CI + # that first live GET -- a second server-to-server hop made from inside + # the relay's own request thread -- failed reliably and dropped the + # labels to [], while the issue-filing POST on the same path still + # worked. Seeding the cache keeps label resolution deterministic (the + # name->id mapping is still exercised) and leaves the issue POST live. + client.labels = {label["name"]: label["id"] for label in REPO_LABELS} + client.labels_at = time.monotonic() + r = relay.Relay(client, self.limiter, log=self.logs.append) self.server = ThreadingHTTPServer(("127.0.0.1", 0), relay.make_handler(r)) threading.Thread(target=self.server.serve_forever, daemon=True).start() self.url = f"http://127.0.0.1:{self.server.server_address[1]}"