|
|
|
@@ -0,0 +1,756 @@
|
|
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
|
//! Amlogic A113D / AXG (Antminer S21 Pro-class) board module: tier-2 network
|
|
|
|
|
//! UPDATE of a board already running alkane. Our OS is staged as FILES in the
|
|
|
|
|
//! nvdata UBI volume (mtd6): anthillos/{vmlinux.bin, devicetree.dtb,
|
|
|
|
|
//! uramdisk.image.gz}. The signed FIP bootloader (mtd0/mtd1), the stock boot
|
|
|
|
|
//! fallback (mtd4), and mtd2/3/5 are PRESERVED - this module performs ZERO raw
|
|
|
|
|
//! NAND writes. It copies three files into an already-mounted UBIFS volume and
|
|
|
|
|
//! nothing else, so no code path here can touch a raw /dev/mtd device.
|
|
|
|
|
//!
|
|
|
|
|
//! The brick guard is therefore STRUCTURAL: there is no flash_erase, nandwrite,
|
|
|
|
|
//! or dd-to-/dev/mtd anywhere in this module. Each file destination is checked
|
|
|
|
|
//! to be a bare basename inside the resolved anthillos directory of a ubifs
|
|
|
|
|
//! mount; the raw FIP partitions (mtd0-5) are never named.
|
|
|
|
|
//!
|
|
|
|
|
//! The first from-stock install (via the vendor toolkit, past the signed
|
|
|
|
|
//! bootloader) is the dsh-owned path and is NOT this module. This is the
|
|
|
|
|
//! repeatable alkane-to-alkane update.
|
|
|
|
|
|
|
|
|
|
use crate::md5::md5_hex;
|
|
|
|
|
use crate::preflight::{classify, parse_digest};
|
|
|
|
|
use crate::transport::{Remote, RemoteError};
|
|
|
|
|
use alkane_artifacts::afw::{AfwImage, AfwPartition, 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 = "a113d";
|
|
|
|
|
pub const ARCH: &str = "arm64";
|
|
|
|
|
/// The UBI volume subdirectory the boot chain reads our OS files from.
|
|
|
|
|
pub const ANTHILLOS_DIR: &str = "anthillos";
|
|
|
|
|
/// nvdata UBI usable size; the three files together must fit (0xB900000).
|
|
|
|
|
pub const NVDATA_USABLE: u64 = 0xB900000;
|
|
|
|
|
/// Raw NAND partitions that are NEVER a write target (FIP + stock boot).
|
|
|
|
|
pub const PRESERVE_DEVICES: [&str; 6] = [
|
|
|
|
|
"/dev/mtd0", "/dev/mtd1", "/dev/mtd2", "/dev/mtd3", "/dev/mtd4", "/dev/mtd5",
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
/// Authoritative file targets: (image, on-board basename, ceiling, format).
|
|
|
|
|
/// Written rootfs -> dtb -> kernel so a mid-write interruption never leaves a
|
|
|
|
|
/// new rootfs beside an old kernel (the kernel file lands last).
|
|
|
|
|
const TARGETS: [(&str, &str, u64, &str); 3] = [
|
|
|
|
|
("rootfs", "uramdisk.image.gz", 0x6000000, "uimage"),
|
|
|
|
|
("dtb", "devicetree.dtb", 0x100000, "fdt"),
|
|
|
|
|
("kernel", "vmlinux.bin", 0x4000000, "arm64-image"),
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
#[derive(Debug, Error)]
|
|
|
|
|
pub enum A113dPlanError {
|
|
|
|
|
#[error("bundle is for {0}, not a113d")]
|
|
|
|
|
WrongBoard(String),
|
|
|
|
|
#[error("bundle arch is {0}, a113d needs arm64")]
|
|
|
|
|
WrongArch(String),
|
|
|
|
|
#[error("a113d requires bootloader_policy preserve (the FIP is never written)")]
|
|
|
|
|
BootloaderPolicy,
|
|
|
|
|
#[error("a113d bundle carries a bootloader/spl/fip/tpl member: {0}")]
|
|
|
|
|
BootloaderMember(String),
|
|
|
|
|
#[error("manifest is not an OS payload")]
|
|
|
|
|
PayloadType,
|
|
|
|
|
#[error("manifest marker is empty")]
|
|
|
|
|
Marker,
|
|
|
|
|
#[error("a113d must install exactly kernel, dtb and rootfs")]
|
|
|
|
|
InstallCount,
|
|
|
|
|
#[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 },
|
|
|
|
|
#[error("a113d {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
|
|
|
|
|
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")]
|
|
|
|
|
NotArm64 { image: String },
|
|
|
|
|
#[error("a113d {image} is not an FDT")]
|
|
|
|
|
NotFdt { image: String },
|
|
|
|
|
#[error("a113d {image} is not a legacy uImage")]
|
|
|
|
|
NotUimage { image: String },
|
|
|
|
|
#[error("a113d refuses: preserved partition {0} (mtd0-5) carries an image")]
|
|
|
|
|
PreservedCarriesImage(String),
|
|
|
|
|
#[error("a113d refuses an unsafe destination for {image}: {dest}")]
|
|
|
|
|
UnsafeDest { image: String, dest: String },
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
pub struct A113dTarget {
|
|
|
|
|
pub image_name: String,
|
|
|
|
|
/// On-board basename inside the anthillos directory (never a device path).
|
|
|
|
|
pub dest: String,
|
|
|
|
|
pub size: u64,
|
|
|
|
|
pub data: Vec<u8>,
|
|
|
|
|
pub expected_md5: String,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
pub struct A113dPlan {
|
|
|
|
|
pub targets: Vec<A113dTarget>,
|
|
|
|
|
pub marker: String,
|
|
|
|
|
pub kernel_version: String,
|
|
|
|
|
pub sdk_revision: String,
|
|
|
|
|
pub os_revision: String,
|
|
|
|
|
pub afw_sha256: String,
|
|
|
|
|
pub min_free_bytes: u64,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn is_bootloaderish(image: &AfwImage) -> bool {
|
|
|
|
|
let lowered = format!("{} {} {}", image.name, image.file, image.role).to_lowercase();
|
|
|
|
|
image.role == "bootloader"
|
|
|
|
|
|| lowered.contains("spl")
|
|
|
|
|
|| lowered.contains("u-boot")
|
|
|
|
|
|| lowered.contains("uboot")
|
|
|
|
|
|| lowered.contains("fip")
|
|
|
|
|
|| lowered.contains("tpl")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// A destination is safe only as a bare basename (no separators, no traversal,
|
|
|
|
|
/// not a device path). This is what keeps every write inside anthillos/.
|
|
|
|
|
fn is_safe_dest(dest: &str) -> bool {
|
|
|
|
|
!dest.is_empty()
|
|
|
|
|
&& !dest.contains('/')
|
|
|
|
|
&& !dest.contains("..")
|
|
|
|
|
&& !dest.starts_with("/dev/")
|
|
|
|
|
&& dest == dest.trim()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl A113dPlan {
|
|
|
|
|
pub fn from_afw(afw: &VerifiedAfw) -> Result<Self, A113dPlanError> {
|
|
|
|
|
let manifest = &afw.manifest;
|
|
|
|
|
if manifest.board != BOARD {
|
|
|
|
|
return Err(A113dPlanError::WrongBoard(manifest.board.clone()));
|
|
|
|
|
}
|
|
|
|
|
if manifest.arch != ARCH {
|
|
|
|
|
return Err(A113dPlanError::WrongArch(manifest.arch.clone()));
|
|
|
|
|
}
|
|
|
|
|
if manifest.payload_type != "os" {
|
|
|
|
|
return Err(A113dPlanError::PayloadType);
|
|
|
|
|
}
|
|
|
|
|
if manifest.bootloader_policy != BootloaderPolicy::Preserve {
|
|
|
|
|
return Err(A113dPlanError::BootloaderPolicy);
|
|
|
|
|
}
|
|
|
|
|
if manifest.marker.is_empty() {
|
|
|
|
|
return Err(A113dPlanError::Marker);
|
|
|
|
|
}
|
|
|
|
|
// FIP / bootloader members are never allowed - we reuse the board's.
|
|
|
|
|
for image in &manifest.images {
|
|
|
|
|
if is_bootloaderish(image) {
|
|
|
|
|
return Err(A113dPlanError::BootloaderMember(image.file.clone()));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// 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()));
|
|
|
|
|
}
|
|
|
|
|
// A preserved partition device must be in the never-write set when listed.
|
|
|
|
|
let _ = &partition.device;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let installs: Vec<&AfwImage> = manifest.images.iter().filter(|i| i.install).collect();
|
|
|
|
|
if installs.len() != TARGETS.len() {
|
|
|
|
|
return Err(A113dPlanError::InstallCount);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let mut targets = Vec::with_capacity(TARGETS.len());
|
|
|
|
|
let mut total = 0u64;
|
|
|
|
|
for (image_name, dest, ceiling, expected_format) in TARGETS {
|
|
|
|
|
let image = manifest
|
|
|
|
|
.images
|
|
|
|
|
.iter()
|
|
|
|
|
.find(|i| i.name == image_name && i.install)
|
|
|
|
|
.ok_or_else(|| A113dPlanError::MissingImage(image_name.to_owned()))?;
|
|
|
|
|
if image.format != expected_format {
|
|
|
|
|
return Err(A113dPlanError::ImageFormat {
|
|
|
|
|
image: image_name.to_owned(),
|
|
|
|
|
actual: image.format.clone(),
|
|
|
|
|
expected: expected_format,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
if image.size > ceiling {
|
|
|
|
|
return Err(A113dPlanError::ImageTooLarge {
|
|
|
|
|
image: image_name.to_owned(),
|
|
|
|
|
size: image.size,
|
|
|
|
|
ceiling,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
if !is_safe_dest(dest) {
|
|
|
|
|
return Err(A113dPlanError::UnsafeDest {
|
|
|
|
|
image: image_name.to_owned(),
|
|
|
|
|
dest: dest.to_owned(),
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
let data = afw
|
|
|
|
|
.image(image_name)
|
|
|
|
|
.map(|(_, data)| data)
|
|
|
|
|
.ok_or_else(|| A113dPlanError::MissingImage(image_name.to_owned()))?;
|
|
|
|
|
// Magic checks, independent of the producer gate.
|
|
|
|
|
match expected_format {
|
|
|
|
|
"arm64-image" => {
|
|
|
|
|
if !(data.len() >= 0x3C && data[0x38..0x3C] == *b"ARMd") {
|
|
|
|
|
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() });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
"uimage" => {
|
|
|
|
|
if !(data.len() >= 4 && data[0..4] == [0x27, 0x05, 0x19, 0x56]) {
|
|
|
|
|
return Err(A113dPlanError::NotUimage { image: image_name.to_owned() });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
_ => {}
|
|
|
|
|
}
|
|
|
|
|
total += image.size;
|
|
|
|
|
targets.push(A113dTarget {
|
|
|
|
|
image_name: image_name.to_owned(),
|
|
|
|
|
dest: dest.to_owned(),
|
|
|
|
|
size: image.size,
|
|
|
|
|
expected_md5: md5_hex(data),
|
|
|
|
|
data: data.to_vec(),
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
if total > NVDATA_USABLE {
|
|
|
|
|
return Err(A113dPlanError::OverNvdata { total, usable: NVDATA_USABLE });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Ok(Self {
|
|
|
|
|
targets,
|
|
|
|
|
marker: manifest.marker.clone(),
|
|
|
|
|
kernel_version: manifest.kernel_version.clone(),
|
|
|
|
|
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(
|
|
|
|
|
"tier 2 update: copy OS files into the nvdata UBI (anthillos/); \
|
|
|
|
|
FIP (mtd0/1) + stock boot (mtd4) + mtd2/3/5 preserved, zero raw NAND writes\n",
|
|
|
|
|
);
|
|
|
|
|
out.push_str("image format kernel=arm64-image, dtb=fdt, rootfs=uimage\n");
|
|
|
|
|
for target in &self.targets {
|
|
|
|
|
out.push_str(&format!(
|
|
|
|
|
"copy {} -> {ANTHILLOS_DIR}/{} size {} B md5 {}\n",
|
|
|
|
|
target.image_name, target.dest, target.size, target.expected_md5
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
out.push_str(&format!(
|
|
|
|
|
"marker {} kernel {} sdk {} os {}",
|
|
|
|
|
self.marker,
|
|
|
|
|
self.kernel_version,
|
|
|
|
|
short(&self.sdk_revision),
|
|
|
|
|
short(&self.os_revision),
|
|
|
|
|
));
|
|
|
|
|
out
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn short(rev: &str) -> &str {
|
|
|
|
|
rev.get(..12).unwrap_or(rev)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Debug, Error)]
|
|
|
|
|
pub enum A113dError {
|
|
|
|
|
#[error("preflight failed:\n{0}")]
|
|
|
|
|
Preflight(String),
|
|
|
|
|
#[error("--confirm FLASH is required to write")]
|
|
|
|
|
Confirm,
|
|
|
|
|
#[error("no mounted ubifs volume with an {0}/ directory was found; refusing to write")]
|
|
|
|
|
NoAnthillos(String),
|
|
|
|
|
#[error("refusing an unsafe destination: {0}")]
|
|
|
|
|
UnsafeDest(String),
|
|
|
|
|
#[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 A113dCheck {
|
|
|
|
|
pub name: String,
|
|
|
|
|
pub ok: bool,
|
|
|
|
|
pub detail: String,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
pub struct A113dPreflight {
|
|
|
|
|
pub host: String,
|
|
|
|
|
pub checks: Vec<A113dCheck>,
|
|
|
|
|
/// Resolved absolute anthillos directory on a mounted ubifs volume.
|
|
|
|
|
pub anthillos: Option<String>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl A113dPreflight {
|
|
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Find a mounted ubifs volume that already holds an anthillos/ directory - that
|
|
|
|
|
/// is where the running alkane boots our OS files from, and the only place this
|
|
|
|
|
/// module ever writes. We never attach or mount a raw device ourselves.
|
|
|
|
|
fn resolve_anthillos(remote: &mut dyn Remote) -> Result<Option<String>, A113dError> {
|
|
|
|
|
let mounts = remote.user_command("cat /proc/mounts 2>/dev/null", Duration::from_secs(20))?;
|
|
|
|
|
for line in String::from_utf8_lossy(&mounts).lines() {
|
|
|
|
|
let mut fields = line.split_whitespace();
|
|
|
|
|
let _dev = fields.next().unwrap_or("");
|
|
|
|
|
let mountpoint = fields.next().unwrap_or("");
|
|
|
|
|
let fstype = fields.next().unwrap_or("");
|
|
|
|
|
if fstype != "ubifs" || mountpoint.is_empty() {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
let candidate = format!("{}/{ANTHILLOS_DIR}", mountpoint.trim_end_matches('/'));
|
|
|
|
|
let probe = remote.user_command(
|
|
|
|
|
&format!("test -d {candidate} && echo __HAVE__"),
|
|
|
|
|
Duration::from_secs(15),
|
|
|
|
|
)?;
|
|
|
|
|
if String::from_utf8_lossy(&probe).contains("__HAVE__") {
|
|
|
|
|
return Ok(Some(candidate));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(None)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn preflight(
|
|
|
|
|
plan: &A113dPlan,
|
|
|
|
|
remote: &mut dyn Remote,
|
|
|
|
|
host: &str,
|
|
|
|
|
) -> Result<A113dPreflight, A113dError> {
|
|
|
|
|
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(A113dCheck {
|
|
|
|
|
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(A113dCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") });
|
|
|
|
|
|
|
|
|
|
let tools = remote.user_command(
|
|
|
|
|
"for c in ubiattach mount cp 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(A113dCheck {
|
|
|
|
|
name: "commands".to_owned(),
|
|
|
|
|
ok: missing.is_empty(),
|
|
|
|
|
detail: if missing.is_empty() {
|
|
|
|
|
"ubi/file tools present".to_owned()
|
|
|
|
|
} else {
|
|
|
|
|
format!("missing {}", missing.join(", "))
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// nvdata (mtd6) must be present; we never write it raw, but its absence means
|
|
|
|
|
// the board is not the expected layout.
|
|
|
|
|
let mtd = String::from_utf8_lossy(
|
|
|
|
|
&remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?,
|
|
|
|
|
)
|
|
|
|
|
.into_owned();
|
|
|
|
|
let have_nvdata = mtd.contains("mtd6:");
|
|
|
|
|
checks.push(A113dCheck {
|
|
|
|
|
name: "nvdata".to_owned(),
|
|
|
|
|
ok: have_nvdata,
|
|
|
|
|
detail: if have_nvdata {
|
|
|
|
|
"mtd6 (nvdata UBI) present".to_owned()
|
|
|
|
|
} else {
|
|
|
|
|
format!("mtd6 not found: {mtd}")
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Every destination is a bare basename - the structural brick guard.
|
|
|
|
|
let dests_safe = plan.targets.iter().all(|t| is_safe_dest(&t.dest));
|
|
|
|
|
checks.push(A113dCheck {
|
|
|
|
|
name: "file-only".to_owned(),
|
|
|
|
|
ok: dests_safe,
|
|
|
|
|
detail: format!(
|
|
|
|
|
"all writes are files in {ANTHILLOS_DIR}/; raw {} never touched",
|
|
|
|
|
PRESERVE_DEVICES.join(",")
|
|
|
|
|
),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Resolve the anthillos directory on a mounted ubifs volume.
|
|
|
|
|
let anthillos = resolve_anthillos(remote)?;
|
|
|
|
|
checks.push(A113dCheck {
|
|
|
|
|
name: "anthillos".to_owned(),
|
|
|
|
|
ok: anthillos.is_some(),
|
|
|
|
|
detail: match &anthillos {
|
|
|
|
|
Some(path) => format!("writing into {path}"),
|
|
|
|
|
None => "no mounted ubifs volume with anthillos/".to_owned(),
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
Ok(A113dPreflight { host: host.to_owned(), checks, anthillos })
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
pub struct A113dInstallOptions {
|
|
|
|
|
pub dry_run: bool,
|
|
|
|
|
pub confirm: Option<String>,
|
|
|
|
|
pub no_reboot: bool,
|
|
|
|
|
pub backup_dir: PathBuf,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
pub struct A113dBackup {
|
|
|
|
|
pub image_name: String,
|
|
|
|
|
pub dest: String,
|
|
|
|
|
pub path: Option<PathBuf>,
|
|
|
|
|
pub md5: Option<String>,
|
|
|
|
|
pub size: u64,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
pub struct A113dReceipt {
|
|
|
|
|
pub anthillos: String,
|
|
|
|
|
pub backups: Vec<A113dBackup>,
|
|
|
|
|
pub rebooted: bool,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub enum A113dOutcome {
|
|
|
|
|
DryRun(Box<A113dPreflight>),
|
|
|
|
|
Installed(A113dReceipt),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn install(
|
|
|
|
|
plan: &A113dPlan,
|
|
|
|
|
remote: &mut dyn Remote,
|
|
|
|
|
options: &A113dInstallOptions,
|
|
|
|
|
host: &str,
|
|
|
|
|
) -> Result<A113dOutcome, A113dError> {
|
|
|
|
|
let report = preflight(plan, remote, host)?;
|
|
|
|
|
if !report.ok() {
|
|
|
|
|
return Err(A113dError::Preflight(report.render()));
|
|
|
|
|
}
|
|
|
|
|
if options.dry_run {
|
|
|
|
|
return Ok(A113dOutcome::DryRun(Box::new(report)));
|
|
|
|
|
}
|
|
|
|
|
if options.confirm.as_deref() != Some("FLASH") {
|
|
|
|
|
return Err(A113dError::Confirm);
|
|
|
|
|
}
|
|
|
|
|
let anthillos = report
|
|
|
|
|
.anthillos
|
|
|
|
|
.clone()
|
|
|
|
|
.ok_or_else(|| A113dError::NoAnthillos(ANTHILLOS_DIR.to_owned()))?;
|
|
|
|
|
|
|
|
|
|
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 {
|
|
|
|
|
// Structural guard, re-asserted at the point of writing: the destination
|
|
|
|
|
// is a bare basename inside anthillos/. No raw device can be named here.
|
|
|
|
|
if !is_safe_dest(&target.dest) {
|
|
|
|
|
return Err(A113dError::UnsafeDest(target.dest.clone()));
|
|
|
|
|
}
|
|
|
|
|
let name = &target.image_name;
|
|
|
|
|
let dest_path = format!("{anthillos}/{}", target.dest);
|
|
|
|
|
|
|
|
|
|
// Back up the existing file we are about to overwrite, if present.
|
|
|
|
|
let have = remote.user_command(
|
|
|
|
|
&format!("test -f {dest_path} && echo __YES__"),
|
|
|
|
|
Duration::from_secs(15),
|
|
|
|
|
)?;
|
|
|
|
|
if String::from_utf8_lossy(&have).contains("__YES__") {
|
|
|
|
|
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 {
|
|
|
|
|
image_name: name.clone(),
|
|
|
|
|
dest: target.dest.clone(),
|
|
|
|
|
md5: Some(md5_hex(&data)),
|
|
|
|
|
size: data.len() as u64,
|
|
|
|
|
path: Some(local),
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
backups.push(A113dBackup {
|
|
|
|
|
image_name: name.clone(),
|
|
|
|
|
dest: target.dest.clone(),
|
|
|
|
|
md5: None,
|
|
|
|
|
size: 0,
|
|
|
|
|
path: None,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Stage the verified payload and prove its remote md5 before copying.
|
|
|
|
|
let mut staged = tempfile::NamedTempFile::new()?;
|
|
|
|
|
staged.write_all(&target.data)?;
|
|
|
|
|
staged.flush()?;
|
|
|
|
|
let remote_stage = format!("/tmp/.alkane-a113d-{name}.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(A113dError::StageMismatch(name.clone()));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Copy into the UBI volume (file write only), then sync. No raw NAND.
|
|
|
|
|
remote.root_command(
|
|
|
|
|
&format!("cp -f {remote_stage} {dest_path} && sync"),
|
|
|
|
|
Duration::from_secs(300),
|
|
|
|
|
)?;
|
|
|
|
|
|
|
|
|
|
// Read back the copied file and compare md5.
|
|
|
|
|
let readback = parse_digest(
|
|
|
|
|
&remote.root_command(&format!("md5sum {dest_path}"), Duration::from_secs(60))?,
|
|
|
|
|
32,
|
|
|
|
|
)
|
|
|
|
|
.unwrap_or_default();
|
|
|
|
|
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
|
|
|
|
|
if readback != target.expected_md5 {
|
|
|
|
|
return Err(A113dError::Readback(name.clone()));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let rebooted = if options.no_reboot {
|
|
|
|
|
false
|
|
|
|
|
} else {
|
|
|
|
|
remote.reboot()?;
|
|
|
|
|
true
|
|
|
|
|
};
|
|
|
|
|
Ok(A113dOutcome::Installed(A113dReceipt { anthillos, backups, rebooted }))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn owns_board(board: &str) -> bool {
|
|
|
|
|
board == BOARD
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// True when no plan target would ever name a preserved raw partition. Used by
|
|
|
|
|
/// tests to assert the structural guard holds for the fixed TARGETS table.
|
|
|
|
|
pub fn no_raw_device_targets(plan: &A113dPlan) -> bool {
|
|
|
|
|
plan.targets.iter().all(|t| {
|
|
|
|
|
is_safe_dest(&t.dest) && !PRESERVE_DEVICES.iter().any(|d| t.dest.contains(d))
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[allow(dead_code)]
|
|
|
|
|
fn _partition_is_preserved(p: &AfwPartition) -> bool {
|
|
|
|
|
p.name != "nvdata"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
|
mod tests {
|
|
|
|
|
use super::*;
|
|
|
|
|
use alkane_artifacts::afw::{AfwManifest, AfwMember};
|
|
|
|
|
use serde_json::json;
|
|
|
|
|
use sha2::{Digest, Sha256};
|
|
|
|
|
|
|
|
|
|
const REV: &str = "0123456789abcdef0123456789abcdef01234567";
|
|
|
|
|
|
|
|
|
|
fn arm64_image(payload: &[u8]) -> Vec<u8> {
|
|
|
|
|
let mut b = vec![0u8; 64];
|
|
|
|
|
b[0x38..0x3C].copy_from_slice(b"ARMd");
|
|
|
|
|
b.extend_from_slice(payload);
|
|
|
|
|
b
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn dtb() -> Vec<u8> {
|
|
|
|
|
let mut b = vec![0u8; 2048];
|
|
|
|
|
b[0..4].copy_from_slice(&[0xd0, 0x0d, 0xfe, 0xed]);
|
|
|
|
|
b
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn uramdisk() -> Vec<u8> {
|
|
|
|
|
let mut b = vec![0u8; 64];
|
|
|
|
|
b[0..4].copy_from_slice(&[0x27, 0x05, 0x19, 0x56]);
|
|
|
|
|
b
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn afw_with(
|
|
|
|
|
kernel: Vec<u8>,
|
|
|
|
|
dtb: Vec<u8>,
|
|
|
|
|
rootfs: Vec<u8>,
|
|
|
|
|
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();
|
|
|
|
|
json!({"name": name, "file": file, "role": role, "format": fmt,
|
|
|
|
|
"size": data.len(), "sha256": sha, "partition": "nvdata", "install": true})
|
|
|
|
|
};
|
|
|
|
|
let value = json!({
|
|
|
|
|
"schema": 2, "format": "afw", "board": "a113d", "arch": "arm64",
|
|
|
|
|
"version": "0.1.0", "build_date": "2026-11-06T00:00:00Z",
|
|
|
|
|
"sdk_revision": REV, "os_revision": REV, "payload_type": "os",
|
|
|
|
|
"bootloader_policy": "preserve",
|
|
|
|
|
"signature": {"type": "unsigned", "member": null, "public_key_hex": null},
|
|
|
|
|
"partitions": partitions,
|
|
|
|
|
"images": [
|
|
|
|
|
image("kernel", "payload/vmlinux.bin", "kernel", "arm64-image", &kernel),
|
|
|
|
|
image("dtb", "payload/devicetree.dtb", "dtb", "fdt", &dtb),
|
|
|
|
|
image("rootfs", "payload/uramdisk.image.gz", "rootfs", "uimage", &rootfs),
|
|
|
|
|
],
|
|
|
|
|
"boot_switch": {}, "preflight": {"min_free_bytes": 16777216},
|
|
|
|
|
"recovery": {}, "marker": "Alkane", "kernel_version": "6.18.48"
|
|
|
|
|
});
|
|
|
|
|
let manifest: AfwManifest = serde_json::from_value(value).unwrap();
|
|
|
|
|
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 },
|
|
|
|
|
],
|
|
|
|
|
manifest_sha256: "0".repeat(64),
|
|
|
|
|
archive_sha256: "0".repeat(64),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn preserved_partitions() -> serde_json::Value {
|
|
|
|
|
json!([
|
|
|
|
|
{"name":"bootloader","device":"/dev/mtd0","offset":0,"size":2097152,
|
|
|
|
|
"secure":true,"boot_critical":true,"write_order":0,"image":null},
|
|
|
|
|
{"name":"nvdata","device":"/dev/mtd6","offset":74448896,"size":193986560,
|
|
|
|
|
"secure":false,"boot_critical":true,"write_order":1,"image":"kernel"}
|
|
|
|
|
])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn good() -> VerifiedAfw {
|
|
|
|
|
afw_with(arm64_image(b"k"), dtb(), uramdisk(), preserved_partitions())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn accepts_a_good_plan_as_file_copies() {
|
|
|
|
|
let plan = A113dPlan::from_afw(&good()).unwrap();
|
|
|
|
|
assert_eq!(plan.targets.len(), 3);
|
|
|
|
|
// write order rootfs, dtb, kernel (kernel file lands last)
|
|
|
|
|
assert_eq!(plan.targets[0].image_name, "rootfs");
|
|
|
|
|
assert_eq!(plan.targets[2].image_name, "kernel");
|
|
|
|
|
// Every destination is a bare basename - no raw device anywhere.
|
|
|
|
|
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!(plan.render().contains("anthillos/"));
|
|
|
|
|
assert!(plan.render().contains("zero raw NAND writes"));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn refuses_a_non_arm64_kernel() {
|
|
|
|
|
let r = A113dPlan::from_afw(&afw_with(vec![0u8; 64], dtb(), uramdisk(), preserved_partitions()));
|
|
|
|
|
assert!(matches!(r, Err(A113dPlanError::NotArm64 { .. })));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn refuses_an_oversize_kernel() {
|
|
|
|
|
let big = arm64_image(&vec![0u8; 0x4000000]);
|
|
|
|
|
let r = A113dPlan::from_afw(&afw_with(big, dtb(), uramdisk(), preserved_partitions()));
|
|
|
|
|
assert!(matches!(r, Err(A113dPlanError::ImageTooLarge { .. })));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
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(_))));
|
|
|
|
|
let mut v = good();
|
|
|
|
|
v.manifest.images[1].file = "payload/fip.bin".to_owned();
|
|
|
|
|
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::BootloaderMember(_))));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn refuses_a_preserved_partition_carrying_an_image() {
|
|
|
|
|
let partitions = json!([
|
|
|
|
|
{"name":"bootloader","device":"/dev/mtd0","offset":0,"size":2097152,
|
|
|
|
|
"secure":true,"boot_critical":true,"write_order":0,"image":"kernel"},
|
|
|
|
|
{"name":"nvdata","device":"/dev/mtd6","offset":74448896,"size":193986560,
|
|
|
|
|
"secure":false,"boot_critical":true,"write_order":1,"image":"kernel"}
|
|
|
|
|
]);
|
|
|
|
|
let v = afw_with(arm64_image(b"k"), dtb(), uramdisk(), partitions);
|
|
|
|
|
assert!(matches!(
|
|
|
|
|
A113dPlan::from_afw(&v),
|
|
|
|
|
Err(A113dPlanError::PreservedCarriesImage(_))
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
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(_))));
|
|
|
|
|
let mut v = good();
|
|
|
|
|
v.manifest.arch = "armv7".to_owned();
|
|
|
|
|
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");
|
|
|
|
|
for dev in PRESERVE_DEVICES {
|
|
|
|
|
assert!(!dest.contains(dev), "{image} dest names a preserved device");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn unsafe_dest_is_rejected_by_guard() {
|
|
|
|
|
assert!(!is_safe_dest("/dev/mtd0"));
|
|
|
|
|
assert!(!is_safe_dest("../escape"));
|
|
|
|
|
assert!(!is_safe_dest("sub/dir/file"));
|
|
|
|
|
assert!(is_safe_dest("vmlinux.bin"));
|
|
|
|
|
}
|
|
|
|
|
}
|