diff --git a/crates/alkane-artifacts/src/afw.rs b/crates/alkane-artifacts/src/afw.rs index d6ab8ec2..1dda0c5d 100644 --- a/crates/alkane-artifacts/src/afw.rs +++ b/crates/alkane-artifacts/src/afw.rs @@ -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(), diff --git a/crates/alkane-artifacts/src/fetch.rs b/crates/alkane-artifacts/src/fetch.rs index f6415d92..aaf43149 100644 --- a/crates/alkane-artifacts/src/fetch.rs +++ b/crates/alkane-artifacts/src/fetch.rs @@ -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, 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 { +pub fn fetch_latest_afw( + src: &ReleaseSource, + board: &str, + dest_dir: &Path, +) -> Result { 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 { 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 -- 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()); diff --git a/crates/alkane-cli/src/main.rs b/crates/alkane-cli/src/main.rs index 14e99d82..14d37dd7 100644 --- a/crates/alkane-cli/src/main.rs +++ b/crates/alkane-cli/src/main.rs @@ -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, ZynqPlan}; -use alkane_flash::stock::{InPlaceOptions, InPlaceOutcome, RestoreImages}; -use alkane_flash::stock_firmware; -use alkane_flash::boards::a113d::{self, A113dInstallOptions, A113dOutcome, A113dPlan}; 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, Box { - 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> { 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}"); @@ -513,7 +512,9 @@ fn install_zynq_in_place( 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)."); + println!( + "Re-run with --confirm FLASH to write rootfs, dtb and kernel (BOOT.bin preserved)." + ); } InPlaceOutcome::Updated(receipt) => { for held in &receipt.backups { @@ -588,7 +589,13 @@ fn run_install(args: &[String]) -> Result<(), Box> { args, &[ ssh_values(), - &["held-backup", "backup-dir", "confirm", "expect-board", "board"], + &[ + "held-backup", + "backup-dir", + "confirm", + "expect-board", + "board", + ], ] .concat(), &[ @@ -685,25 +692,39 @@ fn run_install(args: &[String]) -> Result<(), Box> { 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::>().join(", "); + let targets = plan + .targets + .iter() + .map(|t| t.image_name.as_str()) + .collect::>() + .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 { @@ -763,7 +784,13 @@ fn run_verify_live(args: &[String]) -> Result<(), Box> { args, &[ ssh_values(), - &["marker", "kernel-version", "timeout", "expect-board", "board"], + &[ + "marker", + "kernel-version", + "timeout", + "expect-board", + "board", + ], ] .concat(), &["allow-unsigned"], @@ -801,7 +828,9 @@ fn run_verify_live(args: &[String]) -> Result<(), Box> { ) } } 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) { @@ -839,7 +868,9 @@ fn run_verify_live(args: &[String]) -> Result<(), Box> { )?; print!("{}", report.render()); if !report.ok() { - return Err("live verification failed: HTTP marker and SSH did not both confirm alkane".into()); + return Err( + "live verification failed: HTTP marker and SSH did not both confirm alkane".into(), + ); } return Ok(()); } @@ -879,8 +910,13 @@ fn run_restore(args: &[String]) -> Result<(), Box> { &[ 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(), @@ -1003,7 +1039,8 @@ fn latest_backup(dir: &Path) -> Option { /// Boards this toolkit can install alkane onto, with the miner each is the /// control board for. The install/restore gate is the .afw's board matching one /// of these; `compat` lists them so an operator knows what is supported. -const SUPPORTED: &[(&str, &str)] = &[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")]; +const SUPPORTED: &[(&str, &str)] = + &[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")]; fn is_supported(board: &str) -> bool { SUPPORTED.iter().any(|(b, _)| *b == board) @@ -1014,7 +1051,9 @@ fn run_compat(_args: &[String]) -> Result<(), Box> { for (board, miner) in SUPPORTED { println!(" {board:<12} {miner}"); } - println!("\nInstall a local bundle: alkane-cli afw install --host --confirm FLASH"); + println!( + "\nInstall a local bundle: alkane-cli afw install --host --confirm FLASH" + ); println!("Install the latest build: alkane-cli afw install --latest --board zynq-7010 --host --confirm FLASH"); println!("Remove (back to stock): alkane-cli afw restore-stock --host --confirm FLASH"); Ok(()) @@ -1029,9 +1068,15 @@ fn run_fetch_latest(args: &[String]) -> Result<(), Box> { 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(()) @@ -1043,17 +1088,19 @@ fn resolve_afw_source(opts: &Opts) -> Result 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 |--latest --host --confirm FLASH".into()) + opts.positionals.first().map(PathBuf::from).ok_or_else(|| { + "usage: alkane-cli afw install |--latest --host --confirm FLASH".into() + }) } /// Return an alkane board to genuine Bitmain stock by writing the stock images diff --git a/crates/alkane-flash/src/boards/a113d.rs b/crates/alkane-flash/src/boards/a113d.rs index 4c81a679..96b6c234 100644 --- a/crates/alkane-flash/src/boards/a113d.rs +++ b/crates/alkane-flash/src/boards/a113d.rs @@ -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 { +fn attach_and_mount(remote: &mut dyn Remote, nvdata_mtd: u32) -> Result { // 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) + ); } } diff --git a/crates/alkane-flash/src/boards/am335x.rs b/crates/alkane-flash/src/boards/am335x.rs index 2d772dff..a954ad08 100644 --- a/crates/alkane-flash/src/boards/am335x.rs +++ b/crates/alkane-flash/src/boards/am335x.rs @@ -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 Result { 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::>(); 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::>(); 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, 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 = - PRESERVE_STOCK.iter().map(|s| (*s).to_owned()).collect(); + let tier3_preserve: Vec = 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); diff --git a/crates/alkane-flash/src/boards/zynq.rs b/crates/alkane-flash/src/boards/zynq.rs index 5d8805da..271beb77 100644 --- a/crates/alkane-flash/src/boards/zynq.rs +++ b/crates/alkane-flash/src/boards/zynq.rs @@ -63,13 +63,26 @@ 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 }, + 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 }, + 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}: below BOOT.bin (0x{bootbin:x})")] - WouldClobberBootbin { image: String, offset: u64, bootbin: u64 }, + WouldClobberBootbin { + image: String, + offset: u64, + bootbin: u64, + }, } #[derive(Clone, Debug)] @@ -171,7 +184,9 @@ 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(), @@ -209,7 +224,11 @@ impl ZynqPlan { target.absolute, target.slot, target.size, - if target.uimage_wrapped { " +64 B header" } else { "" }, + if target.uimage_wrapped { + " +64 B header" + } else { + "" + }, target.expected_md5 )); } @@ -236,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"; @@ -250,7 +269,10 @@ mod tests { fn afw(kernel: Vec, dtb: Vec, rootfs: Vec) -> 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}) }; @@ -273,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), @@ -296,7 +327,11 @@ mod tests { assert_eq!(plan.targets[0].image_name, "rootfs"); assert_eq!(plan.targets[2].image_name, "kernel"); for t in &plan.targets { - assert!(t.absolute >= BOOTBIN_PRESERVE, "{} below BOOT.bin", t.image_name); + assert!( + t.absolute >= BOOTBIN_PRESERVE, + "{} below BOOT.bin", + t.image_name + ); } let render = plan.render(); assert!(render.contains("BOOT.bin")); @@ -308,8 +343,14 @@ mod tests { 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_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); } @@ -335,23 +376,35 @@ mod tests { 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_target_is_above_bootbin() { for (image, absolute, _slot, _fmt, _wrapped) in TARGETS { - assert!(absolute >= BOOTBIN_PRESERVE, "{image} target below BOOT.bin"); + assert!( + absolute >= BOOTBIN_PRESERVE, + "{image} target below BOOT.bin" + ); } } } diff --git a/crates/alkane-flash/src/stock.rs b/crates/alkane-flash/src/stock.rs index c1735393..a0074e59 100644 --- a/crates/alkane-flash/src/stock.rs +++ b/crates/alkane-flash/src/stock.rs @@ -109,7 +109,11 @@ impl LiveCheck { self.http, if self.ssh_ok { "PASS" } else { "FAIL" }, self.ssh, - if self.cmdline.is_empty() { "(not read)" } else { &self.cmdline }, + if self.cmdline.is_empty() { + "(not read)" + } else { + &self.cmdline + }, if self.ok() { "PASS" } else { "FAIL" } ) } diff --git a/crates/alkane-flash/src/stock_firmware.rs b/crates/alkane-flash/src/stock_firmware.rs index 7f3ae953..2633ccdf 100644 --- a/crates/alkane-flash/src/stock_firmware.rs +++ b/crates/alkane-flash/src/stock_firmware.rs @@ -145,8 +145,8 @@ fn read(path: &Path) -> Result, StockFirmwareError> { /// Parse a genuine Bitmain stock firmware package (OTA `.tar.gz` or SD `.zip`) /// into its stock images. pub fn parse(path: &Path) -> Result { - 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 { 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 { .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 { 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. diff --git a/crates/alkane-flash/src/stock_method.rs b/crates/alkane-flash/src/stock_method.rs index 4781b7fc..ae3ba05c 100644 --- a/crates/alkane-flash/src/stock_method.rs +++ b/crates/alkane-flash/src/stock_method.rs @@ -81,7 +81,11 @@ fn stock_token() -> Option { env::var("ALKANE_RELEASE_TOKEN") .ok() .filter(|token| !token.is_empty()) - .or_else(|| env::var("GITEA_TOKEN").ok().filter(|token| !token.is_empty())) + .or_else(|| { + env::var("GITEA_TOKEN") + .ok() + .filter(|token| !token.is_empty()) + }) } fn asset_cache_dir() -> Result { @@ -293,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 { @@ -442,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 { @@ -684,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(()); } @@ -801,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(); @@ -853,12 +913,7 @@ fn http_code(result: &CmdResult) -> u16 { text(&result.stdout).trim().parse::().unwrap_or(0) } -fn stock_web_auth( - host: &str, - password: &str, - dir: &Path, - tag: &str, -) -> Result<(), StockError> { +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( @@ -879,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(), + )), } } @@ -902,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 = {}", @@ -911,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(), ], @@ -942,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}"))), ], )?; @@ -962,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, Vec, Vec), StockError> { +fn load_install_images(afw: &VerifiedAfw) -> Result<(Vec, Vec, Vec), StockError> { if afw.manifest.board != BOARD { return Err(StockError::Method("image is not for this target".into())); } @@ -1075,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]; @@ -1126,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; @@ -1261,7 +1382,11 @@ struct TarEntry { fn build_tar(entries: &[TarEntry]) -> Vec { let mut out = Vec::new(); for entry in entries { - let size = if entry.kind == b'0' { entry.data.len() as u64 } else { 0 }; + let 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' { @@ -1341,7 +1466,9 @@ fn read_mtd_map(host: &str, password: Option<&str>) -> Result, 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) } @@ -1420,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 { @@ -1656,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())), }; @@ -1670,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@@") { @@ -1743,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)); } @@ -1761,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(()); @@ -1794,7 +1914,13 @@ fn hold_slots( .unwrap_or(0); let safe_host: String = host .chars() - .map(|c| if c.is_ascii_alphanumeric() || c == '.' { c } else { '_' }) + .map(|c| { + if c.is_ascii_alphanumeric() || c == '.' { + c + } else { + '_' + } + }) .collect(); let mut held = Vec::with_capacity(targets.len()); for target in targets { @@ -1986,7 +2112,10 @@ fn http_marker(host: &str, marker: &str) -> (String, bool) { ); (detail, is_200 && has) } - Ok(result) => (format!("no HTTP answer ({})", text(&result.stderr).trim()), false), + Ok(result) => ( + format!("no HTTP answer ({})", text(&result.stderr).trim()), + false, + ), Err(e) => (format!("{e}"), false), } } @@ -2151,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(dtb), - ), + ("dtb", "stock-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)), ( "kernel", "stock-kernel.uimg", @@ -2227,9 +2350,7 @@ mod tests { "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592" ); assert_eq!( - sha256_hex( - b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" - ), + sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" ); } @@ -2263,7 +2384,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 ); } @@ -2324,7 +2449,11 @@ mod tests { } fn images() -> (Vec, Vec, Vec) { - (vec![0xAA; 0x300000], vec![0xBB; 0x3000], vec![0xCC; 0x400000]) + ( + vec![0xAA; 0x300000], + vec![0xBB; 0x3000], + vec![0xCC; 0x400000], + ) } #[test] @@ -2348,9 +2477,15 @@ mod tests { 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("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)); + assert_eq!( + (at("kernel").rel, at("kernel").absolute), + (0x2000000, 0x2000000) + ); for t in &targets { assert!(t.absolute >= BOOTBIN_PRESERVE); } @@ -2369,8 +2504,14 @@ mod tests { 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)); + 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] diff --git a/crates/alkane-gui/src/stock_ops.rs b/crates/alkane-gui/src/stock_ops.rs index 6caef6a1..69a53d6d 100644 --- a/crates/alkane-gui/src/stock_ops.rs +++ b/crates/alkane-gui/src/stock_ops.rs @@ -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; } diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 0763d33b..3e815e20 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -2080,7 +2080,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 { @@ -2177,7 +2179,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 @@ -2586,7 +2590,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( @@ -2615,7 +2624,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); @@ -2767,7 +2781,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);