diff --git a/README.md b/README.md index def1b8f9..ede5f877 100644 --- a/README.md +++ b/README.md @@ -47,13 +47,20 @@ and Intel, macOS 11 or later; see [docs/macos.md](docs/macos.md). Discovery is read-only. Control and restore actions change miners. Check the selected devices before applying them. -## Headless .afw install (CV1835) +## Headless .afw install (CV1835 and AM335x) `alkane-cli` is the headless engine; the GUI uses the same engine. A verified `.afw` is a full OS bundle for exactly one board. The CV1835 installer writes only `/dev/mmcblk0p1` over SSH, holds the current p1 first, reads the whole partition back, and reboots only after the read-back matches. +The AM335x installer writes mtd8 (type-3 ramdisk), mtd6 (dtb) and mtd7 +(legacy kernel uImage) with `flash_erase` + `nandwrite`. It never touches +mtd0-5 (SPL/U-Boot/bootenv), holds a backup of each target before writing it, +and reads every target back before reboot. Its `verify-live` checks SSH +(kernel string), the HTTP marker on port 80, the API on port 4028, and the +eth0 DHCP lease. + ```sh alkane-cli afw verify BUNDLE.afw --allow-unsigned alkane-cli afw plan BUNDLE.afw --host 10.255.1.167 @@ -64,6 +71,19 @@ alkane-cli afw verify-live BUNDLE.afw --host 10.255.1.167 alkane-cli afw restore --host 10.255.1.167 --held-backup p1.img --confirm FLASH ``` +For AM335x the same subcommands infer the board from the bundle; restore names +the three held copies explicitly: + +```sh +alkane-cli afw plan BUNDLE.afw --host 10.255.1.64 +alkane-cli afw preflight BUNDLE.afw --host 10.255.1.64 +alkane-cli afw install BUNDLE.afw --host 10.255.1.64 --dry-run +alkane-cli afw install BUNDLE.afw --host 10.255.1.64 --confirm FLASH +alkane-cli afw verify-live BUNDLE.afw --host 10.255.1.64 --timeout 300 +alkane-cli afw restore --board am335x --host 10.255.1.64 \ + --held-backup mtd8.img --held-kernel mtd7.img --held-dtb mtd6.img --confirm FLASH +``` + On stock Bitmain CV1835 the SSH login is the unprivileged `miner` account; the toolkit obtains root through the stock update-daemon loopback channel, not a serial console. Credentials come only from `ALKANE_BOARD_PASSWORD` or diff --git a/crates/alkane-artifacts/src/afw.rs b/crates/alkane-artifacts/src/afw.rs index 96314ab8..9856721b 100644 --- a/crates/alkane-artifacts/src/afw.rs +++ b/crates/alkane-artifacts/src/afw.rs @@ -18,6 +18,28 @@ pub const BLOCK: usize = 512; pub const MAX_ARCHIVE: usize = 512 * 1024 * 1024; pub const MAX_MANIFEST: usize = 64 * 1024; pub const CV1835_P1_SIZE: u64 = 16 * 1024 * 1024; +pub const AM335X_HOLE_OFFSET: u64 = 0x780000; +pub const AM335X_HOLE_SIZE: u64 = 0x80000; +pub const AM335X_CHIP_SIZE: u64 = 0x8000000; +const AM335X_MAP: &[(&str, u64, u64, bool, bool, i64, Option<&str>)] = &[ + ("mtd0", 0x0000000, 0x20000, true, true, 0, None), + ("mtd1", 0x0020000, 0x20000, true, true, 0, None), + ("mtd2", 0x0040000, 0x20000, true, true, 0, None), + ("mtd3", 0x0060000, 0x20000, true, true, 0, None), + ("mtd4", 0x0080000, 0x1C0000, true, true, 0, None), + ("mtd5", 0x0240000, 0x20000, true, true, 0, None), + ("mtd6", 0x0260000, 0x20000, false, true, 2, Some("dtb")), + ("mtd7", 0x0280000, 0x500000, false, true, 3, Some("kernel")), + ("mtd8", 0x0800000, 0x1400000, false, true, 1, Some("rootfs")), + ("mtd9", 0x1C00000, 0x200000, true, false, 0, None), + ("mtd10", 0x1E00000, 0x200000, true, false, 0, None), + ("mtd11", 0x2000000, 0x6000000, true, false, 0, None), +]; +const AM335X_CEILINGS: &[(&str, u64, &str)] = &[ + ("kernel", 0x500000, "mtd7"), + ("dtb", 0x20000, "mtd6"), + ("rootfs", 0x1400000, "mtd8"), +]; const IMAGE_ROLES: &[&str] = &["kernel", "dtb", "rootfs", "bootloader", "boot", "component"]; const IMAGE_FORMATS: &[&str] = &["fit", "arm64-image", "fdt", "cpio-gzip", "uimage", "raw"]; @@ -48,11 +70,12 @@ pub struct BoardProfile { /// in this table is refused rather than treated as generic. pub fn board_profile(board: &str) -> Option { let (arch, bootloader_policy) = match board { + "am335x" => ("arm", BootloaderPolicy::Preserve), "cv1835" => ("arm64", BootloaderPolicy::Preserve), "zynq-7010" => ("armv7", BootloaderPolicy::Preserve), "a113d" => ("armv7", BootloaderPolicy::Preserve), "a113d-s21pro" => ("armv7", BootloaderPolicy::Preserve), - "am335x-bb" => ("armv7", BootloaderPolicy::Include), + "am335x-bb" => ("armv7", BootloaderPolicy::Preserve), "zynq-s17" => ("armv7", BootloaderPolicy::Include), _ => return None, }; @@ -509,6 +532,10 @@ fn validate_manifest(manifest: &AfwManifest, options: &VerifyOptions) -> Result< } } + if manifest.board == "am335x" { + validate_am335x(manifest)?; + } + let has_bootloader = manifest .images .iter() @@ -564,6 +591,101 @@ fn validate_manifest(manifest: &AfwManifest, options: &VerifyOptions) -> Result< Ok(()) } +fn validate_am335x(manifest: &AfwManifest) -> Result<(), AfwError> { + for image in &manifest.images { + let lowered = format!("{} {}", image.name, image.file).to_lowercase(); + if lowered.contains("spl") || lowered.contains("u-boot") || lowered.contains("uboot") { + return Err(AfwError::Manifest(format!( + "am335x bundle carries an spl/u-boot member: {}", + image.file + ))); + } + } + let install: Vec<&AfwImage> = manifest.images.iter().filter(|image| image.install).collect(); + if install.len() != 3 { + return Err(AfwError::Manifest( + "am335x must install exactly kernel, dtb and rootfs".to_owned(), + )); + } + for (name, ceiling, partition) in AM335X_CEILINGS { + let Some(image) = manifest.images.iter().find(|image| image.name == *name) else { + return Err(AfwError::Manifest(format!("am335x is missing {name}"))); + }; + let expected_format = if *name == "dtb" { "fdt" } else { "uimage" }; + if !image.install + || image.format != expected_format + || image.partition.as_deref() != Some(*partition) + { + return Err(AfwError::Manifest(format!( + "am335x {name} must be an installing {expected_format} for {partition}" + ))); + } + if image.size > *ceiling { + return Err(AfwError::ImageTooLarge(image.name.clone())); + } + } + if manifest.partitions.len() != AM335X_MAP.len() { + return Err(AfwError::Manifest( + "am335x must plan all 12 mtd partitions".to_owned(), + )); + } + for (name, offset, size, secure, boot_critical, write_order, image) in AM335X_MAP { + let Some(partition) = manifest.partitions.iter().find(|part| part.name == *name) else { + return Err(AfwError::Manifest(format!("am335x is missing {name}"))); + }; + if partition.offset != *offset + || partition.size != *size + || partition.secure != *secure + || partition.boot_critical != *boot_critical + || partition.write_order != *write_order + || partition.image.as_deref() != *image + || partition.device != format!("/dev/{name}") + { + return Err(AfwError::Manifest(format!( + "am335x {name} geometry is wrong" + ))); + } + if partition.offset < AM335X_HOLE_OFFSET + AM335X_HOLE_SIZE + && partition.offset + partition.size > AM335X_HOLE_OFFSET + { + return Err(AfwError::Manifest(format!( + "am335x {name} overlaps the 0x780000-0x800000 hole" + ))); + } + if (name.starts_with("mtd0") || ["mtd1", "mtd2", "mtd3", "mtd4", "mtd5"].contains(name)) + && (partition.write_order != 0 || partition.image.is_some()) + { + return Err(AfwError::Manifest(format!( + "am335x {name} is preserved and must not be written" + ))); + } + } + let mtd7 = manifest + .partitions + .iter() + .find(|part| part.name == "mtd7") + .unwrap(); + let mtd8 = manifest + .partitions + .iter() + .find(|part| part.name == "mtd8") + .unwrap(); + if mtd7.offset + mtd7.size != AM335X_HOLE_OFFSET + || mtd8.offset != AM335X_HOLE_OFFSET + AM335X_HOLE_SIZE + { + return Err(AfwError::Manifest( + "am335x mtd7 must end at the 0x780000 hole and mtd8 start at 0x800000".to_owned(), + )); + } + let total: u64 = manifest.partitions.iter().map(|part| part.size).sum(); + if total != AM335X_CHIP_SIZE - AM335X_HOLE_SIZE { + return Err(AfwError::Manifest( + "am335x partition sizes must sum to 0x7F80000".to_owned(), + )); + } + Ok(()) +} + fn check_image_format( manifest: &AfwManifest, image: &AfwImage, diff --git a/crates/alkane-cli/src/main.rs b/crates/alkane-cli/src/main.rs index fa3f3d65..2d1672c4 100644 --- a/crates/alkane-cli/src/main.rs +++ b/crates/alkane-cli/src/main.rs @@ -8,6 +8,9 @@ use alkane_artifacts::afw::{verify_afw, VerifiedAfw, VerifyOptions}; use alkane_artifacts::{seed_manifest, verify_file}; use alkane_core::platform; +use alkane_flash::boards::am335x::{ + self as am335x, Am335xPlan, AmInstallOptions, AmInstallOutcome, AmRestoreOptions, +}; use alkane_flash::boards::cv1835::Cv1835Plan; use alkane_flash::install::{ install, restore, verify_live, InstallOptions, InstallOutcome, RestoreOptions, @@ -313,6 +316,34 @@ fn run_plan(args: &[String]) -> Result<(), Box> { .first() .ok_or("usage: alkane-cli afw plan --host ")?; let verified = load_afw(path, &opts)?; + if verified.manifest.board == "am335x" { + let plan = Am335xPlan::from_afw(&verified)?; + let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; + let mut transport = SshTransport::connect(ssh, true)?; + let kernel = + String::from_utf8_lossy(&transport.user_command("uname -r", Duration::from_secs(15))?) + .trim() + .to_owned(); + let uid = + String::from_utf8_lossy(&transport.root_command("id -u", Duration::from_secs(15))?) + .trim() + .to_owned(); + let mtd = String::from_utf8_lossy(&transport.user_command( + "cat /proc/mtd 2>/dev/null", + Duration::from_secs(15), + )?) + .into_owned(); + println!("{}", plan.render()); + println!("current kernel {kernel} uid {uid}"); + println!("board mtd table:\n{mtd}"); + println!( + "root channel {} (transport {}, never serial)", + transport.root_method(), + transport.channel() + ); + println!("plan is read-only; no write performed"); + return Ok(()); + } let plan = Cv1835Plan::from_afw(&verified)?; let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; let mut transport = SshTransport::connect(ssh, true)?; @@ -357,9 +388,18 @@ fn run_preflight(args: &[String]) -> Result<(), Box> { .first() .ok_or("usage: alkane-cli afw preflight --host ")?; let verified = load_afw(path, &opts)?; - let plan = Cv1835Plan::from_afw(&verified)?; let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; let mut transport = SshTransport::connect(ssh, true)?; + if verified.manifest.board == "am335x" { + let plan = Am335xPlan::from_afw(&verified)?; + let report = am335x::preflight(&plan, &mut transport, opts.value("host").unwrap_or(""))?; + print!("{}", report.render()); + if !report.ok() { + return Err("preflight failed; do not write".into()); + } + return Ok(()); + } + let plan = Cv1835Plan::from_afw(&verified)?; let held_backup = opts.value("held-backup").map(PathBuf::from); let report = preflight( &plan, @@ -399,13 +439,57 @@ fn run_install(args: &[String]) -> Result<(), Box> { .first() .ok_or("usage: alkane-cli afw install --host --dry-run|--confirm FLASH")?; let verified = load_afw(path, &opts)?; - let plan = Cv1835Plan::from_afw(&verified)?; let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; let mut transport = SshTransport::connect(ssh, true)?; let backup_dir = opts .value("backup-dir") .map(PathBuf::from) .unwrap_or_else(|| platform::config_path("backups")); + if verified.manifest.board == "am335x" { + let plan = Am335xPlan::from_afw(&verified)?; + let install_options = AmInstallOptions { + dry_run: opts.flag("dry-run"), + confirm: opts.value("confirm").map(str::to_owned), + no_reboot: opts.flag("no-reboot"), + backup_dir, + }; + println!("{}", plan.render()); + match am335x::install( + &plan, + &mut transport, + &install_options, + opts.value("host").unwrap_or(""), + )? { + AmInstallOutcome::DryRun(report) => { + print!("{}", report.render()); + println!("DRY RUN: no board erase or write was performed."); + println!("Re-run with --confirm FLASH to write mtd8, mtd6 and mtd7."); + } + AmInstallOutcome::Installed(receipt) => { + for backup in &receipt.backups { + println!( + "held {} {} md5 {} sha256 {}", + backup.partition, + backup.path.display(), + backup.md5, + backup.sha256 + ); + } + println!("all three mtd read-backs matched before reboot"); + if receipt.rebooted { + println!("reboot issued; an SSH drop here is the success signature"); + println!( + "next: alkane-cli afw verify-live --host {} --timeout 300", + opts.value("host").unwrap_or("") + ); + } else { + println!("reboot skipped (--no-reboot); verify-live will fail until the board reboots"); + } + } + } + return Ok(()); + } + let plan = Cv1835Plan::from_afw(&verified)?; let install_options = InstallOptions { dry_run: opts.flag("dry-run"), confirm: opts.value("confirm").map(str::to_owned), @@ -455,26 +539,52 @@ fn run_verify_live(args: &[String]) -> Result<(), Box> { args, &[ ssh_values(), - &["marker", "kernel-version", "timeout", "expect-board"], + &["marker", "kernel-version", "timeout", "expect-board", "board"], ] .concat(), &["allow-unsigned"], )?; - let (marker, kernel_version) = if let Some(path) = opts.positionals.first() { + let requested_board = opts.value("board").map(str::to_owned); + let (board, marker, kernel_version) = if let Some(path) = opts.positionals.first() { let verified = load_afw(path, &opts)?; - let plan = Cv1835Plan::from_afw(&verified)?; - ( - opts.value("marker").unwrap_or(&plan.marker).to_owned(), - opts.value("kernel-version") - .unwrap_or(&plan.kernel_version) - .to_owned(), - ) + let board = verified.manifest.board.clone(); + if board == "am335x" { + let plan = Am335xPlan::from_afw(&verified)?; + ( + board, + opts.value("marker").unwrap_or(&plan.marker).to_owned(), + opts.value("kernel-version") + .unwrap_or(&plan.kernel_version) + .to_owned(), + ) + } else { + let plan = Cv1835Plan::from_afw(&verified)?; + ( + board, + opts.value("marker").unwrap_or(&plan.marker).to_owned(), + opts.value("kernel-version") + .unwrap_or(&plan.kernel_version) + .to_owned(), + ) + } } else { + let board = requested_board.clone().unwrap_or_else(|| "cv1835".to_owned()); + let (marker, kernel) = if board == "am335x" { + ("Alkane".to_owned(), "6.18.48".to_owned()) + } else { + ("CVBOOT".to_owned(), String::new()) + }; ( - opts.value("marker").unwrap_or("CVBOOT").to_owned(), - opts.value("kernel-version").unwrap_or("").to_owned(), + board, + opts.value("marker").unwrap_or(&marker).to_owned(), + opts.value("kernel-version").unwrap_or(&kernel).to_owned(), ) }; + if let Some(expected) = &requested_board { + if expected != &board { + return Err(format!("bundle is for {board}, expected {expected}").into()); + } + } let host = opts.value("host").ok_or("--host is required")?.to_owned(); let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; let timeout = opts @@ -482,6 +592,20 @@ fn run_verify_live(args: &[String]) -> Result<(), Box> { .map(str::parse::) .transpose()? .unwrap_or(DEFAULT_TIMEOUT); + if board == "am335x" { + let report = am335x::verify_live( + &host, + &marker, + &kernel_version, + Duration::from_secs(timeout), + &ssh, + ); + print!("{}", report.render()); + if !report.ok() { + return Err("live verification failed: SSH, HTTP marker, API or DHCP disagreed".into()); + } + return Ok(()); + } let report = verify_live( &host, &marker, @@ -500,11 +624,54 @@ fn run_verify_live(args: &[String]) -> Result<(), Box> { fn run_restore(args: &[String]) -> Result<(), Box> { let opts = parse_args( args, - &[ssh_values(), &["held-backup", "backup-dir", "confirm"]].concat(), + &[ + ssh_values(), + &["held-backup", "backup-dir", "confirm", "board", "held-kernel", "held-dtb"], + ] + .concat(), &["no-reboot"], )?; let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?; let mut transport = SshTransport::connect(ssh, true)?; + if opts.value("board") == Some("am335x") { + let dir = opts + .value("backup-dir") + .map(PathBuf::from) + .unwrap_or_else(|| platform::config_path("backups")); + let mut backups: Vec<(String, PathBuf)> = Vec::new(); + for (name, value, prefix) in [ + ("mtd8", opts.value("held-backup"), "mtd8-"), + ("mtd7", opts.value("held-kernel"), "mtd7-"), + ("mtd6", opts.value("held-dtb"), "mtd6-"), + ] { + let path = match value { + Some(path) => PathBuf::from(path), + None => latest_backup_for(&dir, prefix).ok_or_else(|| { + format!( + "no held {name} backup in {}; pass the matching --held-* option", + dir.display() + ) + })?, + }; + backups.push((name.to_owned(), path)); + } + let receipt = am335x::restore( + &backups, + &mut transport, + &AmRestoreOptions { + confirm: opts.value("confirm").map(str::to_owned), + no_reboot: opts.flag("no-reboot"), + }, + )?; + for (name, path) in &receipt.restored { + println!("restored {name} from {}", path.display()); + } + println!("all mtd read-backs matched before reboot"); + if receipt.rebooted { + println!("reboot issued; the board should return to its held OS"); + } + return Ok(()); + } let backup = if let Some(path) = opts.value("held-backup") { PathBuf::from(path) } else { @@ -536,6 +703,23 @@ fn run_restore(args: &[String]) -> Result<(), Box> { Ok(()) } +fn latest_backup_for(dir: &Path, prefix: &str) -> Option { + let mut entries: Vec = fs::read_dir(dir) + .ok()? + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| { + path.extension() == Some(std::ffi::OsStr::new("img")) + && path + .file_name() + .map(|name| name.to_string_lossy().starts_with(prefix)) + .unwrap_or(false) + }) + .collect(); + entries.sort(); + entries.pop() +} + fn latest_backup(dir: &Path) -> Option { let mut entries: Vec = fs::read_dir(dir) .ok()? @@ -604,8 +788,9 @@ fn run() -> Result<(), Box> { alkane-cli afw preflight --host [ssh options] [--held-backup ]\n \ alkane-cli afw install --host --dry-run [ssh options]\n \ alkane-cli afw install --host --confirm FLASH [ssh options]\n \ - alkane-cli afw verify-live [] --host [--timeout ] [ssh options]\n \ - alkane-cli afw restore --host --held-backup --confirm FLASH [ssh options]\n\ + alkane-cli afw verify-live [] --host [--board ] [--timeout ] [ssh options]\n \ + alkane-cli afw restore --host --held-backup --confirm FLASH [ssh options]\n \ + alkane-cli afw restore --board am335x --host --held-backup \\\n --held-kernel --held-dtb --confirm FLASH [ssh options]\n\ \nssh options: --user --port --identity-file --password-file --known-hosts \ --root-method auto|direct|update-daemon|rroot --update-daemon-port\n\ credentials: ALKANE_BOARD_PASSWORD or ALKANE_BOARD_PASSWORD_FILE; \ diff --git a/crates/alkane-flash/src/boards/am335x.rs b/crates/alkane-flash/src/boards/am335x.rs new file mode 100644 index 00000000..f9b85393 --- /dev/null +++ b/crates/alkane-flash/src/boards/am335x.rs @@ -0,0 +1,1677 @@ +// SPDX-License-Identifier: MIT +//! AM335x board module: legacy uImage update of mtd7 + mtd8 (+ mtd6 dtb). +//! +//! mtd0-5 (SPL, U-Boot, bootenv) are preserved and are never write targets. +//! Every offset comes from the 12-partition map, including the 512 KiB hole at +//! 0x780000-0x800000; it is never derived by summing partition sizes. The +//! board boots a legacy ARM uImage, not a FIT. + +use crate::install::{api_version, http_get}; +use crate::md5::md5_hex; +use crate::preflight::{classify, parse_digest}; +use crate::transport::{Remote, RemoteError, SshOptions, SshTransport}; +use alkane_artifacts::afw::{ + AfwImage, AfwManifest, AfwPartition, BootloaderPolicy, VerifiedAfw, +}; +use serde_json::json; +use sha2::{Digest, Sha256}; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; +use thiserror::Error; + +pub const BOARD: &str = "am335x"; +pub const ARCH: &str = "arm"; +pub const MARKER: &str = "Alkane"; +pub const HOLE_OFFSET: u64 = 0x780000; +pub const HOLE_SIZE: u64 = 0x80000; +pub const CHIP_SIZE: u64 = 0x8000000; + +pub const MTD_MAP: [(&str, u64, u64, bool, bool, i64, Option<&str>); 12] = [ + ("mtd0", 0x0000000, 0x20000, true, true, 0, None), + ("mtd1", 0x0020000, 0x20000, true, true, 0, None), + ("mtd2", 0x0040000, 0x20000, true, true, 0, None), + ("mtd3", 0x0060000, 0x20000, true, true, 0, None), + ("mtd4", 0x0080000, 0x1C0000, true, true, 0, None), + ("mtd5", 0x0240000, 0x20000, true, true, 0, None), + ("mtd6", 0x0260000, 0x20000, false, true, 2, Some("dtb")), + ("mtd7", 0x0280000, 0x500000, false, true, 3, Some("kernel")), + ("mtd8", 0x0800000, 0x1400000, false, true, 1, Some("rootfs")), + ("mtd9", 0x1C00000, 0x200000, true, false, 0, None), + ("mtd10", 0x1E00000, 0x200000, true, false, 0, None), + ("mtd11", 0x2000000, 0x6000000, true, false, 0, None), +]; + +const PRESERVE: [&str; 6] = ["mtd0", "mtd1", "mtd2", "mtd3", "mtd4", "mtd5"]; +const TARGET_IMAGES: [(&str, &str, u64); 3] = [ + ("mtd8", "rootfs", 0x1400000), + ("mtd6", "dtb", 0x20000), + ("mtd7", "kernel", 0x500000), +]; + +#[derive(Debug, Error)] +pub enum AmPlanError { + #[error("bundle is for {0}, not am335x")] + WrongBoard(String), + #[error("bundle arch is {0}, am335x needs arm")] + WrongArch(String), + #[error("am335x requires bootloader_policy preserve")] + BootloaderPolicy, + #[error("am335x bundle carries a bootloader member")] + BootloaderMember, + #[error("am335x bundle carries an spl/u-boot member: {0}")] + SplUbootMember(String), + #[error("manifest is not an OS payload")] + PayloadType, + #[error("manifest marker is empty")] + Marker, + #[error("manifest kernel_version is empty")] + KernelVersion, + #[error("am335x must install exactly kernel, dtb and rootfs")] + InstallCount, + #[error("am335x is missing the {0} image")] + MissingImage(String), + #[error("am335x {image} format is {actual}, expected {expected}")] + ImageFormat { + image: String, + actual: String, + expected: &'static str, + }, + #[error("am335x {image} is {size} bytes, over the 0x{ceiling:x}-byte mtd ceiling")] + ImageTooLarge { + image: String, + size: u64, + ceiling: u64, + }, + #[error("am335x partition {0} geometry is wrong")] + PartitionGeometry(String), + #[error("am335x partition {0} overlaps the 0x780000-0x800000 hole")] + Hole(String), + #[error("am335x {0} is preserved and must not be written")] + PreservedTarget(String), + #[error("am335x {0} is not a legacy ARM uImage")] + UImage(String), + #[error("am335x {image} is a type-{actual} uImage, expected type {expected}")] + UImageType { + image: String, + actual: u8, + expected: u8, + }, + #[error("am335x mtd7 must end at the 0x780000 hole and mtd8 must start at 0x800000")] + HoleBoundary, + #[error("am335x partition sizes must sum to 0x7F80000")] + MapSize, + #[error("manifest preflight is missing {0}")] + Preflight(String), +} + +#[derive(Clone, Debug)] +pub struct AmTarget { + pub image: AfwImage, + pub data: Vec, + pub partition: AfwPartition, + pub expected_md5: String, + pub expected_sha256: String, +} + +#[derive(Clone, Debug)] +pub struct Am335xPlan { + pub targets: Vec, + pub partitions: Vec, + pub marker: String, + pub kernel_version: String, + pub sdk_revision: String, + pub os_revision: String, + pub source_os: Vec, + pub required_commands: Vec, + pub min_free_bytes: u64, + pub afw_sha256: String, +} + +impl Am335xPlan { + pub fn from_afw(afw: &VerifiedAfw) -> Result { + let manifest = &afw.manifest; + if manifest.board != BOARD { + return Err(AmPlanError::WrongBoard(manifest.board.clone())); + } + if manifest.arch != ARCH { + return Err(AmPlanError::WrongArch(manifest.arch.clone())); + } + if manifest.payload_type != "os" { + return Err(AmPlanError::PayloadType); + } + if manifest.bootloader_policy != BootloaderPolicy::Preserve { + return Err(AmPlanError::BootloaderPolicy); + } + if manifest + .images + .iter() + .any(|image| image.role == "bootloader") + { + return Err(AmPlanError::BootloaderMember); + } + for image in &manifest.images { + let lowered = format!("{} {}", image.name, image.file).to_lowercase(); + if lowered.contains("spl") || lowered.contains("u-boot") || lowered.contains("uboot") { + return Err(AmPlanError::SplUbootMember(image.file.clone())); + } + } + if manifest.marker.is_empty() { + return Err(AmPlanError::Marker); + } + if manifest.kernel_version.is_empty() { + return Err(AmPlanError::KernelVersion); + } + + let install: Vec<&AfwImage> = manifest + .images + .iter() + .filter(|image| image.install) + .collect(); + if install.len() != 3 { + return Err(AmPlanError::InstallCount); + } + + validate_partitions(&manifest.partitions)?; + + let mut targets = Vec::with_capacity(3); + for (partition_name, image_name, ceiling) in TARGET_IMAGES { + let image = manifest + .images + .iter() + .find(|image| image.name == image_name) + .ok_or_else(|| AmPlanError::MissingImage(image_name.to_owned()))?; + if !image.install { + return Err(AmPlanError::MissingImage(image_name.to_owned())); + } + let expected_format = if image_name == "dtb" { "fdt" } else { "uimage" }; + if image.format != expected_format { + return Err(AmPlanError::ImageFormat { + image: image_name.to_owned(), + actual: image.format.clone(), + expected: expected_format, + }); + } + if image.partition.as_deref() != Some(partition_name) { + return Err(AmPlanError::PartitionGeometry(partition_name.to_owned())); + } + if image.size > ceiling { + return Err(AmPlanError::ImageTooLarge { + image: image_name.to_owned(), + size: image.size, + ceiling, + }); + } + let partition = manifest + .partitions + .iter() + .find(|part| part.name == partition_name) + .ok_or_else(|| AmPlanError::PartitionGeometry(partition_name.to_owned()))? + .clone(); + let data = afw + .image(image_name) + .map(|(_, data)| data) + .ok_or_else(|| AmPlanError::MissingImage(image_name.to_owned()))?; + if image.format == "uimage" { + check_uimage(image_name, data)?; + } else if data.len() < 4 || !data.starts_with(b"\xd0\x0d\xfe\xed") { + return Err(AmPlanError::ImageFormat { + image: image_name.to_owned(), + actual: "non-fdt".to_owned(), + expected: "fdt", + }); + } + targets.push(AmTarget { + expected_md5: md5_hex(data), + expected_sha256: image.sha256.clone(), + image: image.clone(), + data: data.to_vec(), + partition, + }); + } + targets.sort_by_key(|target| target.partition.write_order); + + Ok(Self { + targets, + partitions: manifest.partitions.clone(), + marker: manifest.marker.clone(), + kernel_version: manifest.kernel_version.clone(), + sdk_revision: manifest.sdk_revision.clone(), + os_revision: manifest.os_revision.clone(), + source_os: json_strings(&manifest.preflight, "source_os"), + required_commands: json_strings(&manifest.preflight, "required_commands"), + min_free_bytes: manifest + .preflight + .get("min_free_bytes") + .and_then(|value| value.as_u64()) + .unwrap_or(32 * 1024 * 1024), + afw_sha256: afw.archive_sha256.clone(), + }) + } + + pub fn render(&self) -> String { + let mut out = String::new(); + out.push_str("board am335x arch arm\n"); + out.push_str(&format!( + "bootloader preserve (mtd0-5 SPL/U-Boot/bootenv kept, never written)\n" + )); + out.push_str(&format!( + "image format legacy-uimage (kernel type 2, ramdisk type 3), never FIT\n" + )); + out.push_str(&format!( + "nand hole 0x{:x}-0x{:x} (never written)\n", + HOLE_OFFSET, + HOLE_OFFSET + HOLE_SIZE + )); + for target in &self.targets { + out.push_str(&format!( + "write {} {} offset 0x{:x} size 0x{:x} <= 0x{:x} image {} {} B sha256 {}\n", + target.partition.name, + target.partition.device, + target.partition.offset, + target.partition.size, + target.partition.size, + target.image.name, + target.image.size, + target.image.sha256, + )); + } + out.push_str(&format!( + "marker {} kernel {} sdk {} os {}", + self.marker, + self.kernel_version, + short_revision(&self.sdk_revision), + short_revision(&self.os_revision), + )); + out + } +} + +fn validate_partitions(partitions: &[AfwPartition]) -> Result<(), AmPlanError> { + if partitions.len() != MTD_MAP.len() { + return Err(AmPlanError::MapSize); + } + for (name, offset, size, secure, boot_critical, write_order, image) in MTD_MAP { + let part = partitions + .iter() + .find(|part| part.name == name) + .ok_or_else(|| AmPlanError::PartitionGeometry(name.to_owned()))?; + if part.offset != offset + || part.size != size + || part.secure != secure + || part.boot_critical != boot_critical + || part.write_order != write_order + || part.image.as_deref() != image + || part.device != format!("/dev/{name}") + { + return Err(AmPlanError::PartitionGeometry(name.to_owned())); + } + if part.offset < HOLE_OFFSET + HOLE_SIZE && part.offset + part.size > HOLE_OFFSET { + return Err(AmPlanError::Hole(name.to_owned())); + } + if PRESERVE.contains(&name) && (part.write_order != 0 || part.image.is_some()) { + return Err(AmPlanError::PreservedTarget(name.to_owned())); + } + } + let mtd7 = partitions.iter().find(|part| part.name == "mtd7").unwrap(); + let mtd8 = partitions.iter().find(|part| part.name == "mtd8").unwrap(); + if mtd7.offset + mtd7.size != HOLE_OFFSET || mtd8.offset != HOLE_OFFSET + HOLE_SIZE { + return Err(AmPlanError::HoleBoundary); + } + let total: u64 = partitions.iter().map(|part| part.size).sum(); + if total != CHIP_SIZE - HOLE_SIZE { + return Err(AmPlanError::MapSize); + } + Ok(()) +} + +fn check_uimage(name: &str, data: &[u8]) -> Result<(), AmPlanError> { + if data.len() < 64 || !data.starts_with(b"\x27\x05\x19\x56") { + return Err(AmPlanError::UImage(name.to_owned())); + } + if data[29] != 2 { + return Err(AmPlanError::UImage(name.to_owned())); + } + let expected = if name == "rootfs" { 3 } else { 2 }; + if data[30] != expected { + return Err(AmPlanError::UImageType { + image: name.to_owned(), + actual: data[30], + expected, + }); + } + Ok(()) +} + +fn short_revision(revision: &str) -> &str { + revision.get(..12).unwrap_or(revision) +} + +fn json_strings(value: &serde_json::Value, key: &str) -> Vec { + value + .get(key) + .and_then(|item| item.as_array()) + .map(|items| { + items + .iter() + .filter_map(|item| item.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() +} + +pub fn manifest_from_json(value: serde_json::Value) -> Result { + serde_json::from_value(value) +} + +#[derive(Clone, Debug)] +pub struct AmCheck { + pub name: String, + pub ok: bool, + pub detail: String, +} + +#[derive(Clone, Debug)] +pub struct AmTargetState { + pub name: String, + pub device: String, + pub size: u64, + pub live_md5: String, +} + +#[derive(Clone, Debug)] +pub struct AmPreflightReport { + pub host: String, + pub source_os: String, + pub kernel: String, + pub model: String, + pub root_method: String, + pub root_uid: String, + pub free_bytes: u64, + pub targets: Vec, + pub checks: Vec, +} + +impl AmPreflightReport { + pub fn ok(&self) -> bool { + self.checks.iter().all(|check| check.ok) + } + + pub fn render(&self) -> String { + let mut out = String::new(); + out.push_str(&format!("preflight {}\n", self.host)); + out.push_str(&format!( + "source-os {} (kernel {})\n", + self.source_os, self.kernel + )); + if !self.model.is_empty() { + out.push_str(&format!("model {}\n", self.model)); + } + out.push_str(&format!( + "root {} (uid {})\n", + self.root_method, self.root_uid + )); + for target in &self.targets { + out.push_str(&format!( + "target {} {} {} B live md5 {}\n", + target.name, target.device, target.size, target.live_md5 + )); + } + out.push_str(&format!( + "free tmp {} MiB\n", + self.free_bytes / (1024 * 1024) + )); + out.push_str("preserved mtd0-5: never erased and never written\n"); + for check in &self.checks { + out.push_str(&format!( + "check {} {}: {}\n", + check.name, + if check.ok { "ok" } else { "FAIL" }, + check.detail + )); + } + out.push_str(if self.ok() { + "result PASS\n" + } else { + "result FAIL (do not write)\n" + }); + out + } +} + +#[derive(Debug, Error)] +pub enum AmError { + #[error("preflight failed; do not write\n{0}")] + Preflight(String), + #[error("install and restore need --confirm FLASH")] + Confirm, + #[error("am335x plan: {0}")] + Plan(#[from] AmPlanError), + #[error("remote: {0}")] + Remote(#[from] RemoteError), + #[error("I/O: {0}")] + Io(#[from] std::io::Error), + #[error("cannot read an mtd backup: {0}")] + Backup(String), + #[error("{0} backup is {1} bytes, expected {2}")] + BackupSize(String, u64, u64), + #[error("{0} backup md5 differs from the live mtd; nothing written for it")] + BackupMismatch(String), + #[error("{0} staged image md5 differs from the verified bundle")] + StageMismatch(String), + #[error("{0} read-back md5 mismatch; do not reboot. Restore with: {1}")] + Readback(String, String), + #[error("held backup {0} is not one of mtd6/mtd7/mtd8")] + BadRestoreTarget(String), + #[error("refusing to write preserved partition {0}")] + PreservedTarget(String), + #[error("restore read-back mismatch for {0}; the board may still hold new data")] + RestoreReadback(String), +} + +pub fn preflight( + plan: &Am335xPlan, + remote: &mut dyn Remote, + host: &str, +) -> Result { + let mut checks = Vec::new(); + let fingerprint = remote.user_command( + "uname -r; echo __MODEL__; cat /proc/device-tree/model 2>/dev/null; echo; \ + echo __RELEASE__; cat /etc/os-release 2>/dev/null; \ + ls /etc/alkane-release /etc/ouros-release /etc/bos_version /etc/fw-info 2>/dev/null", + Duration::from_secs(20), + )?; + let text = String::from_utf8_lossy(&fingerprint).into_owned(); + let mut sections = text.split("__MODEL__"); + let kernel = sections.next().unwrap_or("").trim().to_owned(); + let rest = sections.next().unwrap_or(""); + let mut sections = rest.split("__RELEASE__"); + let model = sections.next().unwrap_or("").trim().to_owned(); + let release = sections.next().unwrap_or(""); + let source_os = classify(&kernel, release, &text); + let source_ok = plan.source_os.is_empty() + || plan.source_os.iter().any(|item| item == &source_os); + checks.push(AmCheck { + name: "source-os".to_owned(), + ok: source_ok, + detail: format!( + "{source_os} (allowed: {})", + if plan.source_os.is_empty() { + "any".to_owned() + } else { + plan.source_os.join(", ") + } + ), + }); + + let root_uid = + String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?) + .trim() + .to_owned(); + checks.push(AmCheck { + name: "root".to_owned(), + ok: root_uid == "0", + detail: format!("uid {root_uid}"), + }); + + let mtd_text = String::from_utf8_lossy(&remote.user_command( + "cat /proc/mtd 2>/dev/null", + Duration::from_secs(20), + )?) + .into_owned(); + let mtd = parse_proc_mtd(&mtd_text); + let map_ok = MTD_MAP.iter().all(|(name, _, size, ..)| { + mtd.get(*name) + .map(|entry: &(u64, String)| entry.0 == *size && entry.1 == *name) + .unwrap_or(false) + }); + checks.push(AmCheck { + name: "mtd-map".to_owned(), + ok: map_ok, + detail: if map_ok { + "12 partitions match the captured map".to_owned() + } else { + format!("partition table differs: {mtd_text}") + }, + }); + + let commands = remote.user_command( + "for c in /usr/sbin/flash_erase /usr/sbin/nandwrite /usr/sbin/nanddump \ + md5sum sync; do command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done", + Duration::from_secs(15), + )?; + let commands_text = String::from_utf8_lossy(&commands).into_owned(); + let missing: Vec<&str> = commands_text + .lines() + .filter_map(|line| line.strip_prefix("missing:")) + .collect(); + checks.push(AmCheck { + name: "commands".to_owned(), + ok: missing.is_empty(), + detail: if missing.is_empty() { + "/usr/sbin/flash_erase, /usr/sbin/nandwrite, /usr/sbin/nanddump, md5sum, sync present".to_owned() + } else { + format!("missing {}", missing.join(", ")) + }, + }); + + let free = free_bytes(remote)?; + checks.push(AmCheck { + name: "free-space".to_owned(), + ok: free >= plan.min_free_bytes, + detail: format!( + "{} MiB at /tmp (plan {} MiB)", + free / (1024 * 1024), + plan.min_free_bytes / (1024 * 1024) + ), + }); + + let mut targets = Vec::new(); + for target in &plan.targets { + let name = target.partition.name.clone(); + let device = target.partition.device.clone(); + let block = String::from_utf8_lossy(&remote.user_command( + &format!("test -c {device} && echo char || echo missing"), + Duration::from_secs(15), + )?) + .trim() + .to_owned(); + let live_md5 = live_target_md5(remote, &name, &device, target.partition.size)?; + checks.push(AmCheck { + name: format!("target-{name}"), + ok: block == "char" && live_md5.len() == 32, + detail: format!("{device} {block} live md5 {live_md5}"), + }); + targets.push(AmTargetState { + name, + device, + size: target.partition.size, + live_md5, + }); + } + + let preserve_ok = plan + .partitions + .iter() + .filter(|part| PRESERVE.contains(&part.name.as_str())) + .all(|part| part.write_order == 0 && part.image.is_none() && part.secure); + checks.push(AmCheck { + name: "preserve-mtd0-5".to_owned(), + ok: preserve_ok, + detail: "mtd0-5 are secure, image-free and outside the write order".to_owned(), + }); + + Ok(AmPreflightReport { + host: host.to_owned(), + source_os, + kernel, + model, + root_method: remote.root_method().to_owned(), + root_uid, + free_bytes: free, + targets, + checks, + }) +} + +fn parse_proc_mtd(text: &str) -> std::collections::HashMap { + let mut result = std::collections::HashMap::new(); + for line in text.lines() { + let Some((index, rest)) = line.split_once(':') else { + continue; + }; + let mut fields = rest.split_whitespace(); + let Some(size) = fields.next().and_then(|value| u64::from_str_radix(value, 16).ok()) + else { + continue; + }; + let label = fields + .next_back() + .unwrap_or("") + .trim_matches('"') + .to_owned(); + result.insert(index.trim().to_owned(), (size, label)); + } + result +} + +fn live_target_md5( + remote: &mut dyn Remote, + name: &str, + device: &str, + size: u64, +) -> Result { + let probe = format!("/tmp/.alkane-probe-{name}.img"); + remote.root_command( + &format!( + "/usr/sbin/nanddump --omitoob --bb=skipbad --length={size} -f {probe} {device}" + ), + Duration::from_secs(180), + )?; + let output = remote.root_command( + &format!("md5sum {probe}"), + Duration::from_secs(60), + )?; + let _ = remote.root_command(&format!("rm -f {probe}"), Duration::from_secs(15)); + Ok(parse_digest(&output, 32).unwrap_or_else(|| "unreadable".to_owned())) +} + +fn free_bytes(remote: &mut dyn Remote) -> Result { + let out = remote.user_command("df -k /tmp 2>/dev/null || df -k /", Duration::from_secs(15))?; + let text = String::from_utf8_lossy(&out); + for line in text.lines().rev() { + let fields: Vec<&str> = line.split_whitespace().collect(); + if fields.len() >= 4 { + if let Ok(kib) = fields[3].parse::() { + return Ok(kib.saturating_mul(1024)); + } + } + } + Ok(0) +} + +#[derive(Clone, Debug)] +pub struct AmInstallOptions { + pub dry_run: bool, + pub confirm: Option, + pub no_reboot: bool, + pub backup_dir: PathBuf, +} + +impl Default for AmInstallOptions { + fn default() -> Self { + Self { + dry_run: false, + confirm: None, + no_reboot: false, + backup_dir: alkane_core::platform::config_path("backups"), + } + } +} + +#[derive(Clone, Debug)] +pub struct AmBackup { + pub partition: String, + pub device: String, + pub path: PathBuf, + pub md5: String, + pub sha256: String, + pub size: u64, +} + +#[derive(Clone, Debug)] +pub struct AmInstallReceipt { + pub backups: Vec, + pub rebooted: bool, +} + +#[derive(Clone, Debug)] +pub enum AmInstallOutcome { + DryRun(Box), + Installed(AmInstallReceipt), +} + +pub fn install( + plan: &Am335xPlan, + remote: &mut dyn Remote, + options: &AmInstallOptions, + host: &str, +) -> Result { + let report = preflight(plan, remote, host)?; + if !report.ok() { + return Err(AmError::Preflight(report.render())); + } + if options.dry_run { + return Ok(AmInstallOutcome::DryRun(Box::new(report))); + } + if options.confirm.as_deref() != Some("FLASH") { + return Err(AmError::Confirm); + } + fs::create_dir_all(&options.backup_dir)?; + let epoch = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let mut backups = Vec::new(); + for target in &plan.targets { + let name = &target.partition.name; + let device = &target.partition.device; + let live_md5 = report + .targets + .iter() + .find(|state| &state.name == name) + .map(|state| state.live_md5.clone()) + .unwrap_or_else(|| "unreadable".to_owned()); + let remote_backup = format!("/tmp/.alkane-{name}-backup.img"); + remote.root_command( + &format!( + "/usr/sbin/nanddump --omitoob --bb=skipbad --length={} -f {remote_backup} {device}", + target.partition.size + ), + Duration::from_secs(300), + )?; + let local = options + .backup_dir + .join(format!("{name}-{epoch}.img")); + remote.pull(&remote_backup, &local, Duration::from_secs(300))?; + let _ = remote.root_command(&format!("rm -f {remote_backup}"), Duration::from_secs(15)); + let data = fs::read(&local)?; + if data.len() as u64 != target.partition.size { + return Err(AmError::BackupSize( + name.clone(), + data.len() as u64, + target.partition.size, + )); + } + let md5 = md5_hex(&data); + if live_md5.len() == 32 && md5 != live_md5 { + return Err(AmError::BackupMismatch(name.clone())); + } + let sha256: String = Sha256::digest(&data) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + write_sidecars( + &local, + name, + device, + target.partition.size, + &md5, + &sha256, + &plan.afw_sha256, + epoch, + )?; + backups.push(AmBackup { + partition: name.clone(), + device: device.clone(), + path: local, + md5, + sha256, + size: target.partition.size, + }); + + // Stage the verified payload, prove its remote md5, then erase and write. + let mut staged = tempfile::NamedTempFile::new()?; + staged.write_all(&target.data)?; + staged.flush()?; + let remote_stage = format!("/tmp/.alkane-{name}-stage.img"); + remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?; + let staged_md5 = remote.root_command( + &format!("md5sum {remote_stage}"), + Duration::from_secs(60), + )?; + let staged_md5 = parse_digest(&staged_md5, 32).unwrap_or_default(); + if staged_md5 != target.expected_md5 { + let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15)); + return Err(AmError::StageMismatch(name.clone())); + } + remote.root_command( + &format!("/usr/sbin/flash_erase {device} 0 0"), + Duration::from_secs(300), + )?; + remote.root_command( + &format!("/usr/sbin/nandwrite -p {device} {remote_stage} && sync"), + Duration::from_secs(300), + )?; + let remote_readback = format!("/tmp/.alkane-{name}-readback.img"); + remote.root_command( + &format!( + "/usr/sbin/nanddump --omitoob --bb=skipbad --length={} -f {remote_readback} {device}", + target.image.size + ), + Duration::from_secs(300), + )?; + let readback = remote.root_command( + &format!("md5sum {remote_readback}"), + Duration::from_secs(60), + )?; + let readback = parse_digest(&readback, 32).unwrap_or_default(); + let _ = remote.root_command( + &format!("rm -f {remote_stage} {remote_readback}"), + Duration::from_secs(15), + ); + if readback != target.expected_md5 { + return Err(AmError::Readback( + name.clone(), + restore_hint(&backups, name), + )); + } + } + + let rebooted = if options.no_reboot { + false + } else { + remote.reboot()?; + true + }; + Ok(AmInstallOutcome::Installed(AmInstallReceipt { + backups, + rebooted, + })) +} + +fn restore_hint(backups: &[AmBackup], failed: &str) -> String { + let mut text = format!( + "alkane-cli afw restore --board am335x --host --held-backup " + ); + for backup in backups { + let flag = match backup.partition.as_str() { + "mtd8" => "--held-backup", + "mtd7" => "--held-kernel", + "mtd6" => "--held-dtb", + _ => "--held-backup", + }; + text.push_str(&format!( + " {} {}", + flag, + backup.path.display() + )); + } + if !backups.iter().any(|backup| backup.partition == failed) { + text.push_str(&format!(" (no backup of {failed} exists)")); + } + text +} + +fn read_sha_sidecar(path: &Path) -> Option { + let text = fs::read_to_string(path.with_extension("img.sha256")).ok()?; + text.split_whitespace() + .next() + .filter(|value| value.len() == 64) + .map(str::to_owned) +} + +fn write_sidecars( + path: &Path, + partition: &str, + device: &str, + size: u64, + md5: &str, + sha256: &str, + afw_sha256: &str, + epoch: u64, +) -> Result<(), AmError> { + let file_name = path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| format!("{partition}.img")); + fs::write( + path.with_extension("img.sha256"), + format!("{sha256} {file_name}\n"), + )?; + let metadata = json!({ + "board": "am335x", + "partition": partition, + "device": device, + "size": size, + "md5": md5, + "sha256": sha256, + "afw_sha256": afw_sha256, + "created_unix": epoch, + }); + fs::write( + path.with_extension("img.json"), + serde_json::to_vec_pretty(&metadata).unwrap_or_default(), + )?; + Ok(()) +} + +#[derive(Clone, Debug)] +pub struct AmRestoreOptions { + pub confirm: Option, + pub no_reboot: bool, +} + +#[derive(Clone, Debug)] +pub struct AmRestoreReceipt { + pub restored: Vec<(String, PathBuf)>, + pub rebooted: bool, +} + +pub fn restore( + backups: &[(String, PathBuf)], + remote: &mut dyn Remote, + options: &AmRestoreOptions, +) -> Result { + if options.confirm.as_deref() != Some("FLASH") { + return Err(AmError::Confirm); + } + if backups.is_empty() { + return Err(AmError::Backup("no held mtd backup was named".to_owned())); + } + let mut ordered = backups.to_vec(); + ordered.sort_by_key(|(name, _)| { + MTD_MAP + .iter() + .find(|(mtd, ..)| mtd == name) + .map(|(_, _, _, _, _, write_order, _)| *write_order) + .unwrap_or(i64::MAX) + }); + for (name, path) in &ordered { + let (_, _, size, ..) = MTD_MAP + .iter() + .find(|(mtd, ..)| mtd == name) + .ok_or_else(|| AmError::BadRestoreTarget(name.clone()))?; + if PRESERVE.contains(&name.as_str()) { + return Err(AmError::PreservedTarget(name.clone())); + } + if *size == 0 { + return Err(AmError::BadRestoreTarget(name.clone())); + } + let data = fs::read(path)?; + if data.len() as u64 != *size { + return Err(AmError::BackupSize( + name.clone(), + data.len() as u64, + *size, + )); + } + let md5 = md5_hex(&data); + let sha256: String = Sha256::digest(&data) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + if let Some(expected) = read_sha_sidecar(path) { + if expected != sha256 { + return Err(AmError::BackupMismatch(name.clone())); + } + } + let device = format!("/dev/{name}"); + let remote_stage = format!("/tmp/.alkane-{name}-restore.img"); + remote.push(path, &remote_stage, Duration::from_secs(300))?; + let staged = remote.root_command( + &format!("md5sum {remote_stage}"), + Duration::from_secs(60), + )?; + if parse_digest(&staged, 32).unwrap_or_default() != md5 { + let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15)); + return Err(AmError::StageMismatch(name.clone())); + } + remote.root_command( + &format!("/usr/sbin/flash_erase {device} 0 0"), + Duration::from_secs(300), + )?; + remote.root_command( + &format!("/usr/sbin/nandwrite -p {device} {remote_stage} && sync"), + Duration::from_secs(300), + )?; + let remote_readback = format!("/tmp/.alkane-{name}-restore-readback.img"); + remote.root_command( + &format!( + "/usr/sbin/nanddump --omitoob --bb=skipbad --length={size} -f {remote_readback} {device}" + ), + Duration::from_secs(300), + )?; + let readback = remote.root_command( + &format!("md5sum {remote_readback}"), + Duration::from_secs(60), + )?; + let _ = remote.root_command( + &format!("rm -f {remote_stage} {remote_readback}"), + Duration::from_secs(15), + ); + if parse_digest(&readback, 32).unwrap_or_default() != md5 { + return Err(AmError::RestoreReadback(name.clone())); + } + } + let rebooted = if options.no_reboot { + false + } else { + remote.reboot()?; + true + }; + Ok(AmRestoreReceipt { + restored: ordered, + rebooted, + }) +} + +#[derive(Clone, Debug)] +pub struct AmLiveReport { + pub attempts: u32, + pub http: String, + pub http_ok: bool, + pub ssh: String, + pub ssh_ok: bool, + pub api: String, + pub api_ok: bool, + pub dhcp: String, + pub dhcp_ok: bool, +} + +impl AmLiveReport { + pub fn ok(&self) -> bool { + self.http_ok && self.ssh_ok && self.api_ok && self.dhcp_ok + } + + pub fn render(&self) -> String { + format!( + "verify-live attempts {}\n http {}: {}\n ssh {}: {}\n api {}: {}\n dhcp {}: {}\nresult {}", + self.attempts, + if self.http_ok { "ok" } else { "FAIL" }, + self.http, + if self.ssh_ok { "ok" } else { "FAIL" }, + self.ssh, + if self.api_ok { "ok" } else { "FAIL" }, + self.api, + if self.dhcp_ok { "ok" } else { "FAIL" }, + self.dhcp, + if self.ok() { "PASS" } else { "FAIL" } + ) + } +} + +pub fn verify_live( + host: &str, + marker: &str, + kernel_version: &str, + timeout: Duration, + ssh_options: &SshOptions, +) -> AmLiveReport { + let deadline = Instant::now() + timeout; + let mut attempts = 0; + loop { + attempts += 1; + let (http, http_ok) = match http_get(host, "/", Duration::from_secs(5)) { + Ok(body) => { + let ok = body.contains(marker); + ( + if ok { + format!("marker {marker} present") + } else { + format!("marker {marker} absent ({} bytes)", body.len()) + }, + ok, + ) + } + Err(error) => (error, false), + }; + let (ssh, ssh_ok, dhcp, dhcp_ok) = match SshTransport::connect(ssh_options.clone(), false) + { + Ok(mut session) => { + let ssh = match session.user_command("uname -r", Duration::from_secs(15)) { + Ok(output) => { + let kernel = String::from_utf8_lossy(&output).trim().to_owned(); + let ok = !kernel.is_empty() + && (kernel_version.is_empty() || kernel.contains(kernel_version)); + ( + format!("kernel {kernel}"), + ok, + ) + } + Err(error) => (format!("{error}"), false), + }; + let dhcp = match session.user_command( + "cat /var/run/udhcpc.eth0.lease 2>/dev/null; echo __ADDR__; \ + ip -4 addr show eth0 2>/dev/null", + Duration::from_secs(15), + ) { + Ok(output) => check_dhcp(&String::from_utf8_lossy(&output)), + Err(error) => (format!("{error}"), false), + }; + (ssh.0, ssh.1, dhcp.0, dhcp.1) + } + Err(error) => (format!("{error}"), false, format!("{error}"), false), + }; + let (api, api_ok) = match api_version(host, Duration::from_secs(5)) { + Ok(body) => { + let ok = body.contains("\"STATUS\"") + || body.contains("\"VERSION\"") + || body.to_lowercase().contains("version"); + (format!("{} bytes", body.len()), ok) + } + Err(error) => (error, false), + }; + if http_ok && ssh_ok && api_ok && dhcp_ok { + return AmLiveReport { + attempts, + http, + http_ok, + ssh, + ssh_ok, + api, + api_ok, + dhcp, + dhcp_ok, + }; + } + if Instant::now() >= deadline { + return AmLiveReport { + attempts, + http, + http_ok, + ssh, + ssh_ok, + api, + api_ok, + dhcp, + dhcp_ok, + }; + } + std::thread::sleep(Duration::from_secs(5)); + } +} + +fn check_dhcp(output: &str) -> (String, bool) { + let mut lease_ip = None; + let mut in_addr = false; + for line in output.lines() { + if line == "__ADDR__" { + in_addr = true; + continue; + } + if !in_addr { + if let Some(ip) = line.strip_prefix("ip=") { + lease_ip = Some(ip.trim().to_owned()); + } + } else { + if let Some(ip) = line + .split_whitespace() + .skip_while(|field| *field != "inet") + .nth(1) + { + let ip = ip.split('/').next().unwrap_or(ip); + if !ip.is_empty() && !ip.starts_with("169.254.") { + return ( + format!( + "lease {} bound to {}", + lease_ip.unwrap_or_else(|| "eth0".to_owned()), + ip + ), + true, + ); + } + } + } + } + if let Some(ip) = lease_ip { + if !ip.is_empty() && !ip.starts_with("169.254.") && output.contains(&ip) { + return (format!("lease ip {ip}"), true); + } + } + ("no completed DHCP lease on eth0".to_owned(), false) +} + +#[cfg(test)] +mod tests { + use super::*; + use alkane_artifacts::afw::AfwMember; + use serde_json::json; + use sha2::{Digest, Sha256}; + + const REV: &str = "0000000000000000000000000000000000000000"; + + fn uimage(kind: u8, payload: &[u8]) -> Vec { + let mut header = vec![0_u8; 64]; + header[..4].copy_from_slice(b"\x27\x05\x19\x56"); + header[12..16].copy_from_slice(&(payload.len() as u32).to_be_bytes()); + header[29] = 2; + header[30] = kind; + header[31] = if kind == 3 { 1 } else { 0 }; + header[32..45].copy_from_slice(b"alkane-am335x"); + let mut data = header; + data.extend_from_slice(payload); + data + } + + fn dtb() -> Vec { + let mut data = vec![0_u8; 256]; + data[..4].copy_from_slice(b"\xd0\x0d\xfe\xed"); + data + } + + fn sha_hex(data: &[u8]) -> String { + Sha256::digest(data) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() + } + + fn partition(name: &str, device: &str, offset: u64, size: u64, secure: bool, + boot_critical: bool, write_order: i64, image: Option<&str>) -> AfwPartition { + AfwPartition { + name: name.to_owned(), + device: device.to_owned(), + offset, + size, + secure, + boot_critical, + write_order, + image: image.map(str::to_owned), + } + } + + fn manifest_value(kernel: &[u8], dtb_data: &[u8], rootfs: &[u8]) -> serde_json::Value { + let partitions = MTD_MAP + .iter() + .map(|(name, offset, size, secure, boot_critical, write_order, image)| { + partition(name, &format!("/dev/{name}"), *offset, *size, *secure, + *boot_critical, *write_order, *image) + }) + .collect::>(); + json!({ + "schema": 2, + "format": "afw", + "board": "am335x", + "arch": "arm", + "version": "0.1.0", + "build_date": "2026-11-04T00:00:00Z", + "sdk_revision": REV, + "os_revision": REV, + "payload_type": "os", + "bootloader_policy": "preserve", + "signature": {"type": "unsigned", "member": null, "public_key_hex": null}, + "partitions": partitions, + "images": [ + {"name": "kernel", "file": "payload/alkane-am335x.uImage", + "role": "kernel", "format": "uimage", "size": kernel.len(), + "sha256": sha_hex(kernel), "partition": "mtd7", "install": true}, + {"name": "dtb", "file": "payload/am335x-alkane.dtb", + "role": "dtb", "format": "fdt", "size": dtb_data.len(), + "sha256": sha_hex(dtb_data), "partition": "mtd6", "install": true}, + {"name": "rootfs", "file": "payload/alkane-am335x-ramdisk.uImage", + "role": "rootfs", "format": "uimage", "size": rootfs.len(), + "sha256": sha_hex(rootfs), "partition": "mtd8", "install": true} + ], + "boot_switch": {"method": "preserved-u-boot-go"}, + "preflight": {"required_commands": ["flash_erase", "nandwrite", "nanddump", "md5sum", "sync"], + "source_os": ["alkane", "ouros", "braiins"], + "min_free_bytes": 33554432}, + "recovery": {"network": "afw restore", "held_partition": "mtd8"}, + "marker": "Alkane", + "kernel_version": "6.18.48" + }) + } + + fn afw(kernel: &[u8], dtb_data: &[u8], rootfs: &[u8]) -> VerifiedAfw { + let manifest = manifest_from_json(manifest_value(kernel, dtb_data, rootfs)).unwrap(); + VerifiedAfw { + manifest, + members: vec![ + AfwMember { + name: "payload/alkane-am335x.uImage".to_owned(), + data: kernel.to_vec(), + }, + AfwMember { + name: "payload/am335x-alkane.dtb".to_owned(), + data: dtb_data.to_vec(), + }, + AfwMember { + name: "payload/alkane-am335x-ramdisk.uImage".to_owned(), + data: rootfs.to_vec(), + }, + ], + manifest_sha256: "0".repeat(64), + archive_sha256: "0".repeat(64), + } + } + + fn good() -> (Vec, Vec, Vec) { + (uimage(2, b"kernel"), dtb(), uimage(3, b"ramdisk")) + } + + #[test] + fn accepts_a_good_plan_and_orders_writes_root_dtb_kernel() { + let (kernel, dtb_data, rootfs) = good(); + let plan = Am335xPlan::from_afw(&afw(&kernel, &dtb_data, &rootfs)).unwrap(); + assert_eq!(plan.targets.len(), 3); + assert_eq!(plan.targets[0].partition.name, "mtd8"); + assert_eq!(plan.targets[1].partition.name, "mtd6"); + assert_eq!(plan.targets[2].partition.name, "mtd7"); + assert!(plan.render().contains("mtd0-5")); + assert_eq!(plan.targets[2].expected_md5, md5_hex(&kernel)); + } + + #[test] + fn refuses_wrong_board_arch_policy_and_bootloader() { + let (kernel, dtb_data, rootfs) = good(); + let mut verified = afw(&kernel, &dtb_data, &rootfs); + verified.manifest.board = "cv1835".to_owned(); + assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::WrongBoard(_)))); + + let mut verified = afw(&kernel, &dtb_data, &rootfs); + verified.manifest.arch = "armv7".to_owned(); + assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::WrongArch(_)))); + + let mut verified = afw(&kernel, &dtb_data, &rootfs); + verified.manifest.bootloader_policy = BootloaderPolicy::Include; + assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::BootloaderPolicy))); + + let mut verified = afw(&kernel, &dtb_data, &rootfs); + verified.manifest.images[0].role = "bootloader".to_owned(); + assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::BootloaderMember))); + } + + #[test] + fn refuses_an_spl_or_u_boot_member_under_preserve() { + let (kernel, dtb_data, rootfs) = good(); + let mut verified = afw(&kernel, &dtb_data, &rootfs); + verified.manifest.images.push(AfwImage { + name: "u-boot".to_owned(), + file: "payload/u-boot.img".to_owned(), + role: "component".to_owned(), + format: "uimage".to_owned(), + size: 4, + sha256: "0".repeat(64), + partition: None, + install: false, + }); + assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::SplUbootMember(_)))); + } + + #[test] + fn refuses_a_preserved_mtd4_write_target() { + let (kernel, dtb_data, rootfs) = good(); + let mut verified = afw(&kernel, &dtb_data, &rootfs); + let part = verified + .manifest + .partitions + .iter_mut() + .find(|part| part.name == "mtd4") + .unwrap(); + part.write_order = 1; + part.image = Some("kernel".to_owned()); + part.secure = false; + assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::PartitionGeometry(_)))); + } + + #[test] + fn refuses_a_partition_in_the_hole() { + let (kernel, dtb_data, rootfs) = good(); + let mut verified = afw(&kernel, &dtb_data, &rootfs); + let part = verified + .manifest + .partitions + .iter_mut() + .find(|part| part.name == "mtd8") + .unwrap(); + part.offset = HOLE_OFFSET; + assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::PartitionGeometry(_)))); + } + + #[test] + fn refuses_oversize_kernel_and_root() { + let (kernel, dtb_data, rootfs) = good(); + let mut verified = afw(&kernel, &dtb_data, &rootfs); + verified.manifest.images[0].size = 0x500001; + assert!(matches!( + Am335xPlan::from_afw(&verified), + Err(AmPlanError::ImageTooLarge { .. }) + )); + let mut verified = afw(&kernel, &dtb_data, &rootfs); + verified.manifest.images[2].size = 0x1400001; + assert!(matches!( + Am335xPlan::from_afw(&verified), + Err(AmPlanError::ImageTooLarge { .. }) + )); + } + + #[test] + fn refuses_a_ramdisk_that_is_not_type_3() { + let (kernel, dtb_data, _) = good(); + let rootfs = uimage(2, b"wrong-type"); + let error = Am335xPlan::from_afw(&afw(&kernel, &dtb_data, &rootfs)).unwrap_err(); + assert!(matches!(error, AmPlanError::UImageType { expected: 3, .. })); + } + + struct MockRemote { + partitions: std::collections::HashMap>, + files: std::collections::HashMap>, + commands: Vec, + writes: Vec, + rebooted: bool, + readback_corrupt: Option, + } + + impl MockRemote { + fn new(_data_size: usize) -> Self { + let mut partitions = std::collections::HashMap::new(); + for (name, _, size, ..) in MTD_MAP { + partitions.insert(name.to_owned(), vec![0x11_u8; size as usize]); + } + Self { + partitions, + files: std::collections::HashMap::new(), + commands: Vec::new(), + writes: Vec::new(), + rebooted: false, + readback_corrupt: None, + } + } + } + + impl Remote for MockRemote { + fn channel(&self) -> &str { + "mock" + } + fn root_method(&self) -> &'static str { + "direct" + } + fn user_command(&mut self, command: &str, _: Duration) -> Result, RemoteError> { + self.commands.push(command.to_owned()); + let text = if command.contains("uname -r") { + "6.18.48\n__MODEL__\nBitmain AM335x\n__RELEASE__\n/etc/alkane-release\n" + .to_owned() + } else if command.contains("cat /proc/mtd") { + MTD_MAP + .iter() + .enumerate() + .map(|(index, (name, _, size, ..))| { + format!("mtd{index}: {:08x} 00020000 \"{name}\"\n", size) + }) + .collect() + } else if command.contains("for c in /usr/sbin/flash_erase") { + "flash_erase\nnandwrite\nnanddump\nmd5sum\nsync\n".to_owned() + } else if command.contains("df -k") { + "Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/root 100000 1 90000 1% /tmp\n".to_owned() + } else if command.contains("test -c") { + "char".to_owned() + } else { + String::new() + }; + Ok(text.into_bytes()) + } + fn root_command(&mut self, command: &str, _: Duration) -> Result, RemoteError> { + self.commands.push(command.to_owned()); + if command == "id -u" { + return Ok(b"0\n".to_vec()); + } + if command.contains("nanddump --omitoob") { + let path = command + .split(" -f ") + .nth(1) + .and_then(|rest| rest.split_whitespace().next()) + .unwrap_or("") + .to_owned(); + let device = command.split_whitespace().last().unwrap_or("").to_owned(); + let name = device.trim_start_matches("/dev/"); + let mut data = self.partitions.get(name).cloned().unwrap_or_default(); + if let Some(length) = command + .split("--length=") + .nth(1) + .and_then(|rest| rest.split_whitespace().next()) + .and_then(|value| value.parse::().ok()) + { + data.truncate(length); + } + if command.contains("readback") + && self.readback_corrupt.as_deref() == Some(name) + { + if let Some(last) = data.last_mut() { + *last ^= 0xff; + } + self.readback_corrupt = None; + } + self.files.insert(path, data); + return Ok(Vec::new()); + } + if command.starts_with("md5sum ") { + let path = command + .trim_start_matches("md5sum ") + .split_whitespace() + .next() + .unwrap_or(""); + let data = self.files.get(path).cloned().unwrap_or_default(); + return Ok(format!("{} {path}\n", md5_hex(&data)).into_bytes()); + } + if command.contains("flash_erase /dev/") { + let name = command + .split_whitespace() + .nth(1) + .unwrap_or("") + .trim_start_matches("/dev/") + .to_owned(); + if let Some(data) = self.partitions.get_mut(&name) { + data.fill(0xff); + } + return Ok(Vec::new()); + } + if command.contains("nandwrite -p /dev/") { + let mut fields = command.split_whitespace(); + let _ = fields.next(); + let _ = fields.next(); + let device = fields.next().unwrap_or(""); + let stage = fields.next().unwrap_or(""); + let name = device.trim_start_matches("/dev/").to_owned(); + self.writes.push(name.clone()); + let data = self.files.get(stage).cloned().unwrap_or_default(); + if let Some(partition) = self.partitions.get_mut(&name) { + let length = data.len().min(partition.len()); + partition[..length].copy_from_slice(&data[..length]); + } + return Ok(Vec::new()); + } + if command.starts_with("rm -f ") { + for path in command.trim_start_matches("rm -f ").split_whitespace() { + self.files.remove(path); + } + return Ok(Vec::new()); + } + Ok(Vec::new()) + } + fn push(&mut self, local: &Path, remote: &str, _: Duration) -> Result<(), RemoteError> { + self.files.insert(remote.to_owned(), fs::read(local)?); + Ok(()) + } + fn pull(&mut self, remote: &str, local: &Path, _: Duration) -> Result<(), RemoteError> { + let data = self + .files + .get(remote) + .cloned() + .ok_or_else(|| RemoteError::Daemon("missing file".to_owned()))?; + fs::write(local, data)?; + Ok(()) + } + fn reboot(&mut self) -> Result<(), RemoteError> { + self.rebooted = true; + Ok(()) + } + } + + fn test_plan() -> (Am335xPlan, MockRemote) { + let (kernel, dtb_data, rootfs) = good(); + let plan = Am335xPlan::from_afw(&afw(&kernel, &dtb_data, &rootfs)).unwrap(); + (plan, MockRemote::new(0x20000)) + } + + #[test] + fn installs_three_targets_with_a_held_backup_and_readback_before_reboot() { + let (plan, mut remote) = test_plan(); + let temp = tempfile::tempdir().unwrap(); + let options = AmInstallOptions { + dry_run: false, + confirm: Some("FLASH".to_owned()), + no_reboot: true, + backup_dir: temp.path().to_path_buf(), + }; + let outcome = install(&plan, &mut remote, &options, "10.255.1.64").unwrap(); + let AmInstallOutcome::Installed(receipt) = outcome else { + panic!("expected an install"); + }; + assert_eq!(receipt.backups.len(), 3); + assert_eq!(remote.writes, vec!["mtd8", "mtd6", "mtd7"]); + assert!(!remote.rebooted); + for name in ["mtd8", "mtd6", "mtd7"] { + assert!(receipt + .backups + .iter() + .any(|backup| backup.partition == name && backup.path.is_file())); + } + let first_write = remote + .commands + .iter() + .position(|command| command.contains("nandwrite -p ")) + .unwrap(); + let first_backup = remote + .commands + .iter() + .position(|command| command.contains("nanddump --omitoob") && command.contains("backup")) + .unwrap(); + assert!(first_backup < first_write); + } + + #[test] + fn dry_run_never_erases_or_writes() { + let (plan, mut remote) = test_plan(); + let temp = tempfile::tempdir().unwrap(); + let options = AmInstallOptions { + dry_run: true, + confirm: None, + no_reboot: false, + backup_dir: temp.path().to_path_buf(), + }; + let outcome = install(&plan, &mut remote, &options, "10.255.1.64").unwrap(); + assert!(matches!(outcome, AmInstallOutcome::DryRun(_))); + assert!(!remote + .commands + .iter() + .any(|command| command.contains("flash_erase /dev/") + || command.contains("nandwrite -p "))); + } + + #[test] + fn a_readback_mismatch_stops_before_reboot() { + let (plan, mut remote) = test_plan(); + remote.readback_corrupt = Some("mtd7".to_owned()); + let temp = tempfile::tempdir().unwrap(); + let options = AmInstallOptions { + dry_run: false, + confirm: Some("FLASH".to_owned()), + no_reboot: false, + backup_dir: temp.path().to_path_buf(), + }; + let result = install(&plan, &mut remote, &options, "10.255.1.64"); + assert!(matches!(result, Err(AmError::Readback(_, _)))); + assert!(!remote.rebooted); + } + + #[test] + fn accepts_a_bound_dhcp_lease_and_rejects_link_local() { + let bound = "interface=eth0\nip=10.255.1.64\nmask=255.255.255.0\n\ + router=10.255.1.1\n__ADDR__\n2: eth0: \n inet 10.255.1.64/24 brd 10.255.1.255 scope global eth0\n"; + let (detail, ok) = check_dhcp(bound); + assert!(ok, "{detail}"); + let missing = "interface=eth0\n__ADDR__\n2: eth0: \n inet 169.254.1.2/16 brd 169.254.255.255 scope global eth0\n"; + let (_, ok) = check_dhcp(missing); + assert!(!ok); + } + + #[test] + fn refuses_a_restore_into_a_preserved_mtd() { + let mut remote = MockRemote::new(0x20000); + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("mtd4.img"); + fs::write(&path, vec![0_u8; 0x1C0000]).unwrap(); + let result = restore( + &[("mtd4".to_owned(), path)], + &mut remote, + &AmRestoreOptions { + confirm: Some("FLASH".to_owned()), + no_reboot: true, + }, + ); + assert!(matches!(result, Err(AmError::PreservedTarget(_)))); + assert!(remote.writes.is_empty()); + } +} diff --git a/crates/alkane-flash/src/boards/mod.rs b/crates/alkane-flash/src/boards/mod.rs index 37d9db02..57638ceb 100644 --- a/crates/alkane-flash/src/boards/mod.rs +++ b/crates/alkane-flash/src/boards/mod.rs @@ -2,4 +2,5 @@ //! Board modules. Each module validates the verified manifest for its family //! and exposes the exact write plan the installer follows. +pub mod am335x; pub mod cv1835; diff --git a/crates/alkane-flash/src/install.rs b/crates/alkane-flash/src/install.rs index bae9c9eb..8d7937df 100644 --- a/crates/alkane-flash/src/install.rs +++ b/crates/alkane-flash/src/install.rs @@ -480,7 +480,7 @@ pub fn verify_live( } } -fn http_get(host: &str, path: &str, timeout: Duration) -> Result { +pub(crate) fn http_get(host: &str, path: &str, timeout: Duration) -> Result { let address = (host, 80_u16) .to_socket_addrs() .map_err(|error| format!("resolve: {error}"))? @@ -524,7 +524,7 @@ fn http_get(host: &str, path: &str, timeout: Duration) -> Result } } -fn api_version(host: &str, timeout: Duration) -> Result { +pub(crate) fn api_version(host: &str, timeout: Duration) -> Result { let address = (host, 4028_u16) .to_socket_addrs() .map_err(|error| format!("resolve: {error}"))? diff --git a/crates/alkane-flash/src/preflight.rs b/crates/alkane-flash/src/preflight.rs index f9be22c5..729328f3 100644 --- a/crates/alkane-flash/src/preflight.rs +++ b/crates/alkane-flash/src/preflight.rs @@ -341,7 +341,7 @@ pub fn preflight( }) } -fn classify(kernel: &str, release: &str, all: &str) -> String { +pub(crate) fn classify(kernel: &str, release: &str, all: &str) -> String { if all.contains("/etc/bos_version") || release.contains("Braiins") { return "braiins".to_owned(); }