// SPDX-License-Identifier: MIT //! Parse a genuine Bitmain Antminer stock firmware package into the flashable //! stock images, so the toolkit can restore a board to genuine stock using the //! vendor's own files (no carved blobs). //! //! Two genuine source shapes are handled for the Zynq-7010 (Antminer S17): //! //! - OTA update `.tar.gz` (`Antminer-S17-user-OM--sig*.tar.gz`): a signed //! outer tar holding `cert.pem`, `fw.tar.gz` and `runme.sh` (each with a //! `.sig`). The inner `fw.tar.gz` holds `BOOT.bin`, `uImage` (legacy kernel), //! `uramdisk.image.gz` (rootfs) and `md5_info` (md5 of the rootfs). The OTA //! package does NOT carry the device tree: the factory SD provisioning writes //! it once and OTA upgrades preserve it. //! - SD recovery `.zip` (`SD_Antminer-S17-*.zip`): the full factory image, //! which DOES include `devicetree.dtb` alongside `BOOT.bin`/`uImage`/ //! `uramdisk.image.gz`. This is the complete source for a from-anywhere //! restore, because it carries the device tree the stock kernel needs. //! //! Extraction shells out to the system `tar`/`unzip`/`gzip` (as the release //! fetch shells out to `curl`); nothing is written outside a private temp dir. use std::path::Path; use std::process::Command; use crate::md5::md5_hex; #[derive(Debug, thiserror::Error)] pub enum StockFirmwareError { #[error("io: {0}")] Io(String), #[error("could not read {0}")] Read(String), #[error("unrecognised firmware package (not a .tar.gz or .zip): {0}")] Format(String), #[error("extraction failed: {0}")] Extract(String), #[error("the firmware package is missing a stock {0} image")] MissingImage(&'static str), #[error("rootfs md5 mismatch: package lists {expected}, image is {actual}")] RootfsMd5 { expected: String, actual: String }, #[error("needed system tool not found: {0}")] MissingTool(String), } /// The stock images carved from a genuine Bitmain firmware package, ready to /// write back to NAND. `boot_bin` and `dtb` are optional (an OTA package omits /// the dtb; the bootloader is only written on an explicit full restore). pub struct StockFirmware { pub boot_bin: Option>, pub dtb: Option>, pub kernel: Vec, pub rootfs: Vec, pub version: Option, /// The source package kind, for logging. pub source_kind: &'static str, } impl StockFirmware { pub fn summary(&self) -> String { let v = self.version.as_deref().unwrap_or("unknown"); format!( "{} (version {}): kernel {} B, rootfs {} B, dtb {}, BOOT.bin {}", self.source_kind, v, self.kernel.len(), self.rootfs.len(), self.dtb.as_ref().map_or("absent", |_| "present"), self.boot_bin.as_ref().map_or("absent", |_| "present"), ) } } fn have_tool(tool: &str) -> bool { Command::new(tool) .arg("--version") .output() .map(|o| o.status.success() || !o.stdout.is_empty() || !o.stderr.is_empty()) .unwrap_or(false) } fn run(cmd: &mut Command, what: &str) -> Result<(), StockFirmwareError> { let out = cmd .output() .map_err(|e| StockFirmwareError::Extract(format!("{what}: {e}")))?; if !out.status.success() { return Err(StockFirmwareError::Extract(format!( "{what}: {}", String::from_utf8_lossy(&out.stderr).trim() ))); } Ok(()) } /// Recursively collect files under `dir` as (relative-path-lowercased, absolute path). fn collect_files(dir: &Path) -> Vec<(String, std::path::PathBuf)> { fn walk(base: &Path, dir: &Path, out: &mut Vec<(String, std::path::PathBuf)>) { let Ok(entries) = std::fs::read_dir(dir) else { return; }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { walk(base, &path, out); } else if let Ok(rel) = path.strip_prefix(base) { out.push((rel.to_string_lossy().to_lowercase(), path.clone())); } } } let mut out = Vec::new(); walk(dir, dir, &mut out); out } /// Pick the best file whose basename matches `name`, preferring paths that /// contain one of `prefer` path fragments (e.g. "bin/" for the SD image, "fw" /// for the OTA inner tree), then the shallowest path. fn pick<'a>( files: &'a [(String, std::path::PathBuf)], name: &str, prefer: &[&str], ) -> Option<&'a std::path::PathBuf> { let name = name.to_lowercase(); let mut matches: Vec<&(String, std::path::PathBuf)> = files .iter() .filter(|(rel, _)| rel.rsplit('/').next() == Some(name.as_str()) || *rel == name) .collect(); if matches.is_empty() { return None; } matches.sort_by_key(|(rel, _)| { let pref_rank = prefer .iter() .position(|p| rel.contains(p)) .unwrap_or(prefer.len()); let depth = rel.matches('/').count(); (pref_rank, depth) }); matches.first().map(|(_, p)| p) } fn read(path: &Path) -> Result, StockFirmwareError> { std::fs::read(path).map_err(|_| StockFirmwareError::Read(path.display().to_string())) } /// 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())))?; if bytes.len() < 4 { return Err(StockFirmwareError::Format(path.display().to_string())); } let is_gzip = bytes[0] == 0x1f && bytes[1] == 0x8b; let is_zip = &bytes[0..2] == b"PK"; if !is_gzip && !is_zip { return Err(StockFirmwareError::Format(path.display().to_string())); } let tmp = tempfile::Builder::new() .prefix("alkane-stockfw-") .tempdir() .map_err(|e| StockFirmwareError::Io(e.to_string()))?; let root = tmp.path(); let (source_kind, prefer): (&'static str, &[&str]) = if is_zip { if !have_tool("unzip") { return Err(StockFirmwareError::MissingTool("unzip".into())); } run( Command::new("unzip") .arg("-qq") .arg("-o") .arg(path) .arg("-d") .arg(root), "unzip SD recovery image", )?; ("Bitmain SD recovery image", &["bin/"]) } else { if !have_tool("tar") { return Err(StockFirmwareError::MissingTool("tar".into())); } run( Command::new("tar").arg("xzf").arg(path).arg("-C").arg(root), "untar OTA package", )?; // The signed OTA wraps the real images in an inner fw.tar.gz; extract it. let inner = collect_files(root) .into_iter() .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()))?; run( Command::new("tar") .arg("xzf") .arg(&inner_path) .arg("-C") .arg(&inner_dir), "untar OTA inner fw.tar.gz", )?; } ("Bitmain OTA update package", &["fw/", "bin/"]) }; 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 = 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()?; // Verify the rootfs against md5_info when the package ships one (OTA does). if let Some(md5_path) = pick(&files, "md5_info", prefer) { if let Ok(raw) = std::fs::read_to_string(md5_path) { let expected = raw.split_whitespace().next().unwrap_or("").to_lowercase(); if expected.len() == 32 { let actual = md5_hex(&rootfs); if actual != expected { return Err(StockFirmwareError::RootfsMd5 { expected, actual }); } } } } let version = pick(&files, "version", prefer) .or_else(|| pick(&files, "version_number", &[""])) .and_then(|p| std::fs::read_to_string(p).ok()) .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()); Ok(StockFirmware { boot_bin, dtb, kernel, rootfs, version, source_kind, }) } #[cfg(test)] mod tests { use super::*; #[test] 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(_)) )); } // Parse a real Bitmain firmware package. Set ALKANE_TEST_STOCK_FW to its path. // Ignored by default (needs the vendor file, not in the repo). #[test] #[ignore] fn parses_real_package() { let Ok(path) = std::env::var("ALKANE_TEST_STOCK_FW") else { eprintln!("set ALKANE_TEST_STOCK_FW to a firmware file"); return; }; let fw = parse(Path::new(&path)).expect("parse"); eprintln!("{}", fw.summary()); assert!(!fw.kernel.is_empty(), "kernel present"); assert!(!fw.rootfs.is_empty(), "rootfs present"); // The kernel is a legacy u-boot uImage: magic 0x27051956 big-endian. assert_eq!(&fw.kernel[0..4], &[0x27, 0x05, 0x19, 0x56], "uImage magic"); } }