//! Closed firmware, carried as data and kept apart from Pinnacle's own code //! (`docs/hardware.md`, "Closed firmware"). Each package is described in //! `firmware/.txt`: whose it is, its licence, the linux-firmware //! commit it comes from, and each file's path there, size and SHA-256. The //! files are not in the repository: `cargo xtask firmware` fetches them //! into `target/firmware//`, refusing any whose size or hash differs, //! and a PC's system disk carries them, with the description, in //! `system:/firmware//` unless `PINNACLE_NO_FIRMWARE=1`. use crate::{Result, root}; use std::path::{Path, PathBuf}; use std::process::Command; /// One package, as its description gives it. pub struct Package { /// The description's own name, `intel-wifi`. pub name: String, /// The file the description was read from. pub description: PathBuf, /// Where on the system disk it goes, without the disk: `/firmware/intel`. pub folder: String, /// The repository (`…/linux-firmware.git`) and the commit taken. source: String, commit: String, pub files: Vec, } /// One file of a package. pub struct File { /// Its name on the system disk. pub name: String, /// Its path in the source repository. from: String, size: u64, sha256: [u8; 32], } fn hex32(s: &str) -> Option<[u8; 32]> { let s = s.trim(); if s.len() != 64 { return None; } let mut out = [0u8; 32]; for (i, b) in out.iter_mut().enumerate() { *b = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()?; } Some(out) } fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } /// Reads a description: `key: value` lines, `file:` starting a file whose /// keys are indented below it, `#` comments. fn parse(path: &Path, text: &str) -> Result { let fail = |line: usize, what: &str| format!("{}:{}: {what}", path.display(), line + 1); let mut top: Vec<(String, String)> = Vec::new(); let mut files: Vec<(String, Vec<(String, String)>)> = Vec::new(); for (n, line) in text.lines().enumerate() { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') { continue; } let (key, value) = trimmed .split_once(':') .ok_or_else(|| fail(n, "not `key: value`"))?; let (key, value) = (key.trim().to_string(), value.trim().to_string()); if line.starts_with([' ', '\t']) { let (_, keys) = files .last_mut() .ok_or_else(|| fail(n, "an indented key outside a file"))?; keys.push((key, value)); } else if key == "file" { files.push((value, Vec::new())); } else { top.push((key, value)); } } let get = |list: &[(String, String)], key: &str| { list.iter() .find(|(k, _)| k == key) .map(|(_, v)| v.clone()) .ok_or_else(|| format!("{}: no `{key}`", path.display())) }; let installs = get(&top, "installs-to")?; let folder = installs .strip_prefix("system:") .filter(|f| f.starts_with("/firmware/")) .ok_or_else(|| format!("{}: installs-to must be under system:/firmware/", path.display()))? .to_string(); for key in ["vendor", "licence", "licence-url", "tag"] { get(&top, key)?; } let files = files .into_iter() .map(|(name, keys)| { if name.contains(['/', ':']) || name.starts_with('.') { return Err(format!("{}: `{name}` is not a plain file name", path.display())); } Ok(File { from: get(&keys, "from")?, size: get(&keys, "size")? .parse() .map_err(|_| format!("{}: {name}: size is not a number", path.display()))?, sha256: hex32(&get(&keys, "sha256")?) .ok_or_else(|| format!("{}: {name}: sha256 is not 64 hex digits", path.display()))?, name, }) }) .collect::>>()?; Ok(Package { name: get(&top, "name")?, description: path.to_path_buf(), folder, source: get(&top, "source")?, commit: get(&top, "commit")?, files, }) } /// Every package `firmware/` describes, by name. pub fn packages() -> Result> { let dir = root().join("firmware"); let mut paths: Vec = std::fs::read_dir(&dir) .map_err(|e| format!("{}: {e}", dir.display()))? .filter_map(|e| e.ok().map(|e| e.path())) .filter(|p| p.extension().is_some_and(|x| x == "txt")) .collect(); paths.sort(); paths .iter() .map(|p| { let text = std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display()))?; parse(p, &text) }) .collect() } /// Where a package's fetched files are kept. fn kept(package: &Package) -> PathBuf { root().join("target/firmware").join(&package.name) } /// Whether `bytes` are the file the description names. fn checks(file: &File, bytes: &[u8]) -> std::result::Result<(), String> { if bytes.len() as u64 != file.size { return Err(format!("{} bytes, not the {} described", bytes.len(), file.size)); } let got = pinnacle_crypto::sha2::Sha256::digest(bytes); if got != file.sha256 { return Err(format!( "SHA-256 {}, not the {} described", hex(&got), hex(&file.sha256) )); } Ok(()) } /// Fetches every file of `package` not already kept and whole, from its /// source at its commit, each checked before it is kept. Returns the folder. pub fn fetch(package: &Package) -> Result { let dir = kept(package); std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; for file in &package.files { let at = dir.join(&file.name); if std::fs::read(&at).is_ok_and(|b| checks(file, &b).is_ok()) { continue; } let url = format!("{}/plain/{}?id={}", package.source, file.from, package.commit); let part = dir.join(format!("{}.part", file.name)); let status = Command::new("curl") .args(["-sSfL", "--retry", "2", "--max-time", "300", "-o"]) .arg(&part) .arg(&url) .status() .map_err(|e| format!("curl: {e}"))?; if !status.success() { let _ = std::fs::remove_file(&part); return Err(format!("{}: could not fetch {url}", file.name)); } let bytes = std::fs::read(&part).map_err(|e| format!("{}: {e}", part.display()))?; if let Err(e) = checks(file, &bytes) { let _ = std::fs::remove_file(&part); return Err(format!("{}: refused: {e}", file.name)); } std::fs::rename(&part, &at).map_err(|e| format!("{}: {e}", at.display()))?; println!( "firmware: {} ({} bytes, sha256 {})", file.name, file.size, hex(&file.sha256) ); } Ok(dir) } /// `cargo xtask firmware`: every package fetched and checked. pub fn fetch_all() -> Result { for package in packages()? { let dir = fetch(&package)?; println!( "firmware: {}: {} files in {}", package.name, package.files.len(), dir.display() ); } Ok(()) } /// What a PC's system disk carries of the closed firmware: each package's /// files and its description, as (path on the disk, bytes). None with /// `PINNACLE_NO_FIRMWARE=1`; a package that cannot be fetched (no network) /// is left out, and said so. pub fn for_image() -> Result)>> { if std::env::var("PINNACLE_NO_FIRMWARE").is_ok_and(|v| v == "1") { println!("firmware: none on the system disk (PINNACLE_NO_FIRMWARE=1)"); return Ok(Vec::new()); } let mut out = Vec::new(); for package in packages()? { let dir = match fetch(&package) { Ok(dir) => dir, Err(e) => { eprintln!( "xtask: firmware {} left off the system disk: {e} (`cargo xtask firmware` fetches it)", package.name ); continue; } }; for file in &package.files { let at = dir.join(&file.name); let bytes = std::fs::read(&at).map_err(|e| format!("{}: {e}", at.display()))?; checks(file, &bytes).map_err(|e| format!("{}: {e}", at.display()))?; out.push((format!("{}/{}", package.folder, file.name), bytes)); } let description = std::fs::read(&package.description) .map_err(|e| format!("{}: {e}", package.description.display()))?; out.push((format!("{}/{}.txt", package.folder, package.name), description)); } Ok(out) }