Compare commits

..
12 Commits
Author SHA1 Message Date
noah 1fa4aa5532 Merge pull request 'next: find Alkane OS boards in the scan; install/update/uninstall only where they apply' (#35) from feature/alkane-scan into next
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 16m28s
verify / verify-windows (pull_request) Successful in 9m18s
next-build / windows (push) Successful in 4m21s
next-build / candidate (push) Successful in 19m23s
2026-11-12 15:13:17 -07:00
noahandClaude Opus 5.5 315c595714 gui: find boards running Alkane OS in the scan; offer install/update/uninstall only where they apply
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 7m17s
The fleet scan (asic-rs) recognises miners by their cgminer socket or vendor
web UI. A board running Alkane OS exposes neither, so it never appeared and
could not be right-clicked; the periodic refresh also marked it offline.

- alkane_detect: probe addresses asic-rs does not identify over HTTP:
  GET /api/identity (alkane-os 0.1.2+: os, version, board, MAC, hostname),
  falling back to /api/summary's "alkane-os" STATUS for older images. Used by
  the scan and the refresh. Rows show Firmware "Alkane" with the version, MAC,
  hostname and control board (XIL (C49) for zynq-7010).
- Context menu: "Install alkane OS..." only for a supported board (control
  board alkane-os has an image for; a stock Antminer on XIL (C49), or by model
  S17/S17 Pro/T17 when the stock miner software is down and reports no board)
  that is not running Alkane; "Update alkane OS..." for a supported board
  already running it (same dialog, updated in place); "Uninstall alkane OS"
  only for boards running Alkane. Mixed selections get neither install nor
  update.
- Docs updated.

Verified live on the bench S17: running Alkane -> found as Alkane 0.1.2,
XIL (C49), update + uninstall offered; restored to stock -> found as Antminer
S17 Stock, install offered. Unit tests for the probe parsing and the menu
rules; an ignored live scan test (ALKANE_TEST_SCAN_RANGE).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-12 16:01:40 -06:00
noah 50102800a3 Merge pull request 'main: promote next (alkane-os install/uninstall, genuine-firmware restore, Zynq fixes)' (#32) from next into main
build-test-release / windows (push) Successful in 7m25s
build-test-release / release (push) Successful in 19m26s
2026-11-12 13:11:50 -07:00
noah a998d7a3e3 Merge pull request 'next: ignore the curl-dependent asset-fetch test on Windows' (#34) from feature/afw-os-bundle into next
next-build / windows (push) Successful in 5m12s
next-build / candidate (push) Successful in 5m12s
verify / verify (pull_request) Successful in 11m50s
source / check (pull_request) Skipped
verify / verify-windows (pull_request) Successful in 6m55s
2026-11-12 12:51:54 -07:00
noahandClaude Opus 5.5 cd02ff47a5 test: ignore the curl-dependent asset-fetch test on Windows
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 4m15s
stock_method's fetch test shells out to curl. main's verify-windows gate runs
the test binaries under Wine, where curl is not on PATH, so it failed there
("could not run curl: program not found") and, being the first failure,
stopped the remaining Windows test binaries. Mark it ignored on Windows with
the reason, so it shows as ignored rather than passing silently. Locally under
Wine all headless crates' Windows tests pass; Windows-target clippy is clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-12 13:47:20 -06:00
noah 836a531e93 Merge pull request 'next: update the PR change-surface self-test for the GUI's new dependencies' (#33) from feature/afw-os-bundle into next
source / check (pull_request) Skipped
verify / verify (pull_request) Successful in 11m22s
verify / verify-windows (pull_request) Failing after 7m5s
next-build / windows (push) Failing after 7s
next-build / candidate (push) Skipped
2026-11-12 12:24:50 -07:00
noahandClaude Opus 5.5 8d72f07cf0 ci: update the PR change-surface self-test for the GUI's new dependencies
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 5m16s
alkane-gui now depends on alkane-flash and alkane-artifacts (right-click
install/uninstall, release picker), so a change in either reaches the GUI
graph and needs the full build. pr-surface.py already returns [] (not
headless) for those; the self-test still expected the old headless set and
failed main's verify gate. Pin the new graph: artifacts -> [], flash -> [],
access + flash -> [], access + cli -> [access, cli].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-12 13:18:58 -06:00
noah bdea96229b Merge pull request 'next: rustfmt the afw/stock work (no behaviour change)' (#31) from feature/afw-os-bundle into next
next-build / candidate (push) Successful in 4m56s
source / check (pull_request) Skipped
verify / verify (pull_request) Failing after 31s
next-build / windows (push) Successful in 4m11s
verify / verify-windows (pull_request) Skipped
2026-11-12 12:13:07 -07:00
noahandClaude Opus 5.5 d318b734fa style: rustfmt the afw/stock work (no behaviour change)
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 4m17s
main's verify gate runs cargo fmt --check on the first-party crates; next's
gate does not, so the afw/stock feature work reached next unformatted. Pure
cargo fmt output. clippy -D warnings (workspace and GUI) and all tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-12 13:01:21 -06:00
noah 4305da5e57 Merge pull request 'next: Zynq restore uses the factory device tree; tier-2 in-place update and verify-live for Zynq' (#30) from feature/afw-os-bundle into next
next-build / windows (push) Successful in 3m56s
next-build / candidate (push) Successful in 4m18s
Merge pull request #30: Zynq restore uses the factory device tree; tier-2 in-place update and verify-live for Zynq
2026-11-12 11:04:00 -07:00
noahandClaude Opus 5.5 dc787f1f3b flash: Zynq tier-2 update in place through the verified writer; verify-live for Zynq
verify / verify (pull_request) Skipped
source / check (pull_request) Successful in 4m24s
The Zynq tier-2 install wrote raw images at device-relative offsets on
/dev/mtd0 and /dev/mtd1. On the current alkane image those are stock-cfg and
alkane-cfg, not the boot regions, so it would have erased alkane-cfg first, and
its raw zImage/cpio are not bootable by the stock U-Boot. Its preflight only
checked that mtd0 and mtd1 existed.

- Add StockMethod::update_in_place: refuses a board not running alkane,
  re-registers the boot regions (as restore does), saves every slot locally
  before any erase, writes rootfs/dtb/kernel as the uImages the stock U-Boot
  boots via the shared target builder (BOOT.bin guard, md5 readback), reboots
  and waits for alkane. --dry-run reports the live storage map and the plan.
- boards::zynq keeps the manifest gate; the plan is now in absolute NAND slots
  with ceilings that leave room for the uImage header. The stale writer and
  preflight are removed.
- CLI: Zynq preflight/install use the new path before the generic user
  transport connects.
- verify-live gains a Zynq check (HTTP marker, case-insensitive, plus root SSH
  reporting alkane and the installed kernel; prints the kernel cmdline). It
  previously fell through to the CV1835 check.
- Tests for the protected alkane map, registered and split boot maps, slot
  overrun, and the BOOT.bin guard.

Verified on an S17 (Zynq-7010): dry run, install from a RAM-booted alkane,
NAND boot confirmed on the serial console, verify-live PASS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-12 11:49:53 -06:00
noahandClaude Opus 4.8 f63127d633 flash: restore uses the correct per-board device tree, not the package's
The kernel device tree is never in Bitmain's distributable firmware: all OTA
packages ship none, and the SD recovery image preserves the factory dtb rather
than writing one. The device tree I was taking from the SD recovery package was
its SD-boot dtb (a different partition layout), which does not match the genuine
rootfs and reboot-loops the board.

Fix: restore now takes only the genuine kernel + rootfs from the vendor package
(RestoreImages drops the dtb field), and the method supplies the correct
per-board device tree itself (fetched + verified from the public assets repo, the
same way the NAND-exposing helper is fetched). This pairs genuine kernel/rootfs
with the factory dtb that matches their partition layout. Any genuine package now
works (an OTA .tar.gz as well as an SD .zip), since the package's own dtb is no
longer needed.

cli/gui: --stock-firmware / the uninstall dialog no longer require a package with
a device tree. docs updated.

NOTE: not yet hardware-verified - the bench S17 is mid-recovery (serial-link
hardware issue) and must be brought back before this can be proven on the board.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-11 21:07:44 -06:00
17 changed files with 2065 additions and 768 deletions
+9 -4
View File
@@ -136,12 +136,17 @@ def main() -> None:
["README.md", "ci/pr-surface.py"]):
assert not pr_surface.documentation_only(paths), paths
assert pr_surface.headless_packages(["crates/alkane-cli/src/main.rs"]) == ["alkane-cli"]
assert pr_surface.headless_packages(["crates/alkane-artifacts/src/lib.rs"]) == [
"alkane-artifacts", "alkane-cli", "alkane-flash",
]
# alkane-gui depends on alkane-flash and alkane-artifacts (right-click
# install/uninstall and the release picker), so a change in either reaches
# the GUI graph and needs the full build: not a headless-only change.
assert pr_surface.headless_packages(["crates/alkane-artifacts/src/lib.rs"]) == []
assert pr_surface.headless_packages(["crates/alkane-flash/src/lib.rs"]) == []
assert pr_surface.headless_packages([
"crates/alkane-access/src/lib.rs", "crates/alkane-flash/tests/update.rs",
]) == ["alkane-access", "alkane-flash"]
]) == []
assert pr_surface.headless_packages([
"crates/alkane-access/src/lib.rs", "crates/alkane-cli/src/main.rs",
]) == ["alkane-access", "alkane-cli"]
for paths in ([], ["crates/alkane-core/src/lib.rs"],
["crates/alkane-discovery/src/lib.rs"],
["crates/alkane-gui/src/main.rs"],
+14 -2
View File
@@ -43,7 +43,15 @@ const AM335X_CEILINGS: &[(&str, u64, &str)] = &[
];
const IMAGE_ROLES: &[&str] = &["kernel", "dtb", "rootfs", "bootloader", "boot", "component"];
const IMAGE_FORMATS: &[&str] = &["fit", "arm64-image", "zimage", "fdt", "cpio-gzip", "uimage", "raw"];
const IMAGE_FORMATS: &[&str] = &[
"fit",
"arm64-image",
"zimage",
"fdt",
"cpio-gzip",
"uimage",
"raw",
];
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
@@ -607,7 +615,11 @@ fn validate_am335x(manifest: &AfwManifest) -> Result<(), AfwError> {
)));
}
}
let install: Vec<&AfwImage> = manifest.images.iter().filter(|image| image.install).collect();
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(),
+46 -12
View File
@@ -121,7 +121,10 @@ impl TokenConfig {
return Ok(Self { path: None });
};
let path = std::env::temp_dir().join(format!("alkane-fetch-{}.cfg", std::process::id()));
write_private(&path, &format!("header = \"Authorization: token {token}\"\n"))?;
write_private(
&path,
&format!("header = \"Authorization: token {token}\"\n"),
)?;
Ok(Self { path: Some(path) })
}
@@ -151,7 +154,8 @@ fn write_private(path: &Path, contents: &str) -> Result<(), FetchError> {
.mode(0o600)
.open(path)
.map_err(|e| FetchError::Io(e.to_string()))?;
file.write_all(contents.as_bytes()).map_err(|e| FetchError::Io(e.to_string()))
file.write_all(contents.as_bytes())
.map_err(|e| FetchError::Io(e.to_string()))
}
#[cfg(not(unix))]
@@ -179,7 +183,11 @@ fn curl_bytes(src: &ReleaseSource, url: &str) -> Result<Vec<u8>, FetchError> {
fn curl_download(src: &ReleaseSource, url: &str, dest: &Path) -> Result<(), FetchError> {
let config = TokenConfig::new(&src.token)?;
let mut cmd = Command::new("curl");
cmd.arg("-fsSL").arg("--max-time").arg("600").arg("-o").arg(dest);
cmd.arg("-fsSL")
.arg("--max-time")
.arg("600")
.arg("-o")
.arg(dest);
config.apply(&mut cmd);
cmd.arg(url);
let out = cmd.output().map_err(|e| FetchError::Curl(e.to_string()))?;
@@ -197,12 +205,17 @@ fn curl_download(src: &ReleaseSource, url: &str, dest: &Path) -> Result<(), Fetc
/// Scans the newest-first releases list (so a pre-release counts as latest).
pub fn latest_afw_asset(src: &ReleaseSource, board: &str) -> Result<(String, String), FetchError> {
let body = curl_bytes(src, &src.api_list())?;
let releases: Value = serde_json::from_slice(&body).map_err(|e| FetchError::Parse(e.to_string()))?;
let releases: Value =
serde_json::from_slice(&body).map_err(|e| FetchError::Parse(e.to_string()))?;
pick_asset(&releases, board).ok_or_else(|| FetchError::NoAsset(board.to_string()))
}
/// Download the latest `.afw` for `board` into `dest_dir`; returns its path.
pub fn fetch_latest_afw(src: &ReleaseSource, board: &str, dest_dir: &Path) -> Result<PathBuf, FetchError> {
pub fn fetch_latest_afw(
src: &ReleaseSource,
board: &str,
dest_dir: &Path,
) -> Result<PathBuf, FetchError> {
let (name, url) = latest_afw_asset(src, board)?;
fs::create_dir_all(dest_dir).map_err(|e| FetchError::Io(e.to_string()))?;
let dest = dest_dir.join(&name);
@@ -246,10 +259,24 @@ fn parse_releases(releases: &Value) -> Vec<ReleaseInfo> {
return out;
};
for release in arr {
let tag = release.get("tag_name").and_then(Value::as_str).unwrap_or("").to_string();
let name = release.get("name").and_then(Value::as_str).unwrap_or("").to_string();
let prerelease = release.get("prerelease").and_then(Value::as_bool).unwrap_or(false);
let draft = release.get("draft").and_then(Value::as_bool).unwrap_or(false);
let tag = release
.get("tag_name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let name = release
.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let prerelease = release
.get("prerelease")
.and_then(Value::as_bool)
.unwrap_or(false);
let draft = release
.get("draft")
.and_then(Value::as_bool)
.unwrap_or(false);
let published_at = release
.get("published_at")
.or_else(|| release.get("created_at"))
@@ -315,7 +342,9 @@ mod tests {
let src = ReleaseSource::alkane_os();
assert_eq!(src.owner, "blueflare");
assert_eq!(src.repo, "alkane-os");
assert!(src.api_list().contains("/api/v1/repos/blueflare/alkane-os/releases"));
assert!(src
.api_list()
.contains("/api/v1/repos/blueflare/alkane-os/releases"));
assert!(src.api_list().starts_with("https://gitea.bluefla.re"));
}
@@ -332,7 +361,10 @@ mod tests {
{"name": "alkane-os-0.0.9-zynq-7010-armv7.afw", "browser_download_url": "old"},
]},
]);
assert_eq!(pick_asset(&releases, "zynq-7010"), Some(("alkane-os-0.1.0-zynq-7010-armv7.afw".into(), "u2".into())));
assert_eq!(
pick_asset(&releases, "zynq-7010"),
Some(("alkane-os-0.1.0-zynq-7010-armv7.afw".into(), "u2".into()))
);
assert_eq!(pick_asset(&releases, "cv1835"), None);
}
@@ -357,7 +389,9 @@ mod tests {
assert_eq!(parsed[0].afw_assets.len(), 1);
// The board filter matches the -<board>- segment.
assert_eq!(
parsed[0].asset_for_board("zynq-7010").map(|a| a.url.as_str()),
parsed[0]
.asset_for_board("zynq-7010")
.map(|a| a.url.as_str()),
Some("z")
);
assert!(parsed[0].asset_for_board("am335x").is_none());
+211 -88
View File
@@ -7,21 +7,21 @@
use alkane_artifacts::afw::{verify_afw, VerifiedAfw, VerifyOptions};
use alkane_artifacts::fetch::{self, ReleaseSource};
use alkane_flash::stock;
use alkane_artifacts::{seed_manifest, verify_file};
use alkane_core::platform;
use alkane_flash::boards::a113d::{self, A113dInstallOptions, A113dOutcome, A113dPlan};
use alkane_flash::boards::am335x::{
self as am335x, Am335xPlan, AmInstallOptions, AmInstallOutcome, AmRestoreOptions,
};
use alkane_flash::boards::cv1835::Cv1835Plan;
use alkane_flash::boards::zynq::{self, ZynqInstallOptions, ZynqOutcome, ZynqPlan};
use alkane_flash::stock::RestoreImages;
use alkane_flash::stock_firmware;
use alkane_flash::boards::a113d::{self, A113dInstallOptions, A113dOutcome, A113dPlan};
use alkane_flash::boards::zynq::{self, ZynqPlan};
use alkane_flash::install::{
install, restore, verify_live, InstallOptions, InstallOutcome, RestoreOptions,
};
use alkane_flash::preflight::{preflight, PreflightOptions};
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 std::collections::{BTreeMap, BTreeSet};
use std::fs;
@@ -148,8 +148,8 @@ fn read_board_password(opts: &Opts) -> Result<Option<String>, Box<dyn std::error
let secret = resolve_password(opts)?;
match &secret.path {
Some(path) => {
let raw = fs::read_to_string(path)
.map_err(|e| format!("reading board password: {e}"))?;
let raw =
fs::read_to_string(path).map_err(|e| format!("reading board password: {e}"))?;
Ok(Some(raw.trim_end_matches(['\n', '\r']).to_string()))
}
None => Ok(None),
@@ -350,10 +350,9 @@ fn run_plan(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
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),
)?)
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}");
@@ -422,6 +421,28 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
.first()
.ok_or("usage: alkane-cli afw preflight <file> --host <ip>")?;
let verified = load_afw(path, &opts)?;
// Zynq is reached through the compiled-in method (root SSH, boot regions
// re-registered), not the generic user transport below.
if zynq::owns_board(&verified.manifest.board) {
let host = opts.value("host").ok_or("--host is required")?;
let plan = ZynqPlan::from_afw(&verified)?;
println!("{}", plan.render());
let password = read_board_password(&opts)?;
let options = InPlaceOptions {
dry_run: true,
reboot: false,
backup_dir: None,
};
match stock::update_in_place(host, &verified, password.as_deref(), &options) {
Ok(InPlaceOutcome::DryRun(report)) => print!("{report}"),
Ok(InPlaceOutcome::Updated(_)) => {
return Err("internal error: preflight reported a write".into())
}
Err(e) => return Err(format!("preflight failed; do not write: {e}").into()),
}
println!("preflight is read-only; no write performed");
return Ok(());
}
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
if am335x::owns_board(&verified.manifest.board) {
@@ -433,15 +454,6 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
}
return Ok(());
}
if zynq::owns_board(&verified.manifest.board) {
let plan = ZynqPlan::from_afw(&verified)?;
let report = zynq::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(());
}
if a113d::owns_board(&verified.manifest.board) {
let plan = A113dPlan::from_afw(&verified)?;
let report = a113d::preflight(&plan, &mut transport, opts.value("host").unwrap_or(""))?;
@@ -470,6 +482,63 @@ fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
/// Update a Zynq board that already runs alkane, in place, through the
/// compiled-in method: it re-registers the boot regions (not exposed to Linux on
/// alkane), keeps a copy of every slot before any erase, writes the kernel and
/// rootfs as the uImages the stock U-Boot boots, reads each back, and never
/// writes BOOT.bin. A board on stock is refused (use --from-stock).
fn install_zynq_in_place(
verified: &VerifiedAfw,
opts: &Opts,
) -> Result<(), Box<dyn std::error::Error>> {
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let plan = ZynqPlan::from_afw(verified)?;
println!("{}", plan.render());
let dry_run = opts.flag("dry-run");
if !dry_run && opts.value("confirm") != Some("FLASH") {
return Err("refusing to write without --confirm FLASH (use --dry-run to inspect)".into());
}
let backup_dir = opts
.value("backup-dir")
.map(PathBuf::from)
.unwrap_or_else(|| platform::config_path("backups"));
let password = read_board_password(opts)?;
let options = InPlaceOptions {
dry_run,
reboot: !opts.flag("no-reboot"),
backup_dir: Some(backup_dir),
};
match stock::update_in_place(&host, verified, password.as_deref(), &options)? {
InPlaceOutcome::DryRun(report) => {
print!("{report}");
println!("DRY RUN: no board erase or write was performed.");
println!(
"Re-run with --confirm FLASH to write rootfs, dtb and kernel (BOOT.bin preserved)."
);
}
InPlaceOutcome::Updated(receipt) => {
for held in &receipt.backups {
println!(
"held {} abs 0x{:x} ({} B) {} md5 {}",
held.name,
held.absolute,
held.size,
held.path.display(),
held.md5
);
}
println!("all read-backs matched before reboot; BOOT.bin never touched");
if receipt.rebooted {
println!("board rebooted and answered as alkane again (SSH banner)");
print!("{}", zynq_verify_hint(&host));
} else {
println!("reboot skipped (--no-reboot); the new images run after the next reboot");
}
}
}
Ok(())
}
/// Install onto a board currently on stock via the from-stock install method.
fn install_from_stock_flow(
verified: &VerifiedAfw,
@@ -498,17 +567,35 @@ fn install_from_stock_flow(
);
stock::install_from_stock(host, afw, verified, password.as_deref())?;
println!("from-stock install reported success.");
println!("verify the board is now reachable as alkane:");
println!(" alkane-cli afw verify-live --host {host} --timeout 300");
if zynq::owns_board(&verified.manifest.board) {
print!("{}", zynq_verify_hint(host));
} else {
println!("verify the board is now reachable as alkane:");
println!(" alkane-cli afw verify-live --host {host} --timeout 300");
}
Ok(())
}
/// How to confirm a Zynq board came up on alkane.
fn zynq_verify_hint(host: &str) -> String {
format!(
"verify independently:\n\
\x20 alkane-cli afw verify-live <the .afw> --host {host} --password-file <alkane root pw> --timeout 300\n"
)
}
fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[
ssh_values(),
&["held-backup", "backup-dir", "confirm", "expect-board", "board"],
&[
"held-backup",
"backup-dir",
"confirm",
"expect-board",
"board",
],
]
.concat(),
&[
@@ -537,6 +624,9 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let host = opts.value("host").ok_or("--host is required")?.to_owned();
return install_from_stock_flow(&verified, &host, &path, &opts);
}
if zynq::owns_board(&verified.manifest.board) {
return install_zynq_in_place(&verified, &opts);
}
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
let backup_dir = opts
@@ -593,39 +683,6 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
}
return Ok(());
}
if zynq::owns_board(&verified.manifest.board) {
let plan = ZynqPlan::from_afw(&verified)?;
println!("{}", plan.render());
let install_options = ZynqInstallOptions {
dry_run: opts.flag("dry-run"),
confirm: opts.value("confirm").map(str::to_owned),
no_reboot: opts.flag("no-reboot"),
backup_dir,
};
match zynq::install(&plan, &mut transport, &install_options, opts.value("host").unwrap_or(""))? {
ZynqOutcome::DryRun(report) => {
print!("{}", report.render());
println!("DRY RUN: no board erase or write was performed.");
let targets = plan.targets.iter().map(|t| t.image_name.as_str()).collect::<Vec<_>>().join(", ");
println!("Re-run with --confirm FLASH to write {targets} (BOOT.bin preserved).");
}
ZynqOutcome::Installed(receipt) => {
for backup in &receipt.backups {
println!(
"held {} {} offset 0x{:x} md5 {}",
backup.image_name, backup.path.display(), backup.offset, backup.md5
);
}
println!("all read-backs matched before reboot; BOOT.bin never touched");
if receipt.rebooted {
println!("reboot issued; an SSH drop here is the success signature");
} else {
println!("reboot skipped (--no-reboot)");
}
}
}
return Ok(());
}
if a113d::owns_board(&verified.manifest.board) {
let plan = A113dPlan::from_afw(&verified)?;
println!("{}", plan.render());
@@ -635,25 +692,39 @@ fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
no_reboot: opts.flag("no-reboot"),
backup_dir,
};
match a113d::install(&plan, &mut transport, &install_options, opts.value("host").unwrap_or(""))? {
match a113d::install(
&plan,
&mut transport,
&install_options,
opts.value("host").unwrap_or(""),
)? {
A113dOutcome::DryRun(report) => {
print!("{}", report.render());
println!("DRY RUN: no file was written into the nvdata UBI.");
let targets = plan.targets.iter().map(|t| t.image_name.as_str()).collect::<Vec<_>>().join(", ");
let targets = plan
.targets
.iter()
.map(|t| t.image_name.as_str())
.collect::<Vec<_>>()
.join(", ");
println!("Re-run with --confirm FLASH to write {targets} into the alkane/ dir on nvdata (FIP + mtd0-5 are not MTD devices).");
}
A113dOutcome::Installed(receipt) => {
println!("wrote OS files into the alkane/ dir on nvdata volume {}", receipt.volume);
println!(
"wrote OS files into the alkane/ dir on nvdata volume {}",
receipt.volume
);
for backup in &receipt.backups {
match (&backup.path, &backup.md5) {
(Some(path), Some(md5)) => println!(
"held {} {} md5 {}",
backup.image_name, path.display(), md5
),
(Some(path), Some(md5)) => {
println!("held {} {} md5 {}", backup.image_name, path.display(), md5)
}
_ => println!("held {} (no prior file on board)", backup.image_name),
}
}
println!("all read-backs matched before reboot; no raw NAND write, FIP never touched");
println!(
"all read-backs matched before reboot; no raw NAND write, FIP never touched"
);
if receipt.rebooted {
println!("reboot issued; an SSH drop here is the success signature");
} else {
@@ -713,7 +784,13 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
args,
&[
ssh_values(),
&["marker", "kernel-version", "timeout", "expect-board", "board"],
&[
"marker",
"kernel-version",
"timeout",
"expect-board",
"board",
],
]
.concat(),
&["allow-unsigned"],
@@ -722,7 +799,16 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let (board, marker, kernel_version) = if let Some(path) = opts.positionals.first() {
let verified = load_afw(path, &opts)?;
let board = verified.manifest.board.clone();
if board == "am335x" {
if zynq::owns_board(&board) {
let plan = ZynqPlan::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 if board == "am335x" {
let plan = Am335xPlan::from_afw(&verified)?;
(
board,
@@ -742,9 +828,13 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
)
}
} else {
let board = requested_board.clone().unwrap_or_else(|| "cv1835".to_owned());
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 if zynq::owns_board(&board) {
("Alkane".to_owned(), String::new())
} else {
("CVBOOT".to_owned(), String::new())
};
@@ -760,12 +850,31 @@ fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
}
}
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let timeout = opts
.value("timeout")
.map(str::parse::<u64>)
.transpose()?
.unwrap_or(DEFAULT_TIMEOUT);
if zynq::owns_board(&board) {
// Zynq is checked through the compiled-in method's root SSH (the host
// key changes on every reflash, so it is not pinned) plus the web page.
let password = read_board_password(&opts)?;
let report = stock::verify_zynq_live(
&host,
password.as_deref(),
&marker,
&kernel_version,
Duration::from_secs(timeout),
)?;
print!("{}", report.render());
if !report.ok() {
return Err(
"live verification failed: HTTP marker and SSH did not both confirm alkane".into(),
);
}
return Ok(());
}
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
if board == "am335x" {
let report = am335x::verify_live(
&host,
@@ -801,8 +910,13 @@ fn run_restore(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
&[
ssh_values(),
&[
"held-backup", "backup-dir", "confirm", "board", "held-kernel",
"held-dtb", "held-uboot",
"held-backup",
"backup-dir",
"confirm",
"board",
"held-kernel",
"held-dtb",
"held-uboot",
],
]
.concat(),
@@ -925,7 +1039,8 @@ fn latest_backup(dir: &Path) -> Option<PathBuf> {
/// 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)")];
fn is_supported(board: &str) -> bool {
SUPPORTED.iter().any(|(b, _)| *b == board)
@@ -936,7 +1051,9 @@ fn run_compat(_args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
for (board, miner) in SUPPORTED {
println!(" {board:<12} {miner}");
}
println!("\nInstall a local bundle: alkane-cli afw install <file.afw> --host <ip> --confirm FLASH");
println!(
"\nInstall a local bundle: alkane-cli afw install <file.afw> --host <ip> --confirm FLASH"
);
println!("Install the latest build: alkane-cli afw install --latest --board zynq-7010 --host <ip> --confirm FLASH");
println!("Remove (back to stock): alkane-cli afw restore-stock --host <ip> --confirm FLASH");
Ok(())
@@ -951,9 +1068,15 @@ fn run_fetch_latest(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, &["board", "output"], &[])?;
let board = opts.value("board").unwrap_or("zynq-7010");
if !is_supported(board) {
return Err(format!("{board} is not a supported install target (see: alkane-cli afw compat)").into());
return Err(format!(
"{board} is not a supported install target (see: alkane-cli afw compat)"
)
.into());
}
let dest = opts.value("output").map(PathBuf::from).unwrap_or_else(download_dir);
let dest = opts
.value("output")
.map(PathBuf::from)
.unwrap_or_else(download_dir);
let path = fetch::fetch_latest_afw(&ReleaseSource::alkane_os(), board, &dest)?;
println!("fetched {}", path.display());
Ok(())
@@ -965,17 +1088,19 @@ fn resolve_afw_source(opts: &Opts) -> Result<PathBuf, Box<dyn std::error::Error>
if opts.flag("latest") {
let board = opts.value("board").unwrap_or("zynq-7010");
if !is_supported(board) {
return Err(format!("{board} is not a supported install target (see: alkane-cli afw compat)").into());
return Err(format!(
"{board} is not a supported install target (see: alkane-cli afw compat)"
)
.into());
}
println!("fetching the latest {board} release from Gitea...");
let path = fetch::fetch_latest_afw(&ReleaseSource::alkane_os(), board, &download_dir())?;
println!("using {}", path.display());
return Ok(path);
}
opts.positionals
.first()
.map(PathBuf::from)
.ok_or_else(|| "usage: alkane-cli afw install <file>|--latest --host <ip> --confirm FLASH".into())
opts.positionals.first().map(PathBuf::from).ok_or_else(|| {
"usage: alkane-cli afw install <file>|--latest --host <ip> --confirm FLASH".into()
})
}
/// Return an alkane board to genuine Bitmain stock by writing the stock images
@@ -989,23 +1114,22 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let firmware = opts.value("stock-firmware").ok_or(
"--stock-firmware <genuine Bitmain firmware file> is required \
(SD recovery image SD_Antminer-*.zip, which includes the device tree)",
(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)?;
// Parse the genuine vendor package into the stock images to write back.
// 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.
let fw = stock_firmware::parse(Path::new(firmware))?;
let dtb = fw.dtb.as_deref().ok_or(
"this firmware package has no device tree; use the Bitmain SD recovery \
image (SD_Antminer-S17-*.zip), which includes devicetree.dtb",
)?;
println!("stock firmware: {}", fw.summary());
if opts.flag("dry-run") {
println!("DRY RUN: would restore {host} to stock by writing the stock dtb, kernel and");
println!("rootfs back to NAND (BOOT.bin preserved). Re-run with --confirm FLASH.");
println!("DRY RUN: would restore {host} to stock by writing the genuine stock kernel");
println!("and rootfs plus the per-board device tree back to NAND (BOOT.bin preserved).");
println!("Re-run with --confirm FLASH.");
return Ok(());
}
if opts.value("confirm") != Some("FLASH") {
@@ -1013,7 +1137,6 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
}
println!("restoring {host} to genuine stock from {firmware} (network-only)...");
let images = RestoreImages {
dtb,
kernel: &fw.kernel,
rootfs: &fw.rootfs,
};
+112 -32
View File
@@ -67,9 +67,17 @@ pub enum A113dPlanError {
#[error("a113d is missing the {0} image")]
MissingImage(String),
#[error("a113d {image} format is {actual}, expected {expected}")]
ImageFormat { image: String, actual: String, expected: &'static str },
ImageFormat {
image: String,
actual: String,
expected: &'static str,
},
#[error("a113d {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
ImageTooLarge { image: String, size: u64, ceiling: u64 },
ImageTooLarge {
image: String,
size: u64,
ceiling: u64,
},
#[error("a113d images total {total} bytes, over the nvdata UBI (0x{usable:x})")]
OverNvdata { total: u64, usable: u64 },
#[error("a113d {image} is not an arm64 Image")]
@@ -152,7 +160,9 @@ impl A113dPlan {
// Defense in depth: only nvdata (mtd6) may carry an image; mtd0-5 preserved.
for partition in &manifest.partitions {
if partition.name != "nvdata" && partition.image.is_some() {
return Err(A113dPlanError::PreservedCarriesImage(partition.name.clone()));
return Err(A113dPlanError::PreservedCarriesImage(
partition.name.clone(),
));
}
}
@@ -199,17 +209,23 @@ impl A113dPlan {
match expected_format {
"arm64-image" => {
if !(data.len() >= 0x3C && data[0x38..0x3C] == *b"ARMd") {
return Err(A113dPlanError::NotArm64 { image: image_name.to_owned() });
return Err(A113dPlanError::NotArm64 {
image: image_name.to_owned(),
});
}
}
"fdt" => {
if !(data.len() >= 4 && data[0..4] == [0xd0, 0x0d, 0xfe, 0xed]) {
return Err(A113dPlanError::NotFdt { image: image_name.to_owned() });
return Err(A113dPlanError::NotFdt {
image: image_name.to_owned(),
});
}
}
"uimage" => {
if !(data.len() >= 4 && data[0..4] == [0x27, 0x05, 0x19, 0x56]) {
return Err(A113dPlanError::NotUimage { image: image_name.to_owned() });
return Err(A113dPlanError::NotUimage {
image: image_name.to_owned(),
});
}
}
_ => {}
@@ -224,7 +240,10 @@ impl A113dPlan {
});
}
if total > NVDATA_USABLE {
return Err(A113dPlanError::OverNvdata { total, usable: NVDATA_USABLE });
return Err(A113dPlanError::OverNvdata {
total,
usable: NVDATA_USABLE,
});
}
Ok(Self {
@@ -327,7 +346,11 @@ impl A113dPreflight {
}
out.push_str(&format!(
"result {}",
if self.ok() { "PASS" } else { "FAIL (do not write)" }
if self.ok() {
"PASS"
} else {
"FAIL (do not write)"
}
));
out
}
@@ -379,7 +402,11 @@ pub fn preflight(
let uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
checks.push(A113dCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") });
checks.push(A113dCheck {
name: "root".to_owned(),
ok: uid == "0",
detail: format!("uid {uid}"),
});
let tools = remote.user_command(
"for c in ubiattach ubidetach mount umount cp md5sum sync; do \
@@ -426,7 +453,11 @@ pub fn preflight(
detail: format!("all writes are files under {ALKANE_DIR}/ on the nvdata UBI"),
});
Ok(A113dPreflight { host: host.to_owned(), checks, nvdata_mtd })
Ok(A113dPreflight {
host: host.to_owned(),
checks,
nvdata_mtd,
})
}
#[derive(Clone, Debug)]
@@ -464,10 +495,7 @@ const MNT: &str = "/tmp/.alkane-nvdata";
/// Returns (ubi device number, volume name). The volume name is DISCOVERED, never
/// assumed (vendor histories leave different names: umc_os_rootfs, nvdada_log,
/// overlay, ...).
fn attach_and_mount(
remote: &mut dyn Remote,
nvdata_mtd: u32,
) -> Result<String, A113dError> {
fn attach_and_mount(remote: &mut dyn Remote, nvdata_mtd: u32) -> Result<String, A113dError> {
// Attach (idempotent: if ubi0 already exists, reuse it).
let _ = remote.root_command(
&format!(
@@ -491,8 +519,10 @@ fn attach_and_mount(
Duration::from_secs(60),
)?;
// Confirm the mount actually took.
let mounted =
remote.user_command(&format!("mount | grep -c ' {MNT} '"), Duration::from_secs(20))?;
let mounted = remote.user_command(
&format!("mount | grep -c ' {MNT} '"),
Duration::from_secs(20),
)?;
if String::from_utf8_lossy(&mounted).trim() == "0" {
return Err(A113dError::Mount);
}
@@ -501,7 +531,9 @@ fn attach_and_mount(
fn unmount(remote: &mut dyn Remote) {
let _ = remote.root_command(
&format!("sync; umount {MNT} 2>/dev/null; ubidetach -d 0 2>/dev/null; rmdir {MNT} 2>/dev/null"),
&format!(
"sync; umount {MNT} 2>/dev/null; ubidetach -d 0 2>/dev/null; rmdir {MNT} 2>/dev/null"
),
Duration::from_secs(60),
);
}
@@ -527,7 +559,10 @@ pub fn install(
.ok_or_else(|| A113dError::NoNvdataMtd(NVDATA_LABEL.to_owned()))?;
fs::create_dir_all(&options.backup_dir)?;
let epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
let epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let volume = attach_and_mount(remote, nvdata_mtd)?;
let alkane_dir = format!("{MNT}/{ALKANE_DIR}");
@@ -549,7 +584,9 @@ pub fn install(
Duration::from_secs(15),
)?;
if String::from_utf8_lossy(&have).contains("__YES__") {
let local = options.backup_dir.join(format!("{}-{epoch}.bak", target.dest));
let local = options
.backup_dir
.join(format!("{}-{epoch}.bak", target.dest));
remote.pull(&dest_path, &local, Duration::from_secs(300))?;
let data = fs::read(&local)?;
backups.push(A113dBackup {
@@ -616,7 +653,11 @@ pub fn install(
remote.reboot()?;
true
};
Ok(A113dOutcome::Installed(A113dReceipt { volume, backups, rebooted }))
Ok(A113dOutcome::Installed(A113dReceipt {
volume,
backups,
rebooted,
}))
}
pub fn owns_board(board: &str) -> bool {
@@ -664,7 +705,10 @@ mod tests {
partitions: serde_json::Value,
) -> VerifiedAfw {
let image = |name: &str, file: &str, role: &str, fmt: &str, data: &[u8]| {
let sha: String = Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect();
let sha: String = Sha256::digest(data)
.iter()
.map(|b| format!("{b:02x}"))
.collect();
json!({"name": name, "file": file, "role": role, "format": fmt,
"size": data.len(), "sha256": sha, "partition": "nvdata", "install": true})
};
@@ -687,9 +731,18 @@ mod tests {
VerifiedAfw {
manifest,
members: vec![
AfwMember { name: "payload/vmlinux.bin".to_owned(), data: kernel },
AfwMember { name: "payload/devicetree.dtb".to_owned(), data: dtb },
AfwMember { name: "payload/uramdisk.image.gz".to_owned(), data: rootfs },
AfwMember {
name: "payload/vmlinux.bin".to_owned(),
data: kernel,
},
AfwMember {
name: "payload/devicetree.dtb".to_owned(),
data: dtb,
},
AfwMember {
name: "payload/uramdisk.image.gz".to_owned(),
data: rootfs,
},
],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
@@ -718,7 +771,11 @@ mod tests {
assert_eq!(plan.targets[2].image_name, "kernel");
assert!(no_raw_device_targets(&plan));
for t in &plan.targets {
assert!(!t.dest.contains('/'), "{} has a path, not a basename", t.image_name);
assert!(
!t.dest.contains('/'),
"{} has a path, not a basename",
t.image_name
);
}
assert!(plan.render().contains("alkane/"));
assert!(plan.render().contains("no raw NAND write is possible"));
@@ -726,7 +783,12 @@ mod tests {
#[test]
fn refuses_a_non_arm64_kernel() {
let r = A113dPlan::from_afw(&afw_with(vec![0u8; 64], dtb(), uramdisk(), preserved_partitions()));
let r = A113dPlan::from_afw(&afw_with(
vec![0u8; 64],
dtb(),
uramdisk(),
preserved_partitions(),
));
assert!(matches!(r, Err(A113dPlanError::NotArm64 { .. })));
}
@@ -741,10 +803,16 @@ mod tests {
fn refuses_a_fip_member() {
let mut v = good();
v.manifest.images[0].role = "bootloader".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::BootloaderMember(_))));
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::BootloaderMember(_))
));
let mut v = good();
v.manifest.images[1].file = "payload/fip.bin".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::BootloaderMember(_))));
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::BootloaderMember(_))
));
}
#[test]
@@ -766,16 +834,25 @@ mod tests {
fn wrong_board_and_arch_are_refused() {
let mut v = good();
v.manifest.board = "zynq-7010".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::WrongBoard(_))));
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::WrongBoard(_))
));
let mut v = good();
v.manifest.arch = "armv7".to_owned();
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::WrongArch(_))));
assert!(matches!(
A113dPlan::from_afw(&v),
Err(A113dPlanError::WrongArch(_))
));
}
#[test]
fn every_target_is_a_basename_never_a_device() {
for (image, dest, _ceiling, _fmt) in TARGETS {
assert!(is_safe_dest(dest), "{image} dest {dest} is not a safe basename");
assert!(
is_safe_dest(dest),
"{image} dest {dest} is not a safe basename"
);
}
}
@@ -795,6 +872,9 @@ mod tests {
// No nvdata line -> None (the no-NAND running image).
assert_eq!(parse_nvdata_mtd("dev: size erasesize name\n"), None);
// Different index is honored.
assert_eq!(parse_nvdata_mtd("mtd3: 0b900000 00020000 \"nvdata\"\n"), Some(3));
assert_eq!(
parse_nvdata_mtd("mtd3: 0b900000 00020000 \"nvdata\"\n"),
Some(3)
);
}
}
+174 -96
View File
@@ -10,9 +10,7 @@ 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 alkane_artifacts::afw::{AfwImage, AfwManifest, AfwPartition, BootloaderPolicy, VerifiedAfw};
use serde_json::json;
use sha2::{Digest, Sha256};
use std::fs;
@@ -88,7 +86,15 @@ const TARGET_IMAGES_STOCK: [(&str, &str, u64); 4] = [
pub struct Profile {
pub board: &'static str,
pub policy: BootloaderPolicy,
pub mtd_map: &'static [(&'static str, u64, u64, bool, bool, i64, Option<&'static str>)],
pub mtd_map: &'static [(
&'static str,
u64,
u64,
bool,
bool,
i64,
Option<&'static str>,
)],
pub preserve: &'static [&'static str],
pub targets: &'static [(&'static str, &'static str, u64)],
/// Tier 3 ships our U-Boot as a `bootloader` member; tier 2 never does.
@@ -319,7 +325,11 @@ impl Am335xPlan {
Ok(Self {
board: profile.board.to_owned(),
preserve: profile.preserve.iter().map(|name| (*name).to_owned()).collect(),
preserve: profile
.preserve
.iter()
.map(|name| (*name).to_owned())
.collect(),
targets,
partitions: manifest.partitions.clone(),
marker: manifest.marker.clone(),
@@ -351,9 +361,7 @@ impl Am335xPlan {
);
} else {
out.push_str("bootloader preserve (mtd0-5 SPL/U-Boot/bootenv kept, never written)\n");
out.push_str(
"image format legacy-uimage (kernel type 2, ramdisk type 3), never FIT\n",
);
out.push_str("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",
@@ -523,7 +531,9 @@ impl AmPreflightReport {
"free tmp {} MiB\n",
self.free_bytes / (1024 * 1024)
));
out.push_str("preserved partitions (see preserve-spl check): never erased and never written\n");
out.push_str(
"preserved partitions (see preserve-spl check): never erased and never written\n",
);
for check in &self.checks {
out.push_str(&format!(
"check {} {}: {}\n",
@@ -592,8 +602,8 @@ pub fn preflight(
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);
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,
@@ -607,20 +617,18 @@ pub fn preflight(
),
});
let root_uid =
String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
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),
)?)
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);
// Validate the live geometry against the plan's partitions by index+size.
@@ -636,7 +644,10 @@ pub fn preflight(
name: "mtd-map".to_owned(),
ok: map_ok,
detail: if map_ok {
format!("{} partitions match the plan geometry by size", plan.partitions.len())
format!(
"{} partitions match the plan geometry by size",
plan.partitions.len()
)
} else {
format!("partition table differs: {mtd_text}")
},
@@ -656,7 +667,8 @@ pub fn preflight(
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()
"/usr/sbin/flash_erase, /usr/sbin/nandwrite, /usr/sbin/nanddump, md5sum, sync present"
.to_owned()
} else {
format!("missing {}", missing.join(", "))
},
@@ -731,7 +743,9 @@ fn parse_proc_mtd(text: &str) -> std::collections::HashMap<String, (u64, String)
continue;
};
let mut fields = rest.split_whitespace();
let Some(size) = fields.next().and_then(|value| u64::from_str_radix(value, 16).ok())
let Some(size) = fields
.next()
.and_then(|value| u64::from_str_radix(value, 16).ok())
else {
continue;
};
@@ -753,15 +767,10 @@ fn live_target_md5(
) -> Result<String, AmError> {
let probe = format!("/tmp/.alkane-probe-{name}.img");
remote.root_command(
&format!(
"/usr/sbin/nanddump --omitoob --bb=skipbad --length={size} -f {probe} {device}"
),
&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 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()))
}
@@ -860,9 +869,7 @@ pub fn install(
),
Duration::from_secs(300),
)?;
let local = options
.backup_dir
.join(format!("{name}-{epoch}.img"));
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)?;
@@ -906,10 +913,8 @@ pub fn install(
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 =
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));
@@ -970,11 +975,7 @@ fn restore_hint(backups: &[AmBackup], failed: &str) -> String {
"mtd6" => "--held-dtb",
_ => "--held-backup",
};
text.push_str(&format!(
" {} {}",
flag,
backup.path.display()
));
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)"));
@@ -1072,11 +1073,7 @@ pub fn restore(
}
let data = fs::read(path)?;
if data.len() as u64 != *size {
return Err(AmError::BackupSize(
name.clone(),
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)
@@ -1091,10 +1088,8 @@ pub fn restore(
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),
)?;
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()));
@@ -1198,18 +1193,14 @@ pub fn verify_live(
}
Err(error) => (error, false),
};
let (ssh, ssh_ok, dhcp, dhcp_ok) = match SshTransport::connect(ssh_options.clone(), 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,
)
(format!("kernel {kernel}"), ok)
}
Err(error) => (format!("{error}"), false),
};
@@ -1339,8 +1330,16 @@ mod tests {
.collect()
}
fn partition(name: &str, device: &str, offset: u64, size: u64, secure: bool,
boot_critical: bool, write_order: i64, image: Option<&str>) -> AfwPartition {
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(),
@@ -1356,10 +1355,20 @@ mod tests {
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)
})
.map(
|(name, offset, size, secure, boot_critical, write_order, image)| {
partition(
name,
&format!("/dev/{name}"),
*offset,
*size,
*secure,
*boot_critical,
*write_order,
*image,
)
},
)
.collect::<Vec<_>>();
json!({
"schema": 2,
@@ -1427,10 +1436,20 @@ mod tests {
fn stock_afw(uboot: &[u8], kernel: &[u8], dtb_data: &[u8], rootfs: &[u8]) -> VerifiedAfw {
let partitions = MTD_MAP_STOCK
.iter()
.map(|(name, offset, size, secure, boot_critical, write_order, image)| {
partition(name, &format!("/dev/{name}"), *offset, *size, *secure,
*boot_critical, *write_order, *image)
})
.map(
|(name, offset, size, secure, boot_critical, write_order, image)| {
partition(
name,
&format!("/dev/{name}"),
*offset,
*size,
*secure,
*boot_critical,
*write_order,
*image,
)
},
)
.collect::<Vec<_>>();
let value = json!({
"schema": 2, "format": "afw", "board": "am335x-stock", "arch": "arm",
@@ -1463,10 +1482,22 @@ mod tests {
VerifiedAfw {
manifest,
members: vec![
AfwMember { name: "payload/alkane-am335x-uboot-mtd4.uImage".to_owned(), data: uboot.to_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() },
AfwMember {
name: "payload/alkane-am335x-uboot-mtd4.uImage".to_owned(),
data: uboot.to_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),
@@ -1475,32 +1506,57 @@ mod tests {
#[test]
fn accepts_a_good_stock_plan_and_writes_uboot_before_kernel() {
let (uboot, kernel, dtb_data, rootfs) =
(uimage(5, b"u-boot"), uimage(2, b"kernel"), dtb(), uimage(3, b"ramdisk"));
let (uboot, kernel, dtb_data, rootfs) = (
uimage(5, b"u-boot"),
uimage(2, b"kernel"),
dtb(),
uimage(3, b"ramdisk"),
);
let plan = Am335xPlan::from_afw(&stock_afw(&uboot, &kernel, &dtb_data, &rootfs)).unwrap();
assert_eq!(plan.board, "am335x-stock");
assert_eq!(plan.targets.len(), 4);
// write order: rootfs(1), dtb(2), u-boot(3), kernel(4) - U-Boot before kernel.
let order: Vec<&str> = plan.targets.iter().map(|t| t.partition.name.as_str()).collect();
let order: Vec<&str> = plan
.targets
.iter()
.map(|t| t.partition.name.as_str())
.collect();
assert_eq!(order, ["mtd8", "mtd6", "mtd4", "mtd7"]);
assert!(plan.preserve.iter().all(|p| p != "mtd4"), "mtd4 must not be preserved on tier 3");
assert!(plan.preserve.contains(&"mtd5".to_owned()) && plan.preserve.contains(&"mtd0".to_owned()));
assert!(
plan.preserve.iter().all(|p| p != "mtd4"),
"mtd4 must not be preserved on tier 3"
);
assert!(
plan.preserve.contains(&"mtd5".to_owned())
&& plan.preserve.contains(&"mtd0".to_owned())
);
assert!(plan.render().contains("tier 3 from stock"));
}
#[test]
fn stock_rejects_a_uboot_that_is_not_firmware_type() {
// U-Boot payload wrongly built as a type-2 kernel uImage must be caught.
let (uboot, kernel, dtb_data, rootfs) =
(uimage(2, b"u-boot"), uimage(2, b"kernel"), dtb(), uimage(3, b"ramdisk"));
let (uboot, kernel, dtb_data, rootfs) = (
uimage(2, b"u-boot"),
uimage(2, b"kernel"),
dtb(),
uimage(3, b"ramdisk"),
);
let result = Am335xPlan::from_afw(&stock_afw(&uboot, &kernel, &dtb_data, &rootfs));
assert!(matches!(result, Err(AmPlanError::UImageType { expected: 5, .. })));
assert!(matches!(
result,
Err(AmPlanError::UImageType { expected: 5, .. })
));
}
#[test]
fn stock_rejects_making_an_spl_copy_a_write_target() {
let (uboot, kernel, dtb_data, rootfs) =
(uimage(5, b"u-boot"), uimage(2, b"kernel"), dtb(), uimage(3, b"ramdisk"));
let (uboot, kernel, dtb_data, rootfs) = (
uimage(5, b"u-boot"),
uimage(2, b"kernel"),
dtb(),
uimage(3, b"ramdisk"),
);
let mut verified = stock_afw(&uboot, &kernel, &dtb_data, &rootfs);
// Turn mtd0 (an SPL copy) into a write target.
for part in &mut verified.manifest.partitions {
@@ -1511,7 +1567,10 @@ mod tests {
}
}
let result = Am335xPlan::from_afw(&verified);
assert!(matches!(result, Err(AmPlanError::PartitionGeometry(_)) | Err(AmPlanError::PreservedTarget(_))));
assert!(matches!(
result,
Err(AmPlanError::PartitionGeometry(_)) | Err(AmPlanError::PreservedTarget(_))
));
}
#[test]
@@ -1531,19 +1590,31 @@ mod tests {
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(_))));
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(_))));
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)));
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)));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::BootloaderMember)
));
}
#[test]
@@ -1560,7 +1631,10 @@ mod tests {
partition: None,
install: false,
});
assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::SplUbootMember(_))));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::SplUbootMember(_))
));
}
#[test]
@@ -1576,7 +1650,10 @@ mod tests {
part.write_order = 1;
part.image = Some("kernel".to_owned());
part.secure = false;
assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::PartitionGeometry(_))));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::PartitionGeometry(_))
));
}
#[test]
@@ -1590,7 +1667,10 @@ mod tests {
.find(|part| part.name == "mtd8")
.unwrap();
part.offset = HOLE_OFFSET;
assert!(matches!(Am335xPlan::from_afw(&verified), Err(AmPlanError::PartitionGeometry(_))));
assert!(matches!(
Am335xPlan::from_afw(&verified),
Err(AmPlanError::PartitionGeometry(_))
));
}
#[test]
@@ -1654,8 +1734,7 @@ mod tests {
fn user_command(&mut self, command: &str, _: Duration) -> Result<Vec<u8>, 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()
"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()
@@ -1698,9 +1777,7 @@ mod tests {
{
data.truncate(length);
}
if command.contains("readback")
&& self.readback_corrupt.as_deref() == Some(name)
{
if command.contains("readback") && self.readback_corrupt.as_deref() == Some(name) {
if let Some(last) = data.last_mut() {
*last ^= 0xff;
}
@@ -1809,7 +1886,9 @@ mod tests {
let first_backup = remote
.commands
.iter()
.position(|command| command.contains("nanddump --omitoob") && command.contains("backup"))
.position(|command| {
command.contains("nanddump --omitoob") && command.contains("backup")
})
.unwrap();
assert!(first_backup < first_write);
}
@@ -1887,8 +1966,7 @@ mod tests {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("mtd4.img");
fs::write(&path, vec![0_u8; 0x1C0000]).unwrap();
let tier3_preserve: Vec<String> =
PRESERVE_STOCK.iter().map(|s| (*s).to_owned()).collect();
let tier3_preserve: Vec<String> = PRESERVE_STOCK.iter().map(|s| (*s).to_owned()).collect();
// mtd4 restore is accepted (it reaches the write path, not the guard).
let mut remote = MockRemote::new(0x1C0000);
+149 -346
View File
@@ -1,45 +1,47 @@
// SPDX-License-Identifier: MIT
//! Zynq-7010 board module: tier-2 network UPDATE of a board already running
//! alkane (the first install from stock, past the RSA gate, is handled elsewhere
//! and is not this module). It writes our kernel (zImage) into the mtd0
//! kernel slot, the dtb, and the rootfs into mtd1, and PRESERVES BOOT.bin
//! (FSBL + FPGA bitstream + stock U-Boot) at the front of mtd0.
//! Zynq-7010 board module: the manifest gate and write plan for putting our
//! OS onto a Zynq control board (Antminer S17/S19 class).
//!
//! The write offsets are DEVICE-RELATIVE and authoritative here (like the
//! am335x MTD_MAP): dtb at 0x1a00000 and kernel at 0x2000000 within /dev/mtd0,
//! rootfs at 0 within /dev/mtd1 - the layout the on-board stock U-Boot
//! `nandboot` reads, confirmed live on an S17 (alkane-sdk install plan
//! install/plans/zynq-7010.yaml, 2026-11-10). The module REFUSES to erase or
//! write /dev/mtd0 below BOOTBIN_PRESERVE, so a bad offset can never clobber
//! BOOT.bin.
//! This module decides WHAT may be written and WHERE, in absolute NAND terms.
//! It does not write. The write itself (for a board already on alkane, and for
//! the first install from stock) is done by the compiled-in method behind
//! `crate::stock` (`update_in_place` / `install_from_stock`), because on a board
//! running alkane the boot regions are deliberately not exposed to Linux and
//! have to be re-registered first; that mechanism lives with the method.
//!
//! Layout (absolute NAND offsets, 128 KiB erase blocks): BOOT.bin (FSBL + FPGA
//! bitstream + stock U-Boot + env) occupies 0x0..0x1a00000 and is never
//! written. The stock U-Boot reads the dtb at 0x1a00000, the kernel at
//! 0x2000000 and the ramdisk at 0x2800000, and boots the kernel and ramdisk as
//! legacy uImages, so both are written with a 64-byte uImage header.
//!
//! History: an earlier version of this module wrote raw images at
//! device-relative offsets on /dev/mtd0 and /dev/mtd1. That matched an early
//! alkane image that exposed the whole NAND, not the current one (which exposes
//! only the small `stock-cfg` and `alkane-cfg` partitions), and its raw kernel
//! and ramdisk were not bootable by the stock U-Boot. It was removed.
use crate::md5::md5_hex;
use crate::preflight::{classify, parse_digest};
use crate::transport::{Remote, RemoteError};
use alkane_artifacts::afw::{AfwImage, BootloaderPolicy, VerifiedAfw};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use thiserror::Error;
pub const BOARD: &str = "zynq-7010";
pub const ARCH: &str = "armv7";
/// mtd0 0x0..0x1a00000 is BOOT.bin (FSBL + FPGA bitstream + stock U-Boot) + the
/// U-Boot env, and is NEVER erased or written by this module. (Was 0x2200000
/// under the superseded stage-2 map; the live S17 layout places the dtb at
/// 0x1a00000, so BOOT.bin ends there.)
/// Absolute NAND 0x0..0x1a00000 is BOOT.bin (FSBL + FPGA bitstream + stock
/// U-Boot) + the U-Boot env, and is NEVER erased or written.
pub const BOOTBIN_PRESERVE: u64 = 0x1A00000;
/// Authoritative write targets: (image, device, device-relative offset, ceiling, format).
/// Written rootfs -> dtb -> kernel so a mid-write interruption never leaves a new
/// rootfs under an old kernel. Offsets and ceilings match the alkane-sdk install
/// plan (install/plans/zynq-7010.yaml): dtb slot 0x1a00000 (0x600000), kernel
/// slot 0x2000000 (0x800000), rootfs mtd1 (0x2000000).
const TARGETS: [(&str, &str, u64, u64, &str); 3] = [
("rootfs", "/dev/mtd1", 0x0, 0x2000000, "cpio-gzip"),
("dtb", "/dev/mtd0", 0x1A00000, 0x20000, "fdt"),
("kernel", "/dev/mtd0", 0x2000000, 0x800000, "zimage"),
/// Size of the legacy uImage header the stock U-Boot needs on the kernel and
/// the ramdisk.
const UIMAGE_HEADER: u64 = 64;
/// Write targets in write order (rootfs, dtb, kernel, so an interrupted write
/// never leaves a new rootfs under an old kernel): (image, absolute NAND
/// offset, slot size, expected manifest format, uImage-wrapped).
const TARGETS: [(&str, u64, u64, &str, bool); 3] = [
("rootfs", 0x2800000, 0x2000000, "cpio-gzip", true),
("dtb", 0x1A00000, 0x20000, "fdt", false),
("kernel", 0x2000000, 0x800000, "zimage", true),
];
#[derive(Debug, Error)]
@@ -61,21 +63,37 @@ pub enum ZynqPlanError {
#[error("zynq-7010 is missing the {0} image")]
MissingImage(String),
#[error("zynq-7010 {image} format is {actual}, expected {expected}")]
ImageFormat { image: String, actual: String, expected: &'static str },
#[error("zynq-7010 {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
ImageTooLarge { image: String, size: u64, ceiling: u64 },
ImageFormat {
image: String,
actual: String,
expected: &'static str,
},
#[error("zynq-7010 {image} is {size} bytes, over the {ceiling}-byte ceiling for its 0x{slot:x} slot")]
ImageTooLarge {
image: String,
size: u64,
ceiling: u64,
slot: u64,
},
#[error("zynq-7010 {image} is not an ARM zImage")]
NotZImage { image: String },
#[error("zynq-7010 refuses to place {image} at 0x{offset:x} on {device}: below BOOT.bin (0x{bootbin:x})")]
WouldClobberBootbin { image: String, device: String, offset: u64, bootbin: u64 },
#[error("zynq-7010 refuses to place {image} at 0x{offset:x}: below BOOT.bin (0x{bootbin:x})")]
WouldClobberBootbin {
image: String,
offset: u64,
bootbin: u64,
},
}
#[derive(Clone, Debug)]
pub struct ZynqTarget {
pub image_name: String,
pub device: String,
pub offset: u64,
/// Absolute NAND offset of the slot.
pub absolute: u64,
pub slot: u64,
/// Size of the image as shipped in the `.afw` (before any uImage header).
pub size: u64,
pub uimage_wrapped: bool,
pub data: Vec<u8>,
pub expected_md5: String,
}
@@ -88,7 +106,6 @@ pub struct ZynqPlan {
pub sdk_revision: String,
pub os_revision: String,
pub afw_sha256: String,
pub min_free_bytes: u64,
}
fn is_bootloaderish(image: &AfwImage) -> bool {
@@ -130,7 +147,7 @@ impl ZynqPlan {
}
let mut targets = Vec::with_capacity(TARGETS.len());
for (image_name, device, offset, ceiling, expected_format) in TARGETS {
for (image_name, absolute, slot, expected_format, wrapped) in TARGETS {
let image = manifest
.images
.iter()
@@ -143,20 +160,20 @@ impl ZynqPlan {
expected: expected_format,
});
}
let ceiling = if wrapped { slot - UIMAGE_HEADER } else { slot };
if image.size > ceiling {
return Err(ZynqPlanError::ImageTooLarge {
image: image_name.to_owned(),
size: image.size,
ceiling,
slot,
});
}
// The one hard brick guard: a write on /dev/mtd0 must sit entirely
// above BOOT.bin.
if device == "/dev/mtd0" && offset < BOOTBIN_PRESERVE {
// The hard brick guard: nothing is ever placed inside BOOT.bin.
if absolute < BOOTBIN_PRESERVE {
return Err(ZynqPlanError::WouldClobberBootbin {
image: image_name.to_owned(),
device: device.to_owned(),
offset,
offset: absolute,
bootbin: BOOTBIN_PRESERVE,
});
}
@@ -167,13 +184,16 @@ impl ZynqPlan {
if expected_format == "zimage"
&& !(data.len() >= 0x28 && data[0x24..0x28] == [0x18, 0x28, 0x6f, 0x01])
{
return Err(ZynqPlanError::NotZImage { image: image_name.to_owned() });
return Err(ZynqPlanError::NotZImage {
image: image_name.to_owned(),
});
}
targets.push(ZynqTarget {
image_name: image_name.to_owned(),
device: device.to_owned(),
offset,
absolute,
slot,
size: image.size,
uimage_wrapped: wrapped,
expected_md5: md5_hex(data),
data: data.to_vec(),
});
@@ -186,25 +206,30 @@ impl ZynqPlan {
sdk_revision: manifest.sdk_revision.clone(),
os_revision: manifest.os_revision.clone(),
afw_sha256: afw.archive_sha256.clone(),
min_free_bytes: manifest
.preflight
.get("min_free_bytes")
.and_then(|v| v.as_u64())
.unwrap_or(16 * 1024 * 1024),
})
}
pub fn render(&self) -> String {
let mut out = format!("board {BOARD} arch {ARCH}\n");
out.push_str(&format!(
"tier 2 update: write the kernel slot + mtd1; BOOT.bin (mtd0 0..0x{:x}) preserved, never written\n",
BOOTBIN_PRESERVE
"boot slots (absolute NAND); BOOT.bin 0x0..0x{BOOTBIN_PRESERVE:x} preserved, never written\n"
));
out.push_str("image format kernel=zImage, dtb=fdt, rootfs=cpio-gzip\n");
out.push_str(
"kernel and rootfs are written as legacy uImages (what the stock U-Boot boots); dtb raw\n",
);
for target in &self.targets {
out.push_str(&format!(
"write {} {} offset 0x{:x} size {} B md5 {}\n",
target.image_name, target.device, target.offset, target.size, target.expected_md5
"write {:<6} abs 0x{:x} slot 0x{:x} size {} B{} md5 {}\n",
target.image_name,
target.absolute,
target.slot,
target.size,
if target.uimage_wrapped {
" +64 B header"
} else {
""
},
target.expected_md5
));
}
out.push_str(&format!(
@@ -222,273 +247,6 @@ fn short(rev: &str) -> &str {
rev.get(..12).unwrap_or(rev)
}
#[derive(Debug, Error)]
pub enum ZynqError {
#[error("preflight failed:\n{0}")]
Preflight(String),
#[error("--confirm FLASH is required to write")]
Confirm,
#[error("refusing to write {device} at 0x{offset:x}: below BOOT.bin (0x{bootbin:x})")]
BootbinGuard { device: String, offset: u64, bootbin: u64 },
#[error("{0} staged md5 differs from the verified bundle")]
StageMismatch(String),
#[error("{0} read-back md5 mismatch; do not reboot")]
Readback(String),
#[error(transparent)]
Remote(#[from] RemoteError),
#[error(transparent)]
Io(#[from] std::io::Error),
}
#[derive(Clone, Debug)]
pub struct ZynqCheck {
pub name: String,
pub ok: bool,
pub detail: String,
}
#[derive(Clone, Debug)]
pub struct ZynqPreflight {
pub host: String,
pub checks: Vec<ZynqCheck>,
}
impl ZynqPreflight {
pub fn ok(&self) -> bool {
self.checks.iter().all(|c| c.ok)
}
pub fn render(&self) -> String {
let mut out = format!("preflight {}\n", self.host);
for c in &self.checks {
out.push_str(&format!("check {} {}: {}\n", c.name, if c.ok { "ok" } else { "FAIL" }, c.detail));
}
out.push_str(&format!("result {}", if self.ok() { "PASS" } else { "FAIL (do not write)" }));
out
}
}
pub fn preflight(
plan: &ZynqPlan,
remote: &mut dyn Remote,
host: &str,
) -> Result<ZynqPreflight, ZynqError> {
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; cat /etc/alkane-release 2>/dev/null \
|| true",
Duration::from_secs(20),
)?;
let text = String::from_utf8_lossy(&fingerprint).into_owned();
let mut it = text.split("__MODEL__");
let kernel = it.next().unwrap_or("").trim().to_owned();
let rest = it.next().unwrap_or("");
let mut it2 = rest.split("__RELEASE__");
let _model = it2.next().unwrap_or("");
let release = it2.next().unwrap_or("");
let source = classify(&kernel, release, &text);
checks.push(ZynqCheck {
name: "source-os".to_owned(),
ok: source == "alkane",
detail: format!("{source} (update path requires alkane)"),
});
let uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
.trim()
.to_owned();
checks.push(ZynqCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") });
let tools = 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 missing: Vec<String> = String::from_utf8_lossy(&tools)
.lines()
.filter_map(|l| l.strip_prefix("missing:").map(str::to_owned))
.collect();
checks.push(ZynqCheck {
name: "commands".to_owned(),
ok: missing.is_empty(),
detail: if missing.is_empty() { "flash tools present".to_owned() } else { format!("missing {}", missing.join(", ")) },
});
let mtd = String::from_utf8_lossy(&remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?).into_owned();
let have_mtd01 = mtd.contains("mtd0:") && mtd.contains("mtd1:");
checks.push(ZynqCheck {
name: "mtd".to_owned(),
ok: have_mtd01,
detail: if have_mtd01 { "mtd0 (BOOT.bin+kernel) and mtd1 present".to_owned() } else { format!("mtd0/mtd1 not found: {mtd}") },
});
// The guard, asserted again at preflight: no target writes mtd0 below BOOT.bin.
let guard_ok = plan
.targets
.iter()
.all(|t| !(t.device == "/dev/mtd0" && t.offset < BOOTBIN_PRESERVE));
checks.push(ZynqCheck {
name: "preserve-bootbin".to_owned(),
ok: guard_ok,
detail: format!("no write on /dev/mtd0 below 0x{BOOTBIN_PRESERVE:x}"),
});
Ok(ZynqPreflight { host: host.to_owned(), checks })
}
#[derive(Clone, Debug)]
pub struct ZynqInstallOptions {
pub dry_run: bool,
pub confirm: Option<String>,
pub no_reboot: bool,
pub backup_dir: PathBuf,
}
#[derive(Clone, Debug)]
pub struct ZynqBackup {
pub image_name: String,
pub device: String,
pub offset: u64,
pub path: PathBuf,
pub md5: String,
pub size: u64,
}
#[derive(Clone, Debug)]
pub struct ZynqReceipt {
pub backups: Vec<ZynqBackup>,
pub rebooted: bool,
}
pub enum ZynqOutcome {
DryRun(Box<ZynqPreflight>),
Installed(ZynqReceipt),
}
/// flash_erase/nandwrite erase-block count that covers `size` bytes at a 128 KiB
/// erase block (the Zynq pl35x-nand block size).
fn erase_blocks(size: u64) -> u64 {
const BLOCK: u64 = 0x20000;
size.div_ceil(BLOCK)
}
pub fn install(
plan: &ZynqPlan,
remote: &mut dyn Remote,
options: &ZynqInstallOptions,
host: &str,
) -> Result<ZynqOutcome, ZynqError> {
let report = preflight(plan, remote, host)?;
if !report.ok() {
return Err(ZynqError::Preflight(report.render()));
}
if options.dry_run {
return Ok(ZynqOutcome::DryRun(Box::new(report)));
}
if options.confirm.as_deref() != Some("FLASH") {
return Err(ZynqError::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 {
// Hard guard, right before touching NAND: never below BOOT.bin on mtd0.
if target.device == "/dev/mtd0" && target.offset < BOOTBIN_PRESERVE {
return Err(ZynqError::BootbinGuard {
device: target.device.clone(),
offset: target.offset,
bootbin: BOOTBIN_PRESERVE,
});
}
let name = &target.image_name;
let device = &target.device;
let offset = target.offset;
// Back up the region we are about to overwrite, offset-aware.
let remote_backup = format!("/tmp/.alkane-z-{name}-backup.img");
remote.root_command(
&format!(
"/usr/sbin/nanddump --omitoob --bb=skipbad --start=0x{offset:x} --length={} -f {remote_backup} {device}",
target.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)?;
let md5 = md5_hex(&data);
backups.push(ZynqBackup {
image_name: name.clone(),
device: device.clone(),
offset,
path: local,
md5,
size: target.size,
});
// Stage the verified payload and prove its remote md5 before writing.
let mut staged = tempfile::NamedTempFile::new()?;
staged.write_all(&target.data)?;
staged.flush()?;
let remote_stage = format!("/tmp/.alkane-z-{name}-stage.img");
remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?;
let staged_md5 = parse_digest(
&remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?,
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(ZynqError::StageMismatch(name.clone()));
}
// Erase and write exactly the region at its offset. flash_erase takes an
// offset + block count, so BOOT.bin (below the offset) is never touched.
let blocks = erase_blocks(target.size);
remote.root_command(
&format!("/usr/sbin/flash_erase {device} 0x{offset:x} {blocks}"),
Duration::from_secs(300),
)?;
remote.root_command(
&format!("/usr/sbin/nandwrite -p --start=0x{offset:x} {device} {remote_stage} && sync"),
Duration::from_secs(300),
)?;
// Read back exactly what we wrote and compare.
let remote_readback = format!("/tmp/.alkane-z-{name}-readback.img");
remote.root_command(
&format!(
"/usr/sbin/nanddump --omitoob --bb=skipbad --start=0x{offset:x} --length={} -f {remote_readback} {device}",
target.size
),
Duration::from_secs(300),
)?;
let readback = parse_digest(
&remote.root_command(&format!("md5sum {remote_readback}"), Duration::from_secs(60))?,
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(ZynqError::Readback(name.clone()));
}
}
let rebooted = if options.no_reboot {
false
} else {
remote.reboot()?;
true
};
Ok(ZynqOutcome::Installed(ZynqReceipt { backups, rebooted }))
}
pub fn owns_board(board: &str) -> bool {
board == BOARD
}
@@ -497,8 +255,8 @@ pub fn owns_board(board: &str) -> bool {
mod tests {
use super::*;
use alkane_artifacts::afw::{AfwManifest, AfwMember};
use sha2::{Digest, Sha256};
use serde_json::json;
use sha2::{Digest, Sha256};
const REV: &str = "0123456789abcdef0123456789abcdef01234567";
@@ -511,7 +269,10 @@ mod tests {
fn afw(kernel: Vec<u8>, dtb: Vec<u8>, rootfs: Vec<u8>) -> VerifiedAfw {
let image = |name: &str, file: &str, role: &str, fmt: &str, data: &[u8]| {
let sha: String = Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect();
let sha: String = Sha256::digest(data)
.iter()
.map(|b| format!("{b:02x}"))
.collect();
json!({"name": name, "file": file, "role": role, "format": fmt,
"size": data.len(), "sha256": sha, "partition": "x", "install": true})
};
@@ -534,9 +295,18 @@ mod tests {
VerifiedAfw {
manifest,
members: vec![
AfwMember { name: "payload/zImage".to_owned(), data: kernel },
AfwMember { name: "payload/zynq-alkane.dtb".to_owned(), data: dtb },
AfwMember { name: "payload/rootfs.cpio.gz".to_owned(), data: rootfs },
AfwMember {
name: "payload/zImage".to_owned(),
data: kernel,
},
AfwMember {
name: "payload/zynq-alkane.dtb".to_owned(),
data: dtb,
},
AfwMember {
name: "payload/rootfs.cpio.gz".to_owned(),
data: rootfs,
},
],
manifest_sha256: "0".repeat(64),
archive_sha256: "0".repeat(64),
@@ -557,11 +327,32 @@ mod tests {
assert_eq!(plan.targets[0].image_name, "rootfs");
assert_eq!(plan.targets[2].image_name, "kernel");
for t in &plan.targets {
if t.device == "/dev/mtd0" {
assert!(t.offset >= BOOTBIN_PRESERVE, "{} below BOOT.bin", t.image_name);
}
assert!(
t.absolute >= BOOTBIN_PRESERVE,
"{} below BOOT.bin",
t.image_name
);
}
assert!(plan.render().contains("BOOT.bin"));
let render = plan.render();
assert!(render.contains("BOOT.bin"));
assert!(render.contains("uImage"));
}
#[test]
fn slots_match_the_stock_uboot_layout() {
let plan = ZynqPlan::from_afw(&afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec())).unwrap();
let at = |name: &str| plan.targets.iter().find(|t| t.image_name == name).unwrap();
assert_eq!((at("dtb").absolute, at("dtb").slot), (0x1A00000, 0x20000));
assert_eq!(
(at("kernel").absolute, at("kernel").slot),
(0x2000000, 0x800000)
);
assert_eq!(
(at("rootfs").absolute, at("rootfs").slot),
(0x2800000, 0x2000000)
);
assert!(at("kernel").uimage_wrapped && at("rootfs").uimage_wrapped);
assert!(!at("dtb").uimage_wrapped);
}
#[test]
@@ -571,37 +362,49 @@ mod tests {
}
#[test]
fn refuses_an_oversize_kernel() {
// Over the kernel-slot ceiling (0x800000).
let big = zimage(&vec![0u8; 0x800001]);
fn refuses_a_kernel_that_would_not_fit_with_its_uimage_header() {
// Exactly the slot size is too big once the 64-byte header is added.
let big = zimage(&vec![0u8; 0x800000 - 64]);
assert_eq!(big.len(), 0x800000);
let result = ZynqPlan::from_afw(&afw(big, dtb(), b"\x1f\x8brf".to_vec()));
assert!(matches!(result, Err(ZynqPlanError::ImageTooLarge { .. })));
let fits = zimage(&vec![0u8; 0x800000 - 128]);
assert!(ZynqPlan::from_afw(&afw(fits, dtb(), b"\x1f\x8brf".to_vec())).is_ok());
}
#[test]
fn refuses_a_bootloader_member() {
let mut verified = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
verified.manifest.images[0].role = "bootloader".to_owned();
assert!(matches!(ZynqPlan::from_afw(&verified), Err(ZynqPlanError::BootloaderMember(_))));
assert!(matches!(
ZynqPlan::from_afw(&verified),
Err(ZynqPlanError::BootloaderMember(_))
));
}
#[test]
fn wrong_board_and_arch_are_refused() {
let mut v = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
v.manifest.board = "am335x".to_owned();
assert!(matches!(ZynqPlan::from_afw(&v), Err(ZynqPlanError::WrongBoard(_))));
assert!(matches!(
ZynqPlan::from_afw(&v),
Err(ZynqPlanError::WrongBoard(_))
));
let mut v = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
v.manifest.arch = "arm".to_owned();
assert!(matches!(ZynqPlan::from_afw(&v), Err(ZynqPlanError::WrongArch(_))));
assert!(matches!(
ZynqPlan::from_afw(&v),
Err(ZynqPlanError::WrongArch(_))
));
}
#[test]
fn every_mtd0_target_is_above_bootbin() {
// Compile-time-ish guarantee from the TARGETS table.
for (image, device, offset, _ceiling, _fmt) in TARGETS {
if device == "/dev/mtd0" {
assert!(offset >= BOOTBIN_PRESERVE, "{image} target below BOOT.bin");
}
fn every_target_is_above_bootbin() {
for (image, absolute, _slot, _fmt, _wrapped) in TARGETS {
assert!(
absolute >= BOOTBIN_PRESERVE,
"{image} target below BOOT.bin"
);
}
}
}
+122 -5
View File
@@ -14,7 +14,7 @@
//! network-only.
use alkane_artifacts::afw::VerifiedAfw;
use std::path::Path;
use std::path::{Path, PathBuf};
use thiserror::Error;
#[derive(Debug, Error)]
@@ -31,15 +31,94 @@ pub enum StockError {
Io(String),
}
/// The genuine Bitmain stock images to write back when restoring to stock,
/// parsed from a vendor firmware package by `stock_firmware`. Borrowed so the
/// large rootfs is not copied before the method needs it.
/// The genuine Bitmain stock kernel and rootfs to write back when restoring to
/// stock, parsed from a vendor firmware package (OTA or SD) by `stock_firmware`.
/// The matching NAND device tree is NOT taken from the package: Bitmain never
/// ships the kernel device tree in its distributable firmware (it is factory-
/// provisioned and preserved by every update), so the method supplies the
/// correct per-board dtb itself. Borrowed so the large rootfs is not copied
/// before the method needs it.
pub struct RestoreImages<'a> {
pub dtb: &'a [u8],
pub kernel: &'a [u8],
pub rootfs: &'a [u8],
}
/// Options for updating a board that already runs alkane, in place.
#[derive(Clone, Debug, Default)]
pub struct InPlaceOptions {
/// Read-only: report the board state, the storage map and the write plan,
/// and write nothing.
pub dry_run: bool,
/// Reboot after the images are written and read back, then wait for the
/// board to return as alkane.
pub reboot: bool,
/// Where to keep a copy of each boot slot as it was before the write. When
/// set, every slot is read and saved before any erase; a failed backup
/// aborts the update with nothing written.
pub backup_dir: Option<PathBuf>,
}
/// One boot slot as it was before an in-place update.
#[derive(Clone, Debug)]
pub struct HeldSlot {
pub name: String,
/// Absolute NAND offset of the slot.
pub absolute: u64,
pub size: u64,
pub path: PathBuf,
pub md5: String,
}
#[derive(Clone, Debug)]
pub struct InPlaceReceipt {
pub backups: Vec<HeldSlot>,
pub rebooted: bool,
}
#[derive(Clone, Debug)]
pub enum InPlaceOutcome {
/// The dry-run report; nothing was written.
DryRun(String),
Updated(InPlaceReceipt),
}
/// Result of a live check that a Zynq board is up on alkane: two channels
/// (HTTP page marker, SSH kernel/OS) must agree.
#[derive(Clone, Debug)]
pub struct LiveCheck {
pub attempts: u32,
pub http: String,
pub http_ok: bool,
pub ssh: String,
pub ssh_ok: bool,
/// The running kernel command line (informational: on a NAND boot it is
/// the board's U-Boot env bootargs).
pub cmdline: String,
}
impl LiveCheck {
pub fn ok(&self) -> bool {
self.http_ok && self.ssh_ok
}
pub fn render(&self) -> String {
format!(
"verify-live attempts {}\n http {}: {}\n ssh {}: {}\n cmdline: {}\nresult {}\n",
self.attempts,
if self.http_ok { "PASS" } else { "FAIL" },
self.http,
if self.ssh_ok { "PASS" } else { "FAIL" },
self.ssh,
if self.cmdline.is_empty() {
"(not read)"
} else {
&self.cmdline
},
if self.ok() { "PASS" } else { "FAIL" }
)
}
}
/// The stock-side methods, implemented by `stock_method`. All implementations
/// must be NETWORK-ONLY (no serial-console dependency).
pub trait StockMethod {
@@ -64,6 +143,20 @@ pub trait StockMethod {
images: &RestoreImages,
password: Option<&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
/// exposed to Linux on alkane, so they are re-registered the same way as for
/// a restore; the images are written in the form the board's stock U-Boot
/// boots, each read back before reboot, and BOOT.bin is never written.
fn update_in_place(
&self,
host: &str,
afw: &VerifiedAfw,
password: Option<&str>,
options: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError>;
}
/// The compiled-in method implementation.
@@ -91,6 +184,30 @@ pub fn restore_to_stock(
method().restore_to_stock(host, images, password)
}
/// Check, over the network, that a Zynq board is up on alkane: the web page
/// carries `marker` (case-insensitive) and SSH reports alkane with a kernel
/// containing `kernel_version` (if non-empty). Retries until `timeout`.
pub fn verify_zynq_live(
host: &str,
password: Option<&str>,
marker: &str,
kernel_version: &str,
timeout: std::time::Duration,
) -> Result<LiveCheck, StockError> {
crate::stock_method::live_check(host, password, marker, kernel_version, timeout)
}
/// Update a board already on alkane to the `.afw`'s images, in place
/// (network-only), via the compiled-in method.
pub fn update_in_place(
host: &str,
afw: &VerifiedAfw,
password: Option<&str>,
options: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError> {
method().update_in_place(host, afw, password, options)
}
#[cfg(test)]
mod tests {
use super::*;
+30 -11
View File
@@ -145,8 +145,8 @@ fn read(path: &Path) -> Result<Vec<u8>, StockFirmwareError> {
/// Parse a genuine Bitmain stock firmware package (OTA `.tar.gz` or SD `.zip`)
/// into its stock images.
pub fn parse(path: &Path) -> Result<StockFirmware, StockFirmwareError> {
let bytes =
std::fs::read(path).map_err(|e| StockFirmwareError::Io(format!("{}: {e}", path.display())))?;
let bytes = std::fs::read(path)
.map_err(|e| StockFirmwareError::Io(format!("{}: {e}", path.display())))?;
if bytes.len() < 4 {
return Err(StockFirmwareError::Format(path.display().to_string()));
}
@@ -167,7 +167,12 @@ pub fn parse(path: &Path) -> Result<StockFirmware, StockFirmwareError> {
return Err(StockFirmwareError::MissingTool("unzip".into()));
}
run(
Command::new("unzip").arg("-qq").arg("-o").arg(path).arg("-d").arg(root),
Command::new("unzip")
.arg("-qq")
.arg("-o")
.arg(path)
.arg("-d")
.arg(root),
"unzip SD recovery image",
)?;
("Bitmain SD recovery image", &["bin/"])
@@ -185,9 +190,14 @@ pub fn parse(path: &Path) -> Result<StockFirmware, StockFirmwareError> {
.find(|(rel, _)| rel.rsplit('/').next() == Some("fw.tar.gz"));
if let Some((_, inner_path)) = inner {
let inner_dir = root.join("fw");
std::fs::create_dir_all(&inner_dir).map_err(|e| StockFirmwareError::Io(e.to_string()))?;
std::fs::create_dir_all(&inner_dir)
.map_err(|e| StockFirmwareError::Io(e.to_string()))?;
run(
Command::new("tar").arg("xzf").arg(&inner_path).arg("-C").arg(&inner_dir),
Command::new("tar")
.arg("xzf")
.arg(&inner_path)
.arg("-C")
.arg(&inner_dir),
"untar OTA inner fw.tar.gz",
)?;
}
@@ -196,13 +206,19 @@ pub fn parse(path: &Path) -> Result<StockFirmware, StockFirmwareError> {
let files = collect_files(root);
let kernel_path = pick(&files, "uImage", prefer).ok_or(StockFirmwareError::MissingImage("uImage (kernel)"))?;
let rootfs_path =
pick(&files, "uramdisk.image.gz", prefer).ok_or(StockFirmwareError::MissingImage("uramdisk.image.gz (rootfs)"))?;
let kernel_path = pick(&files, "uImage", prefer)
.ok_or(StockFirmwareError::MissingImage("uImage (kernel)"))?;
let rootfs_path = pick(&files, "uramdisk.image.gz", prefer).ok_or(
StockFirmwareError::MissingImage("uramdisk.image.gz (rootfs)"),
)?;
let kernel = read(kernel_path)?;
let rootfs = read(rootfs_path)?;
let boot_bin = pick(&files, "BOOT.bin", prefer).map(|p| read(p)).transpose()?;
let dtb = pick(&files, "devicetree.dtb", &["", "bin/"]).map(|p| read(p)).transpose()?;
let boot_bin = pick(&files, "BOOT.bin", prefer)
.map(|p| read(p))
.transpose()?;
let dtb = pick(&files, "devicetree.dtb", &["", "bin/"])
.map(|p| read(p))
.transpose()?;
// Verify the rootfs against md5_info when the package ships one (OTA does).
if let Some(md5_path) = pick(&files, "md5_info", prefer) {
@@ -241,7 +257,10 @@ mod tests {
fn rejects_non_archive() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), b"not an archive").unwrap();
assert!(matches!(parse(tmp.path()), Err(StockFirmwareError::Format(_))));
assert!(matches!(
parse(tmp.path()),
Err(StockFirmwareError::Format(_))
));
}
// Parse a real Bitmain firmware package. Set ALKANE_TEST_STOCK_FW to its path.
+650 -96
View File
@@ -15,7 +15,10 @@
//! bitstream and U-Boot). Every write target in this module is checked to sit
//! at or above that boundary before any erase or write is issued.
use crate::stock::{RestoreImages, StockError, StockMethod};
use crate::stock::{
HeldSlot, InPlaceOptions, InPlaceOutcome, InPlaceReceipt, RestoreImages, StockError,
StockMethod,
};
use alkane_artifacts::afw::VerifiedAfw;
use std::borrow::Cow;
use std::env;
@@ -51,9 +54,16 @@ struct StockAsset {
sha256: &'static str,
}
// The stock kernel/dtb/rootfs are no longer carried as assets: restore now
// writes the genuine Bitmain stock images supplied by the caller. Only the
// NAND-exposing helper (below) is still fetched.
// Restore writes the genuine Bitmain kernel and rootfs supplied by the caller.
// Two small per-board pieces are not in Bitmain's distributable firmware and are
// fetched: the NAND-exposing helper, and the kernel device tree (factory-
// provisioned, preserved by every vendor update, so never shipped in an OTA/SD
// package). The dtb is what pairs the genuine kernel/rootfs to the board's
// partition layout; writing the wrong one reboot-loops the board.
const ASSET_DTB: StockAsset = StockAsset {
file: "blob-1.bin",
sha256: "10a0199be8a638c4bf319a623362a89b6bee38f732ab00204df499a2f25ad2ea",
};
const ASSET_MTD_PATCH: StockAsset = StockAsset {
file: "blob-4.bin",
sha256: "51cfa6806ac0618d67a3d6f2383bc755c67507958c578fc899a25e589c9cf444",
@@ -71,7 +81,11 @@ fn stock_token() -> Option<String> {
env::var("ALKANE_RELEASE_TOKEN")
.ok()
.filter(|token| !token.is_empty())
.or_else(|| env::var("GITEA_TOKEN").ok().filter(|token| !token.is_empty()))
.or_else(|| {
env::var("GITEA_TOKEN")
.ok()
.filter(|token| !token.is_empty())
})
}
fn asset_cache_dir() -> Result<PathBuf, StockError> {
@@ -283,17 +297,70 @@ struct Sha256 {
impl Sha256 {
const K: [u32; 64] = [
0x428a_2f98, 0x7137_4491, 0xb5c0_fbcf, 0xe9b5_dba5, 0x3956_c25b, 0x59f1_11f1,
0x923f_82a4, 0xab1c_5ed5, 0xd807_aa98, 0x1283_5b01, 0x2431_85be, 0x550c_7dc3,
0x72be_5d74, 0x80de_b1fe, 0x9bdc_06a7, 0xc19b_f174, 0xe49b_69c1, 0xefbe_4786,
0x0fc1_9dc6, 0x240c_a1cc, 0x2de9_2c6f, 0x4a74_84aa, 0x5cb0_a9dc, 0x76f9_88da,
0x983e_5152, 0xa831_c66d, 0xb003_27c8, 0xbf59_7fc7, 0xc6e0_0bf3, 0xd5a7_9147,
0x06ca_6351, 0x1429_2967, 0x27b7_0a85, 0x2e1b_2138, 0x4d2c_6dfc, 0x5338_0d13,
0x650a_7354, 0x766a_0abb, 0x81c2_c92e, 0x9272_2c85, 0xa2bf_e8a1, 0xa81a_664b,
0xc24b_8b70, 0xc76c_51a3, 0xd192_e819, 0xd699_0624, 0xf40e_3585, 0x106a_a070,
0x19a4_c116, 0x1e37_6c08, 0x2748_774c, 0x34b0_bcb5, 0x391c_0cb3, 0x4ed8_aa4a,
0x5b9c_ca4f, 0x682e_6ff3, 0x748f_82ee, 0x78a5_636f, 0x84c8_7814, 0x8cc7_0208,
0x90be_fffa, 0xa450_6ceb, 0xbef9_a3f7, 0xc671_78f2,
0x428a_2f98,
0x7137_4491,
0xb5c0_fbcf,
0xe9b5_dba5,
0x3956_c25b,
0x59f1_11f1,
0x923f_82a4,
0xab1c_5ed5,
0xd807_aa98,
0x1283_5b01,
0x2431_85be,
0x550c_7dc3,
0x72be_5d74,
0x80de_b1fe,
0x9bdc_06a7,
0xc19b_f174,
0xe49b_69c1,
0xefbe_4786,
0x0fc1_9dc6,
0x240c_a1cc,
0x2de9_2c6f,
0x4a74_84aa,
0x5cb0_a9dc,
0x76f9_88da,
0x983e_5152,
0xa831_c66d,
0xb003_27c8,
0xbf59_7fc7,
0xc6e0_0bf3,
0xd5a7_9147,
0x06ca_6351,
0x1429_2967,
0x27b7_0a85,
0x2e1b_2138,
0x4d2c_6dfc,
0x5338_0d13,
0x650a_7354,
0x766a_0abb,
0x81c2_c92e,
0x9272_2c85,
0xa2bf_e8a1,
0xa81a_664b,
0xc24b_8b70,
0xc76c_51a3,
0xd192_e819,
0xd699_0624,
0xf40e_3585,
0x106a_a070,
0x19a4_c116,
0x1e37_6c08,
0x2748_774c,
0x34b0_bcb5,
0x391c_0cb3,
0x4ed8_aa4a,
0x5b9c_ca4f,
0x682e_6ff3,
0x748f_82ee,
0x78a5_636f,
0x84c8_7814,
0x8cc7_0208,
0x90be_fffa,
0xa450_6ceb,
0xbef9_a3f7,
0xc671_78f2,
];
fn new() -> Self {
@@ -432,11 +499,15 @@ impl TempDir {
Ok(()) => return Ok(Self { path }),
Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
Err(e) => {
return Err(StockError::Io(format!("could not create a temporary directory: {e}")))
return Err(StockError::Io(format!(
"could not create a temporary directory: {e}"
)))
}
}
}
Err(StockError::Io("could not create a temporary directory".into()))
Err(StockError::Io(
"could not create a temporary directory".into(),
))
}
fn path(&self) -> &Path {
@@ -674,7 +745,12 @@ fn ssh_exec(
}
fn ssh_probe(host: &str, password: Option<&str>) -> Result<(), StockError> {
let result = ssh_exec(host, password, "echo __ALKANE_OK__", Duration::from_secs(20))?;
let result = ssh_exec(
host,
password,
"echo __ALKANE_OK__",
Duration::from_secs(20),
)?;
if result.ok() && text(&result.stdout).contains("__ALKANE_OK__") {
return Ok(());
}
@@ -791,13 +867,7 @@ fn is_alkane_ssh(host: &str) -> bool {
fn is_stock_http(host: &str) -> bool {
let mut command = Command::new("curl");
command.args([
"-sS",
"-i",
"--max-time",
"6",
&format!("http://{host}/"),
]);
command.args(["-sS", "-i", "--max-time", "6", &format!("http://{host}/")]);
match run_command(command, Duration::from_secs(12), None) {
Ok(result) => {
let lower = text(&result.stdout).to_lowercase();
@@ -843,12 +913,7 @@ fn http_code(result: &CmdResult) -> u16 {
text(&result.stdout).trim().parse::<u16>().unwrap_or(0)
}
fn stock_web_auth(
host: &str,
password: &str,
dir: &Path,
tag: &str,
) -> Result<(), StockError> {
fn stock_web_auth(host: &str, password: &str, dir: &Path, tag: &str) -> Result<(), StockError> {
let config = dir.join(format!("auth-{tag}.cfg"));
let output = dir.join(format!("auth-{tag}.out"));
write_curl_config(
@@ -869,7 +934,9 @@ fn stock_web_auth(
200..=299 => Ok(()),
401 | 403 => Err(StockError::Auth("target rejected the credential".into())),
0 => Err(StockError::Network("target unreachable".into())),
_ => Err(StockError::Method("target web interface unavailable".into())),
_ => Err(StockError::Method(
"target web interface unavailable".into(),
)),
}
}
@@ -892,7 +959,10 @@ fn stock_web_upload(
"location".to_string(),
"max-redirs = 5".to_string(),
"max-time = 600".to_string(),
format!("url = {}", curl_quote(&format!("http://{host}/cgi-bin/upgrade.cgi"))),
format!(
"url = {}",
curl_quote(&format!("http://{host}/cgi-bin/upgrade.cgi"))
),
format!("user = {}", curl_quote(&format!("root:{password}"))),
format!(
"header = {}",
@@ -901,7 +971,10 @@ fn stock_web_upload(
))
),
"header = \"Expect:\"".to_string(),
format!("data-binary = {}", curl_quote(&format!("@{}", body.display()))),
format!(
"data-binary = {}",
curl_quote(&format!("@{}", body.display()))
),
format!("output = {}", curl_quote(&output.to_string_lossy())),
"write-out = \"%{http_code}\"".to_string(),
],
@@ -932,7 +1005,10 @@ fn stock_web_trigger(
"location".to_string(),
"max-redirs = 5".to_string(),
"max-time = 900".to_string(),
format!("url = {}", curl_quote(&format!("http://{host}/cgi-bin/{cgi}"))),
format!(
"url = {}",
curl_quote(&format!("http://{host}/cgi-bin/{cgi}"))
),
format!("user = {}", curl_quote(&format!("root:{password}"))),
],
)?;
@@ -952,9 +1028,7 @@ fn afw_payload<'a>(afw: &'a VerifiedAfw, image: &str, file: &str) -> Option<&'a
afw.payload(short)
}
fn load_install_images(
afw: &VerifiedAfw,
) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>), StockError> {
fn load_install_images(afw: &VerifiedAfw) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>), StockError> {
if afw.manifest.board != BOARD {
return Err(StockError::Method("image is not for this target".into()));
}
@@ -1065,22 +1139,75 @@ impl Md5 {
fn compress(&mut self, block: &[u8; 64]) {
const S: [u32; 64] = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14,
20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11,
16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20,
5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
];
const K: [u32; 64] = [
0xd76a_a478, 0xe8c7_b756, 0x2420_70db, 0xc1bd_ceee, 0xf57c_0faf, 0x4787_c62a,
0xa830_4613, 0xfd46_9501, 0x6980_98d8, 0x8b44_f7af, 0xffff_5bb1, 0x895c_d7be,
0x6b90_1122, 0xfd98_7193, 0xa679_438e, 0x49b4_0821, 0xf61e_2562, 0xc040_b340,
0x265e_5a51, 0xe9b6_c7aa, 0xd62f_105d, 0x0244_1453, 0xd8a1_e681, 0xe7d3_fbc8,
0x21e1_cde6, 0xc337_07d6, 0xf4d5_0d87, 0x455a_14ed, 0xa9e3_e905, 0xfcef_a3f8,
0x676f_02d9, 0x8d2a_4c8a, 0xfffa_3942, 0x8771_f681, 0x6d9d_6122, 0xfde5_380c,
0xa4be_ea44, 0x4bde_cfa9, 0xf6bb_4b60, 0xbebf_bc70, 0x289b_7ec6, 0xeaa1_27fa,
0xd4ef_3085, 0x0488_1d05, 0xd9d4_d039, 0xe6db_99e5, 0x1fa2_7cf8, 0xc4ac_5665,
0xf429_2244, 0x432a_ff97, 0xab94_23a7, 0xfc93_a039, 0x655b_59c3, 0x8f0c_cc92,
0xffef_f47d, 0x8584_5dd1, 0x6fa8_7e4f, 0xfe2c_e6e0, 0xa301_4314, 0x4e08_11a1,
0xf753_7e82, 0xbd3a_f235, 0x2ad7_d2bb, 0xeb86_d391,
0xd76a_a478,
0xe8c7_b756,
0x2420_70db,
0xc1bd_ceee,
0xf57c_0faf,
0x4787_c62a,
0xa830_4613,
0xfd46_9501,
0x6980_98d8,
0x8b44_f7af,
0xffff_5bb1,
0x895c_d7be,
0x6b90_1122,
0xfd98_7193,
0xa679_438e,
0x49b4_0821,
0xf61e_2562,
0xc040_b340,
0x265e_5a51,
0xe9b6_c7aa,
0xd62f_105d,
0x0244_1453,
0xd8a1_e681,
0xe7d3_fbc8,
0x21e1_cde6,
0xc337_07d6,
0xf4d5_0d87,
0x455a_14ed,
0xa9e3_e905,
0xfcef_a3f8,
0x676f_02d9,
0x8d2a_4c8a,
0xfffa_3942,
0x8771_f681,
0x6d9d_6122,
0xfde5_380c,
0xa4be_ea44,
0x4bde_cfa9,
0xf6bb_4b60,
0xbebf_bc70,
0x289b_7ec6,
0xeaa1_27fa,
0xd4ef_3085,
0x0488_1d05,
0xd9d4_d039,
0xe6db_99e5,
0x1fa2_7cf8,
0xc4ac_5665,
0xf429_2244,
0x432a_ff97,
0xab94_23a7,
0xfc93_a039,
0x655b_59c3,
0x8f0c_cc92,
0xffef_f47d,
0x8584_5dd1,
0x6fa8_7e4f,
0xfe2c_e6e0,
0xa301_4314,
0x4e08_11a1,
0xf753_7e82,
0xbd3a_f235,
0x2ad7_d2bb,
0xeb86_d391,
];
let mut words = [0u32; 16];
@@ -1116,7 +1243,11 @@ impl Md5 {
let bit_length = self.length.wrapping_mul(8);
let mut padding = vec![0x80u8];
let remaining = (self.used + 1) % 64;
let pad_len = if remaining <= 56 { 56 - remaining } else { 120 - remaining };
let pad_len = if remaining <= 56 {
56 - remaining
} else {
120 - remaining
};
padding.extend(std::iter::repeat(0u8).take(pad_len));
padding.extend_from_slice(&bit_length.to_le_bytes());
let saved_length = self.length;
@@ -1251,7 +1382,11 @@ struct TarEntry {
fn build_tar(entries: &[TarEntry]) -> Vec<u8> {
let mut out = Vec::new();
for entry in entries {
let size = if entry.kind == b'0' { entry.data.len() as u64 } else { 0 };
let size = if entry.kind == b'0' {
entry.data.len() as u64
} else {
0
};
let header = tar_header(&entry.name, entry.mode, size, entry.kind, &entry.link);
out.extend_from_slice(&header);
if entry.kind == b'0' {
@@ -1277,6 +1412,7 @@ struct FlashTarget {
file: &'static str,
device: String,
rel: u64,
absolute: u64,
slot: u64,
data: Cow<'static, [u8]>,
raw_md5: String,
@@ -1330,7 +1466,9 @@ fn read_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockErr
});
}
if map.is_empty() {
return Err(StockError::Method("target storage layout unsupported".into()));
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
Ok(map)
}
@@ -1409,13 +1547,15 @@ fn make_target(
"refusing to write the boot region".into(),
));
}
if !device.starts_with("/dev/")
|| !device[5..].chars().all(|c| c.is_ascii_alphanumeric())
{
return Err(StockError::Method("target storage layout unsupported".into()));
if !device.starts_with("/dev/") || !device[5..].chars().all(|c| c.is_ascii_alphanumeric()) {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
if rel % BLK != 0 || slot == 0 || slot % BLK != 0 {
return Err(StockError::Method("target storage layout unsupported".into()));
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
let blocks = (data.len() as u64).div_ceil(BLK);
if blocks == 0 || blocks * BLK > slot {
@@ -1428,6 +1568,7 @@ fn make_target(
file,
device,
rel,
absolute,
slot,
data,
raw_md5,
@@ -1644,9 +1785,7 @@ fn install_via_web(
}
let password = match chosen {
Some(password) => password,
None if last_auth => {
return Err(StockError::Auth("target rejected the credential".into()))
}
None if last_auth => return Err(StockError::Auth("target rejected the credential".into())),
None => return Err(StockError::Network("target unreachable".into())),
};
@@ -1658,14 +1797,7 @@ fn install_via_web(
let body_path = dir.join("upload.body");
write_private(&body_path, &body)?;
stock_web_upload(
host,
&password,
dir.path(),
&body_path,
&boundary,
&token,
)?;
stock_web_upload(host, &password, dir.path(), &body_path, &boundary, &token)?;
let trigger = stock_web_trigger(host, &password, dir.path(), &cgi, &token)?;
let output = text(&trigger.stdout);
if output.contains("@@FAIL@@") {
@@ -1678,14 +1810,16 @@ fn install_via_web(
}
}
fn install_via_ssh(
host: &str,
password: Option<&str>,
/// 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
/// forms from `load_install_images`.
fn alkane_targets(
map: &[Mtd],
kernel: Vec<u8>,
dtb: Vec<u8>,
rootfs: Vec<u8>,
) -> Result<(), StockError> {
let map = get_mtd_map(host, password)?;
) -> Result<Vec<FlashTarget>, StockError> {
let images = vec![
(
"rootfs",
@@ -1703,7 +1837,18 @@ fn install_via_ssh(
Cow::Owned(kernel),
),
];
let targets = targets_from_map(&map, images)?;
targets_from_map(map, images)
}
fn install_via_ssh(
host: &str,
password: Option<&str>,
kernel: Vec<u8>,
dtb: Vec<u8>,
rootfs: Vec<u8>,
) -> Result<(), StockError> {
let map = get_mtd_map(host, password)?;
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
flash_via_ssh(host, password, &targets)?;
reboot_target(host, password);
if wait_alkane(host, Duration::from_secs(240)) {
@@ -1718,7 +1863,12 @@ fn flash_via_ssh(
password: Option<&str>,
targets: &[FlashTarget],
) -> Result<(), StockError> {
let prep = ssh_exec(host, password, "mkdir -p /tmp/rs; rm -f /tmp/rs/*", Duration::from_secs(20))?;
let prep = ssh_exec(
host,
password,
"mkdir -p /tmp/rs; rm -f /tmp/rs/*",
Duration::from_secs(20),
)?;
if !prep.ok() {
return Err(classify_ssh(&prep));
}
@@ -1736,12 +1886,7 @@ fn flash_via_ssh(
script.as_bytes(),
Duration::from_secs(30),
)?;
let result = ssh_exec(
host,
password,
"sh /tmp/rs/go.sh",
Duration::from_secs(900),
)?;
let result = ssh_exec(host, password, "sh /tmp/rs/go.sh", Duration::from_secs(900))?;
let output = text(&result.stdout);
if output.contains("@@OK@@") && !output.contains("@@FAIL@@") {
return Ok(());
@@ -1752,6 +1897,288 @@ fn flash_via_ssh(
Err(classify_ssh(&result))
}
/// Read each target's whole slot as it is now and keep it under `dir`, before
/// anything is erased. Any short read or local write failure is an error, so
/// the caller aborts with nothing written.
fn hold_slots(
host: &str,
password: Option<&str>,
targets: &[FlashTarget],
dir: &Path,
) -> Result<Vec<HeldSlot>, StockError> {
fs::create_dir_all(dir)
.map_err(|e| StockError::Io(format!("could not create the backup directory: {e}")))?;
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let safe_host: String = host
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '.' {
c
} else {
'_'
}
})
.collect();
let mut held = Vec::with_capacity(targets.len());
for target in targets {
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null",
target.device,
BLK,
target.rel / BLK,
target.slot / BLK
);
let result = ssh_exec(host, password, &remote, Duration::from_secs(600))?;
if !result.ok() {
return Err(classify_ssh(&result));
}
if result.stdout.len() as u64 != target.slot {
return Err(StockError::Method(format!(
"backup of the {} slot was short ({} of {} bytes); nothing was written",
target.name,
result.stdout.len(),
target.slot
)));
}
let absolute = target.absolute;
let path = dir.join(format!(
"zynq-{safe_host}-{}-0x{absolute:x}-{stamp}.img",
target.name
));
write_private_new(&path, &result.stdout)?;
held.push(HeldSlot {
name: target.name.to_string(),
absolute,
size: target.slot,
path,
md5: md5_hex(&result.stdout),
});
}
Ok(held)
}
fn render_map(map: &[Mtd]) -> String {
let mut out = String::new();
for mtd in map {
out.push_str(&format!(
" {} 0x{:08x}..0x{:08x} (0x{:x})\n",
mtd.device,
mtd.offset,
mtd.offset + mtd.size,
mtd.size
));
}
out
}
fn render_targets(targets: &[FlashTarget]) -> String {
let mut out = String::new();
for t in targets {
out.push_str(&format!(
" {:<6} -> {} +0x{:x} (abs 0x{:x}) slot 0x{:x}, {} bytes, md5 {}\n",
t.name,
t.device,
t.rel,
t.absolute,
t.slot,
t.data.len(),
t.raw_md5
));
}
out
}
/// Planned images in absolute NAND terms, independent of how the board's
/// partitions are currently registered.
fn render_absolute_plan(kernel: &[u8], dtb: &[u8], rootfs: &[u8]) -> String {
let mut out = String::new();
for (name, absolute, slot, data) in [
("rootfs", ABS_ROOTFS, ROOTFS_SLOT, rootfs),
("dtb", ABS_DTB, DTB_SLOT, dtb),
("kernel", ABS_KERNEL, KERNEL_SLOT, kernel),
] {
out.push_str(&format!(
" {:<6} -> abs 0x{:x} slot 0x{:x}, {} bytes, md5 {}\n",
name,
absolute,
slot,
data.len(),
md5_hex(data)
));
}
out
}
fn update_in_place_impl(
host: &str,
afw: &VerifiedAfw,
password: Option<&str>,
options: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError> {
validate_host(host)?;
let (kernel, dtb, rootfs) = load_install_images(afw)?;
if !ssh_port_open(host) {
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 != "alkane" {
return Err(StockError::Method(format!(
"the board is not running alkane (detected: {state}); a board on stock is installed with --from-stock"
)));
}
if options.dry_run {
let map = read_mtd_map(host, password)?;
let mut report = String::new();
report.push_str(&format!("board {host}: running alkane\n"));
report.push_str("storage as registered now:\n");
report.push_str(&render_map(&map));
if map_covers_boot_regions(&map) {
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
report.push_str("boot regions are registered; writes would go to:\n");
report.push_str(&render_targets(&targets));
} else {
report.push_str(
"boot regions are NOT registered (normal on alkane); the update re-registers \
them first, as a restore does, then writes:\n",
);
report.push_str(&render_absolute_plan(&kernel, &dtb, &rootfs));
}
report.push_str(&format!(
"BOOT.bin (abs 0x0..0x{BOOTBIN_PRESERVE:x}) is never written.\n"
));
if options.backup_dir.is_some() {
report.push_str("each slot would be saved locally before any erase.\n");
}
return Ok(InPlaceOutcome::DryRun(report));
}
let map = get_mtd_map(host, password)?;
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
let backups = match &options.backup_dir {
Some(dir) => hold_slots(host, password, &targets, dir)?,
None => Vec::new(),
};
flash_via_ssh(host, password, &targets)?;
if !options.reboot {
return Ok(InPlaceOutcome::Updated(InPlaceReceipt {
backups,
rebooted: false,
}));
}
reboot_target(host, password);
// Wait for the board to actually go down before waiting for it to return,
// so a slow reboot is not mistaken for the old system still answering.
let _ = wait_for(|| !ssh_port_open(host), Duration::from_secs(60));
if wait_alkane(host, Duration::from_secs(300)) {
Ok(InPlaceOutcome::Updated(InPlaceReceipt {
backups,
rebooted: true,
}))
} else {
Err(StockError::Method(
"images were written and read back, but the board did not return as alkane after reboot"
.into(),
))
}
}
/// HTTP GET / and report (status-200, marker present case-insensitively).
fn http_marker(host: &str, marker: &str) -> (String, bool) {
let mut command = Command::new("curl");
command.args(["-sS", "-i", "--max-time", "6", &format!("http://{host}/")]);
match run_command(command, Duration::from_secs(12), None) {
Ok(result) if result.ok() => {
let body = text(&result.stdout);
let status = body.lines().next().unwrap_or("").trim().to_string();
let is_200 = status.contains(" 200");
let has = body.to_lowercase().contains(&marker.to_lowercase());
let title = body
.split("<title>")
.nth(1)
.and_then(|rest| rest.split("</title>").next())
.unwrap_or("")
.trim()
.to_string();
let detail = format!(
"{status}; title \"{title}\"; marker {marker} {}",
if has { "present" } else { "absent" }
);
(detail, is_200 && has)
}
Ok(result) => (
format!("no HTTP answer ({})", text(&result.stderr).trim()),
false,
),
Err(e) => (format!("{e}"), false),
}
}
pub(crate) fn live_check(
host: &str,
password: Option<&str>,
marker: &str,
kernel_version: &str,
timeout: Duration,
) -> Result<crate::stock::LiveCheck, StockError> {
validate_host(host)?;
let resolved = resolve_password(password);
let password = resolved.as_deref();
let deadline = Instant::now() + timeout;
let mut attempts = 0;
loop {
attempts += 1;
let (http, http_ok) = http_marker(host, marker);
let (ssh, ssh_ok, cmdline) = match ssh_exec(
host,
password,
"uname -r; echo '##'; cat /proc/cmdline; echo '##'; \
cat /etc/os-release /etc/issue 2>/dev/null; hostname; [ -d /etc/alkane ] && echo alkane-etc",
Duration::from_secs(20),
) {
Ok(result) if result.ok() => {
let out = text(&result.stdout);
let mut parts = out.split("##\n");
let kernel = parts.next().unwrap_or("").trim().to_string();
let cmdline = parts.next().unwrap_or("").trim().to_string();
let os = parts.next().unwrap_or("").to_lowercase();
let is_alkane = os.contains("alkane");
let kernel_ok =
!kernel.is_empty() && (kernel_version.is_empty() || kernel.contains(kernel_version));
(
format!(
"kernel {kernel}; os {}{}",
if is_alkane { "alkane" } else { "not alkane" },
if kernel_ok { "" } else { " (expected the installed kernel)" }
),
is_alkane && kernel_ok,
cmdline,
)
}
Ok(result) => (format!("{}", classify_ssh(&result)), false, String::new()),
Err(e) => (format!("{e}"), false, String::new()),
};
let done = (http_ok && ssh_ok) || Instant::now() >= deadline;
if done {
return Ok(crate::stock::LiveCheck {
attempts,
http,
http_ok,
ssh,
ssh_ok,
cmdline,
});
}
thread::sleep(Duration::from_secs(5));
}
}
fn board_state(host: &str, password: Option<&str>) -> Result<String, StockError> {
let result = ssh_exec(
host,
@@ -1837,6 +2264,11 @@ impl StockMethod for Method {
return Ok(());
}
// The kernel device tree is not in Bitmain's distributable firmware, so
// use the correct per-board dtb (fetched + verified) rather than anything
// from the caller's package. The genuine kernel and rootfs come from the
// package the caller parsed.
let dtb = stock_asset(&ASSET_DTB)?;
// The brick-sensitive boot regions are not exposed to Linux on alkane;
// get_mtd_map re-registers them so the stock images can be written back.
let map = get_mtd_map(host, password)?;
@@ -1848,13 +2280,7 @@ impl StockMethod for Method {
ROOTFS_SLOT,
Cow::Owned(images.rootfs.to_vec()),
),
(
"dtb",
"stock-dtb.bin",
ABS_DTB,
DTB_SLOT,
Cow::Owned(images.dtb.to_vec()),
),
("dtb", "stock-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)),
(
"kernel",
"stock-kernel.uimg",
@@ -1875,6 +2301,16 @@ impl StockMethod for Method {
let _ = wait_stock(host, Duration::from_secs(90));
Ok(())
}
fn update_in_place(
&self,
host: &str,
afw: &VerifiedAfw,
password: Option<&str>,
options: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError> {
update_in_place_impl(host, afw, password, options)
}
}
static METHOD: Method = Method;
@@ -1914,14 +2350,19 @@ mod tests {
"d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
);
assert_eq!(
sha256_hex(
b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
),
sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
);
}
#[test]
// The fetch path shells out to curl (as the whole method relies on local
// ssh/sshpass/curl). The Windows CI runs the test binary under Wine, where
// curl is not on PATH, so the test cannot run there.
#[cfg_attr(
windows,
ignore = "needs curl on PATH; the Windows CI runs tests under Wine without it"
)]
fn fetch_pipeline_caches_verifies_and_redownloads() {
let work = TempDir::new("fetchtest").expect("temp dir");
let source = work.path().join("source");
@@ -1950,7 +2391,11 @@ mod tests {
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
fs::metadata(&cached).expect("metadata").permissions().mode() & 0o777,
fs::metadata(&cached)
.expect("metadata")
.permissions()
.mode()
& 0o777,
0o600
);
}
@@ -1993,6 +2438,115 @@ mod tests {
assert_eq!(data_crc, crc32(b"payload"));
}
fn mtd(device: &str, offset: u64, size: u64) -> Mtd {
Mtd {
device: device.to_string(),
offset,
size,
}
}
/// The storage map the current alkane image registers: only the two small
/// config partitions, at absolute offsets. The boot regions are absent.
fn alkane_protected_map() -> Vec<Mtd> {
vec![
mtd("/dev/mtd0", 0x4800000, 0x800000), // stock-cfg (read-only)
mtd("/dev/mtd1", 0x5000000, 0x100000), // alkane-cfg
]
}
fn images() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
(
vec![0xAA; 0x300000],
vec![0xBB; 0x3000],
vec![0xCC; 0x400000],
)
}
#[test]
fn protected_alkane_map_yields_no_write_targets() {
// On the current alkane layout the boot regions are not registered, so
// nothing may be planned at all - in particular nothing on stock-cfg or
// alkane-cfg (the old tier-2 path erased alkane-cfg here).
let map = alkane_protected_map();
assert!(!map_covers_boot_regions(&map));
let (k, d, r) = images();
assert!(alkane_targets(&map, k, d, r).is_err());
}
#[test]
fn registered_boot_regions_place_targets_on_the_stock_uboot_slots() {
// Whole NAND registered as one device (as after re-registration).
let map = vec![mtd("/dev/mtd2", 0x0, 0x8000000)];
assert!(map_covers_boot_regions(&map));
let (k, d, r) = images();
let targets = alkane_targets(&map, k, d, r).unwrap();
let names: Vec<_> = targets.iter().map(|t| t.name).collect();
assert_eq!(names, ["rootfs", "dtb", "kernel"]);
let at = |n: &str| targets.iter().find(|t| t.name == n).unwrap();
assert_eq!(
(at("rootfs").rel, at("rootfs").absolute),
(0x2800000, 0x2800000)
);
assert_eq!((at("dtb").rel, at("dtb").absolute), (0x1A00000, 0x1A00000));
assert_eq!(
(at("kernel").rel, at("kernel").absolute),
(0x2000000, 0x2000000)
);
for t in &targets {
assert!(t.absolute >= BOOTBIN_PRESERVE);
}
}
#[test]
fn split_boot_partitions_resolve_relative_offsets() {
// Boot regions registered as separate partitions: offsets become
// partition-relative, absolute stays the NAND address.
let map = vec![
mtd("/dev/mtd2", 0x1A00000, 0x600000),
mtd("/dev/mtd3", 0x2000000, 0x800000),
mtd("/dev/mtd4", 0x2800000, 0x2000000),
];
let (k, d, r) = images();
let targets = alkane_targets(&map, k, d, r).unwrap();
let at = |n: &str| targets.iter().find(|t| t.name == n).unwrap();
assert_eq!((at("dtb").device.as_str(), at("dtb").rel), ("/dev/mtd2", 0));
assert_eq!(
(at("kernel").device.as_str(), at("kernel").rel),
("/dev/mtd3", 0)
);
assert_eq!(
(at("rootfs").device.as_str(), at("rootfs").rel),
("/dev/mtd4", 0)
);
}
#[test]
fn a_slot_that_overruns_its_partition_is_refused() {
// Rootfs slot (0x2000000) does not fit a 1 MiB partition at its offset.
let map = vec![
mtd("/dev/mtd2", 0x1A00000, 0x600000),
mtd("/dev/mtd3", 0x2000000, 0x800000),
mtd("/dev/mtd4", 0x2800000, 0x100000),
];
let (k, d, r) = images();
assert!(alkane_targets(&map, k, d, r).is_err());
}
#[test]
fn nothing_is_ever_placed_inside_bootbin() {
let target = make_target(
"x",
"x.bin",
"/dev/mtd2".to_string(),
0x100000,
0x100000,
0x20000,
Cow::Owned(vec![0u8; 16]),
);
assert!(target.is_err());
}
#[test]
fn gzip_and_tar_are_well_formed() {
let entries = vec![
+305
View File
@@ -0,0 +1,305 @@
//! Boards running Alkane OS on the network, and which alkane-os actions apply to
//! a scanned row.
//!
//! asic-rs recognises miners by their cgminer socket (:4028) or a vendor web UI.
//! A board running Alkane OS keeps its cgminer-compatible socket on loopback and
//! serves its own console, so asic-rs reports nothing at that address and the
//! board never appeared in the fleet. This probe finds it over plain HTTP:
//! - `GET /api/identity` (alkane-os 0.1.2 and later): os, os_version, board,
//! sdk_revision, hostname, mac, kernel;
//! - otherwise the cgminer-style `GET /api/summary`, whose STATUS Description
//! is "alkane-os" (earlier images: found, but the board family is unknown).
//!
//! Both endpoints are public and read-only on the board.
use crate::model::MinerRow;
use serde_json::{json, Value};
use std::net::IpAddr;
use std::time::Duration;
/// Firmware family shown for a board running Alkane OS.
pub const FIRMWARE: &str = "Alkane";
const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
const READ_TIMEOUT: Duration = Duration::from_secs(4);
const MAX_RESPONSE: usize = 64 * 1024;
/// Probe `ip` for Alkane OS. Returns a row for the fleet table, or None when the
/// address is not an Alkane board (or does not answer on :80).
pub async fn detect(ip: IpAddr) -> Option<MinerRow> {
if let Some(doc) = get_json(ip, "/api/identity").await {
if doc.get("os").and_then(Value::as_str) == Some("alkane-os") {
return Some(row_from_identity(ip, &doc));
}
}
let summary = get_json(ip, "/api/summary").await?;
if is_alkane_summary(&summary) {
return Some(row_from_identity(ip, &json!({})));
}
None
}
/// The cgminer-style summary an Alkane board serves names "alkane-os" in its
/// STATUS Description.
fn is_alkane_summary(doc: &Value) -> bool {
doc.get("STATUS")
.and_then(Value::as_array)
.and_then(|status| status.first())
.and_then(|entry| entry.get("Description"))
.and_then(Value::as_str)
== Some("alkane-os")
}
/// Control-board labels (cpu, code) for an Alkane board family, matching the
/// labels the scan gives the same board on stock firmware.
fn board_labels(board: &str) -> (&'static str, &'static str) {
match board {
"zynq-7010" => ("XIL", "C49"),
"am335x" => ("BBB", "C77"),
"cv1835" => ("CVI", "C88"),
"a113d" => ("AML", "C76"),
_ => ("", ""),
}
}
fn row_from_identity(ip: IpAddr, doc: &Value) -> MinerRow {
let text = |key: &str| {
doc.get(key)
.and_then(Value::as_str)
.unwrap_or("")
.trim()
.to_string()
};
let board = text("board");
let (cpu, code) = board_labels(&board);
let control_board = if cpu.is_empty() {
board.clone()
} else {
format!("{cpu} ({code})")
};
MinerRow {
ip: ip.to_string(),
// The Alkane-supported control boards are all Bitmain (Antminer) boards.
brand: if cpu.is_empty() {
String::new()
} else {
"Antminer".to_string()
},
firmware: FIRMWARE.to_string(),
fw_version: text("os_version"),
api_version: "alkane-os".to_string(),
mac: text("mac"),
hostname: text("hostname"),
control_board,
cpu: cpu.to_string(),
board_code: code.to_string(),
alkane_board: Some(board),
..Default::default()
}
}
/// HTTP/1.0 GET on :80 returning the JSON body of a 200 reply.
async fn get_json(ip: IpAddr, path: &str) -> Option<Value> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let connect = tokio::net::TcpStream::connect((ip, 80));
let mut stream = tokio::time::timeout(CONNECT_TIMEOUT, connect)
.await
.ok()?
.ok()?;
let request = format!("GET {path} HTTP/1.0\r\nHost: {ip}\r\nConnection: close\r\n\r\n");
stream.write_all(request.as_bytes()).await.ok()?;
let mut raw = Vec::new();
let _ = tokio::time::timeout(READ_TIMEOUT, async {
let mut chunk = [0u8; 4096];
loop {
match stream.read(&mut chunk).await {
Ok(0) | Err(_) => break,
Ok(n) => {
raw.extend_from_slice(&chunk[..n]);
if raw.len() > MAX_RESPONSE {
break;
}
}
}
}
})
.await;
parse_http_json(&raw)
}
fn parse_http_json(raw: &[u8]) -> Option<Value> {
let text = std::str::from_utf8(raw).ok()?;
let (head, body) = text.split_once("\r\n\r\n")?;
let status = head.lines().next()?;
if status.split_whitespace().nth(1) != Some("200") {
return None;
}
serde_json::from_str(body.trim()).ok()
}
/// Whether the row is a board running Alkane OS (found by `detect`).
pub fn is_alkane(row: &MinerRow) -> bool {
row.alkane_board.is_some()
}
/// The alkane-os board family the row's control board is, when it can be told:
/// what an Alkane board reports, or for a stock Antminer the Zynq-7010 (S17/T17
/// era, "XIL (C49)") control board.
pub fn board_family(row: &MinerRow) -> Option<String> {
if let Some(board) = &row.alkane_board {
return (!board.is_empty()).then(|| board.clone());
}
if !row.brand.to_ascii_lowercase().contains("antminer") {
return None;
}
if row.cpu == "XIL" && row.board_code == "C49" {
return Some("zynq-7010".to_string());
}
// A stock S17 whose miner software is down (no hashboards attached: it
// restart-loops) reports its model but no control board. Its model then
// decides; a control board that IS reported always wins above.
if row.cpu.is_empty() && is_zynq_7010_model(&row.model) {
return Some("zynq-7010".to_string());
}
None
}
/// Stock models built only on the Zynq-7010 (XIL C49) control board.
fn is_zynq_7010_model(model: &str) -> bool {
matches!(model.trim(), "S17" | "S17 Pro" | "T17")
}
/// Whether alkane-os can be installed on the row's board: its control board is
/// one the toolkit supports.
pub fn install_supported(row: &MinerRow) -> bool {
board_family(row).is_some_and(|board| crate::stock_ops::is_supported_board(&board))
}
#[cfg(test)]
mod tests {
use super::*;
fn ip() -> IpAddr {
"10.0.0.5".parse().unwrap()
}
#[test]
fn parses_a_200_json_reply_only() {
let ok = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"os\":\"alkane-os\"}";
assert_eq!(parse_http_json(ok).unwrap()["os"], "alkane-os");
let denied = b"HTTP/1.1 401 Unauthorized\r\n\r\n{\"os\":\"alkane-os\"}";
assert!(parse_http_json(denied).is_none());
let html = b"HTTP/1.1 200 OK\r\n\r\n<!DOCTYPE html><title>x</title>";
assert!(parse_http_json(html).is_none());
assert!(parse_http_json(b"garbage").is_none());
}
#[test]
fn recognises_the_alkane_summary() {
let alkane = json!({"STATUS":[{"Code":0,"Description":"alkane-os","STATUS":"S"}]});
assert!(is_alkane_summary(&alkane));
let cgminer = json!({"STATUS":[{"Description":"cgminer 4.11.1","STATUS":"S"}]});
assert!(!is_alkane_summary(&cgminer));
assert!(!is_alkane_summary(&json!({})));
}
#[test]
fn identity_becomes_a_supported_alkane_row() {
let doc = json!({
"os": "alkane-os", "os_version": "0.1.2", "board": "zynq-7010",
"sdk_revision": "6a9080ac82c1", "hostname": "alkane-zynq",
"mac": "26:4e:52:8b:e2:48", "kernel": "6.18.48",
});
let row = row_from_identity(ip(), &doc);
assert_eq!(row.ip, "10.0.0.5");
assert_eq!(row.firmware, "Alkane");
assert_eq!(row.fw_version, "0.1.2");
assert_eq!(row.control_board, "XIL (C49)");
assert_eq!(row.mac, "26:4e:52:8b:e2:48");
assert!(is_alkane(&row));
assert!(install_supported(&row));
}
#[test]
fn an_old_alkane_board_is_alkane_but_its_family_is_unknown() {
// Found via /api/summary only: uninstall applies, install cannot be
// confirmed as supported.
let row = row_from_identity(ip(), &json!({}));
assert!(is_alkane(&row));
assert_eq!(board_family(&row), None);
assert!(!install_supported(&row));
}
#[test]
fn stock_antminers_are_supported_only_on_the_zynq_7010_board() {
let stock = |cpu: &str, code: &str| MinerRow {
brand: "Antminer".into(),
firmware: "Stock".into(),
cpu: cpu.into(),
board_code: code.into(),
..Default::default()
};
let s17 = stock("XIL", "C49");
assert!(install_supported(&s17));
assert!(!is_alkane(&s17));
assert!(!install_supported(&stock("XIL", "C55"))); // S19-era Zynq
assert!(!install_supported(&stock("AML", "C76")));
assert!(!install_supported(&stock("", "")));
let whatsminer = MinerRow {
brand: "WhatsMiner".into(),
cpu: "XIL".into(),
board_code: "C49".into(),
..Default::default()
};
assert!(!install_supported(&whatsminer));
}
#[test]
fn a_stock_s17_without_a_reported_control_board_is_supported_by_model() {
// As seen live: stock S17, miner software down, control board blank.
let s17 = MinerRow {
brand: "Antminer".into(),
model: "S17".into(),
firmware: "Stock".into(),
..Default::default()
};
assert!(install_supported(&s17));
let other = |model: &str| MinerRow {
brand: "Antminer".into(),
model: model.into(),
..Default::default()
};
assert!(install_supported(&other("S17 Pro")));
assert!(install_supported(&other("T17")));
assert!(!install_supported(&other("S19")));
assert!(!install_supported(&other("S17+")));
assert!(!install_supported(&other("")));
// A reported control board overrides the model.
let s17_on_aml = MinerRow {
brand: "Antminer".into(),
model: "S17".into(),
cpu: "AML".into(),
board_code: "C76".into(),
..Default::default()
};
assert!(!install_supported(&s17_on_aml));
}
/// Live check against a real board:
/// `ALKANE_TEST_IP=10.255.1.111 cargo test -p alkane-gui live_detect -- --ignored --nocapture`
#[test]
#[ignore = "needs a board on the network (ALKANE_TEST_IP)"]
fn live_detect() {
let Ok(ip) = std::env::var("ALKANE_TEST_IP") else {
return;
};
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let row = rt.block_on(detect(ip.parse().unwrap()));
println!("{row:#?}");
let row = row.expect("an Alkane board at ALKANE_TEST_IP");
assert!(is_alkane(&row));
}
}
+1
View File
@@ -6,6 +6,7 @@
#![cfg_attr(windows, windows_subsystem = "windows")]
mod access_probe;
mod alkane_detect;
mod askpass;
mod bug_report;
mod credentials;
+4
View File
@@ -527,6 +527,10 @@ pub struct MinerRow {
/// from whether any control capability is available: `None` = unknown,
/// `Some(true)` = locked, `Some(false)` = unlocked/writable.
pub write_locked: Option<bool>,
/// Set when the row is a board running Alkane OS (found by the toolkit's own
/// probe, `alkane_detect`, not asic-rs): the board family it reports
/// ("zynq-7010"), or an empty string for an older image that does not say.
pub alkane_board: Option<String>,
/// Structured error/event lines from the miner (severity + text), most
/// severe first. Empty means none. The Error column shows a summary; the
/// full list is the hover tooltip (added with the tooltip bridge support).
+62 -7
View File
@@ -531,7 +531,10 @@ pub fn start_scan(lines: Vec<String>, timeout_secs: u64) -> ScanHandle {
.ok();
(ip, row)
}
None => (ip, None),
// asic-rs does not recognise a board running Alkane
// OS (no cgminer socket or vendor web UI exposed);
// the toolkit's own probe finds it.
None => (ip, crate::alkane_detect::detect(ip).await),
}
}
})
@@ -1229,6 +1232,8 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
.unwrap_or_default(),
pic_present,
write_locked,
// asic-rs identified this miner, so it is not running Alkane OS.
alkane_board: None,
errors,
faults,
model,
@@ -1917,13 +1922,25 @@ pub fn start_refresh(ips: Vec<String>) -> RefreshHandle {
ok += 1;
RefreshMsg::Row(to_row(&*miner).await)
}
Ok(None) => RefreshMsg::Failed {
ip: ip_s,
detail: "offline".to_string(),
Ok(None) => match crate::alkane_detect::detect(ip).await {
Some(row) => {
ok += 1;
RefreshMsg::Row(row)
}
None => RefreshMsg::Failed {
ip: ip_s,
detail: "offline".to_string(),
},
},
Err(e) => RefreshMsg::Failed {
ip: ip_s,
detail: format!("{e}"),
Err(e) => match crate::alkane_detect::detect(ip).await {
Some(row) => {
ok += 1;
RefreshMsg::Row(row)
}
None => RefreshMsg::Failed {
ip: ip_s,
detail: format!("{e}"),
},
},
},
};
@@ -2615,3 +2632,41 @@ mod tests {
std::env::remove_var(FAKE_SCAN_ENV);
}
}
#[cfg(test)]
mod live_scan_tests {
/// Run the real fleet scan over a range and print, per row found, what the
/// alkane-os menu would offer:
/// `ALKANE_TEST_SCAN_RANGE=10.255.1.0/24 cargo test -p alkane-gui live_scan -- --ignored --nocapture`
#[test]
#[ignore = "needs a reachable miner network (ALKANE_TEST_SCAN_RANGE)"]
fn live_scan() {
let Ok(range) = std::env::var("ALKANE_TEST_SCAN_RANGE") else {
return;
};
let handle = super::start_scan(vec![range], 10);
let mut rows = std::collections::BTreeMap::new();
while let Ok(msg) = handle.rx.recv() {
match msg {
super::ScanMsg::Row(row) => {
rows.insert(row.ip.clone(), row);
}
super::ScanMsg::Done(_) | super::ScanMsg::Failed(_) => break,
_ => {}
}
}
for row in rows.values() {
println!(
"{:<15} brand={:<10} model={:<12} fw={:<8} {:<8} board={:<10} install={} uninstall={}",
row.ip,
row.brand,
row.model,
row.firmware,
row.fw_version,
row.control_board,
crate::alkane_detect::install_supported(row),
crate::alkane_detect::is_alkane(row),
);
}
}
}
+19 -23
View File
@@ -48,7 +48,11 @@ pub enum StockMsg {
/// A human-readable status line for the status bar (acquiring, verifying...).
Progress(String),
/// One board's outcome.
Result { ip: String, ok: bool, detail: String },
Result {
ip: String,
ok: bool,
detail: String,
},
Done,
}
@@ -86,7 +90,9 @@ pub fn start_install(
if fake_scan_enabled() {
let _ = tx.send(StockMsg::Started);
let _ = tx.send(StockMsg::Progress("install (demo): no hardware touched".into()));
let _ = tx.send(StockMsg::Progress(
"install (demo): no hardware touched".into(),
));
for ip in ips {
let _ = tx.send(StockMsg::Result {
ip,
@@ -174,18 +180,15 @@ pub fn start_install(
"installing {} onto {ip} (from stock)...",
verified.manifest.board
)));
let (ok, detail) = match stock::install_from_stock(
&ip,
&afw_path,
&verified,
password.as_deref(),
) {
Ok(()) => (
true,
"installed alkane-os (verify liveness over the network)".to_string(),
),
Err(e) => (false, format!("install failed: {e}")),
};
let (ok, detail) =
match stock::install_from_stock(&ip, &afw_path, &verified, password.as_deref())
{
Ok(()) => (
true,
"installed alkane-os (verify liveness over the network)".to_string(),
),
Err(e) => (false, format!("install failed: {e}")),
};
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
return;
}
@@ -212,16 +215,9 @@ fn restore_one(ip: &str, firmware: &Path, password: Option<&str>) -> (bool, Stri
Ok(f) => f,
Err(e) => return (false, format!("firmware: {e}")),
};
let Some(dtb) = fw.dtb.as_deref() else {
return (
false,
"this package has no device tree; use the Bitmain SD recovery image \
(SD_Antminer-S17-*.zip), which includes devicetree.dtb"
.to_string(),
);
};
// The device tree comes from the toolkit's per-board asset, not the package,
// so any genuine Bitmain firmware (OTA or SD) provides a usable kernel+rootfs.
let images = RestoreImages {
dtb,
kernel: &fw.kernel,
rootfs: &fw.rootfs,
};
+88 -26
View File
@@ -1,6 +1,7 @@
//! Primary view per docs/UI-SPEC.md: KPI header, scan-ranges editor,
//! Excel-style filter panel, columns panel, sortable/drag-reorderable table.
use crate::alkane_detect;
use crate::credentials;
use crate::model::*;
use crate::restore;
@@ -103,6 +104,7 @@ const ID_POOLS_CANCEL: i32 = 789;
// toolkit's own compiled-in network-only engine. Typed-FLASH confirmation.
const ID_CTX_INSTALL_ALKANE: i32 = 770;
const ID_CTX_UNINSTALL_ALKANE: i32 = 771;
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;
@@ -1885,17 +1887,37 @@ impl App {
// the vendor installers cover the current workflow. (ID_CTX_FLASH and the
// flash dialog remain in the code, just not surfaced here.)
let _ = ID_CTX_FLASH;
// Alkane OS install/uninstall via the toolkit's own self-contained,
// network-only engine (stock <-> alkane). Offered for any selection: the
// engine gates on board compatibility and a typed FLASH confirmation, so
// this is safe to surface without relying on asic-rs firmware detection
// (a board on genuine stock often does not identify cleanly).
menu.menu_append_separator();
menu.menu_append(ID_CTX_INSTALL_ALKANE, "Install alkane OS (from stock)...");
menu.menu_append(
ID_CTX_UNINSTALL_ALKANE,
"Uninstall alkane OS (restore to stock)...",
);
// Alkane OS install / update / uninstall via the toolkit's own
// self-contained, network-only engine. Each is offered only when it
// applies to every selected board:
// - Install: a supported board (alkane-os has an image for its control
// board) that is not running Alkane OS yet;
// - Update: a supported board already running Alkane OS (updated in
// 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.
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));
let install = supported && none_alkane;
let update = supported && all_alkane;
let uninstall = all_alkane;
if install || update || uninstall {
menu.menu_append_separator();
}
if install {
menu.menu_append(ID_CTX_INSTALL_ALKANE, "Install alkane OS...");
}
if update {
menu.menu_append(ID_CTX_UPDATE_ALKANE, "Update alkane OS...");
}
if uninstall {
menu.menu_append(
ID_CTX_UNINSTALL_ALKANE,
"Uninstall alkane OS (restore to stock)...",
);
}
self.pending_popup = Some((t, menu));
}
@@ -2164,7 +2186,9 @@ impl App {
// exclusivity guard: don't write pools during a restore or a live scan
// (round 18 #12).
if self.restore.is_some() || self.stock_op.is_some() {
wx_rs::set_status_text("a stock install/restore is in progress -- wait for it to finish");
wx_rs::set_status_text(
"a stock install/restore is in progress -- wait for it to finish",
);
return;
}
if self.scanning {
@@ -2261,7 +2285,9 @@ impl App {
// A restore-to-stock is reverting + rebooting miners; a config action mid-
// revert could hit a unit in an undefined state (round 18 #12).
if self.restore.is_some() || self.stock_op.is_some() {
wx_rs::set_status_text("a stock install/restore is in progress -- wait for it to finish");
wx_rs::set_status_text(
"a stock install/restore is in progress -- wait for it to finish",
);
return;
}
// A scan is opening its own connections to these same miners; a mutating
@@ -2592,11 +2618,12 @@ impl App {
|| self.stock_op.is_some()
}
/// Build the "Install alkane OS (from stock)" dialog: a scanned list of
/// 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.
fn build_install_dialog(&mut self) -> Option<Widget> {
fn build_install_dialog(&mut self, update: bool) -> Option<Widget> {
if self.hardware_busy() {
wx_rs::set_status_text("busy -- try again once the current operation finishes");
return None;
@@ -2626,16 +2653,28 @@ impl App {
self.install_ips = ips.clone();
let frame = Widget::main_frame();
let dlg = Widget::dialog(frame, "Install alkane OS (from stock)");
let title = if update {
"Update alkane OS"
} else {
"Install alkane OS"
};
let dlg = Widget::dialog(frame, title);
let root = Widget::box_sizer(true);
let n = ips.len();
root.add(
Widget::static_text(
dlg,
&format!(
"Install alkane OS onto {n} board(s) currently on stock:\n{}",
ips.join(", ")
),
&if update {
format!(
"Update alkane OS on {n} board(s) already running it (updated in place; BOOT.bin is never written):\n{}",
ips.join(", ")
)
} else {
format!(
"Install alkane OS onto {n} board(s) currently on stock:\n{}",
ips.join(", ")
)
},
),
0,
sf::BORDER_ALL,
@@ -2648,7 +2687,14 @@ impl App {
12,
);
root.add(
Widget::static_text(dlg, "Release to install (newest first):"),
Widget::static_text(
dlg,
if update {
"Release to update to (newest first):"
} else {
"Release to install (newest first):"
},
),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
12,
@@ -2670,7 +2716,12 @@ impl App {
}
choice.choice_set_selection(0);
}
root.add(choice, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12);
root.add(
choice,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
self.install_release_choice = choice;
root.add(
@@ -2699,7 +2750,12 @@ impl App {
12,
);
let confirm = Widget::text_ctrl(dlg, false);
root.add(confirm, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12);
root.add(
confirm,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
self.install_confirm_input = confirm;
let btns = Widget::box_sizer(false);
@@ -2821,7 +2877,7 @@ impl App {
root.add(
Widget::static_text(
dlg,
"Genuine Bitmain stock firmware file (SD recovery image\nSD_Antminer-S17-*.zip, which includes the device tree):",
"Genuine Bitmain stock firmware file for this board\n(an OTA update .tar.gz or an SD recovery .zip):",
),
0,
sf::BORDER_LEFT | sf::BORDER_RIGHT | sf::BORDER_TOP,
@@ -2851,7 +2907,12 @@ impl App {
12,
);
let confirm = Widget::text_ctrl(dlg, false);
root.add(confirm, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 12);
root.add(
confirm,
0,
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
12,
);
self.uninstall_confirm_input = confirm;
let btns = Widget::box_sizer(false);
btns.add_stretch(1);
@@ -3108,7 +3169,8 @@ impl App {
ID_CTX_ACCESS_PROBE => self.start_access_probe(),
ID_CTX_VIEW_LOG => self.start_log_fetch(),
ID_CTX_RESTORE_STOCK => return self.build_restore_confirm_dialog(),
ID_CTX_INSTALL_ALKANE => return self.build_install_dialog(),
ID_CTX_INSTALL_ALKANE => return self.build_install_dialog(false),
ID_CTX_UPDATE_ALKANE => return self.build_install_dialog(true),
ID_CTX_UNINSTALL_ALKANE => return self.build_uninstall_dialog(),
ID_CTX_POOLS => return self.build_pools_dialog(),
ID_CTX_FLASH => {
+69 -20
View File
@@ -68,44 +68,93 @@ verify the board came up as alkane:
alkane-cli afw verify-live --host <miner-ip> --timeout 300
```
On Zynq (S17/S19 class) pass the `.afw` (or `--board zynq-7010`) and the board's
alkane root credential; the check needs the web page to carry the image marker
and SSH to report alkane with the installed kernel, and prints the running kernel
command line (on a NAND boot it is the board's U-Boot env bootargs):
```
alkane-cli afw verify-live path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
--host <miner-ip> --password-file <alkane-root-pw> --timeout 300
```
For a bench image that is not signed, add `--allow-unsigned`.
Without `--from-stock`, `install` performs a tier-2 update of a board already on
alkane: it writes the dtb (`/dev/mtd0 @ 0x1a00000`), the kernel
(`/dev/mtd0 @ 0x2000000`) and the rootfs (`/dev/mtd1`), holds a backup of each,
reads them back (md5), and never writes `/dev/mtd0` below `0x1a00000`
(BOOT.bin/FSBL/FPGA/U-Boot are preserved).
alkane, in place, over the network:
```
alkane-cli afw install path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
--host <miner-ip> --password-file <alkane-root-pw> --dry-run
alkane-cli afw install path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
--host <miner-ip> --password-file <alkane-root-pw> --confirm FLASH
```
On Zynq (S17/S19 class) the update refuses a board that is not running alkane.
Alkane does not expose the NAND boot regions to Linux (only the small
`stock-cfg` and `alkane-cfg` partitions), so the toolkit re-registers them
first, the same way a restore does. It saves each boot slot to `--backup-dir`
(default: the toolkit's `backups` directory) before any erase, then writes the
rootfs (absolute NAND `0x2800000`), dtb (`0x1a00000`) and kernel (`0x2000000`),
with the kernel and rootfs wrapped as the legacy uImages the board's stock
U-Boot boots, and reads each back (md5) before rebooting. Nothing below
`0x1a00000` (BOOT.bin: FSBL, FPGA bitstream, U-Boot) is ever written.
`afw preflight` runs the same checks read-only. `--no-reboot` skips the reboot.
## Remove (back to stock)
```
export ALKANE_RELEASE_TOKEN=<your-gitea-token>
alkane-cli afw restore-stock --host <miner-ip> \
--stock-firmware <genuine-Bitmain-firmware> \
--password-file <alkane-root-pw> --confirm FLASH
```
Returning an aftermarket board to genuine stock is also done by the toolkit
itself, over the network. It uses the same per-board assets (fetched/cached as
above from the now-public assets repo, so no token is needed) and the board's
alkane root credential (`--password-file`, or
`ALKANE_BOARD_PASSWORD`/`ALKANE_BOARD_PASSWORD_FILE`). You then verify
Returning an aftermarket board to genuine stock is done by the toolkit itself,
over the network. It writes the genuine Bitmain stock **kernel and rootfs** -
parsed from a vendor firmware file you supply with `--stock-firmware` (an OTA
update `.tar.gz` or an SD recovery `.zip` for the board) - back to NAND,
preserving BOOT.bin.
The one piece that is NOT in Bitmain's distributable firmware is the kernel
**device tree**: it is factory-provisioned and preserved by every vendor update,
so no OTA/SD package ships it. The toolkit supplies the correct per-board dtb
itself (fetched + verified from the public assets repo, so no token is needed)
and pairs it with the genuine kernel/rootfs. The board's alkane root credential
is given with `--password-file` (or
`ALKANE_BOARD_PASSWORD`/`ALKANE_BOARD_PASSWORD_FILE`).
After a restore the board returns to stock under its stock MAC and typically
takes a new DHCP lease, so it may not reappear on the same address; verify
independently that the board no longer answers as alkane and presents its stock
OS.
## GUI (right-click install / uninstall)
The GUI binary is `alkane-toolkit`. Launch it, let the scan list the fleet, then
right-click one or more boards and choose:
right-click one or more boards. The scan finds boards running Alkane OS too
(Firmware column "Alkane"): they expose no cgminer socket or vendor web UI, so the
toolkit identifies them itself from the board's public read-only
`GET /api/identity` (alkane-os 0.1.2 and later; earlier images are found from
`/api/summary`). Each action below is offered only when it applies to every
selected board:
- "Install alkane OS (from stock)..." - 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 from-stock engine the
CLI uses.
- "Uninstall alkane OS (restore to stock)..." - takes the board's alkane root
password and a typed FLASH confirmation, then restores each selected board to
genuine stock over the network.
- "Install alkane OS..." - for a supported board (one alkane-os has an image
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.
- "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
over the network.
A stock board the scan identifies but cannot place on a supported control board
(or a mixed stock/Alkane selection) gets neither Install nor Update.
Progress and per-board results appear on the status bar; verify board state
independently afterwards (the GUI does not claim liveness on its own).