Files
alkane-toolkit/crates/alkane-flash/src/stock_method.rs
T
noahandClaude Opus 4.8 be2eab6262
source / check (pull_request) Skipped
verify / verify (pull_request) Canceled after 0s
feat(flash): readable network-only stock<->alkane install/restore for a113d (and zynq)
a113d (Amlogic AXG, Antminer BHB42XXX) - VALIDATED end-to-end on bench hardware:
- aml_ubi.rs: stage the OS files into the nvdata UBIFS volume and drive a
  one-byte boot FLAG in misc block 1. Stock U-Boot `checkalk` raw-reads the flag
  (no UBI) and only on a magic match runs `alkboot` (ubifsload alkane + booti),
  else `storeboot` -> genuine stock. Install sets flag=ALAN from stock and writes
  the boot env in-band via /dev/nand_env (CRC-correct 64 KiB blob, read back
  byte-exact before reboot). Restore erases the flag block in-band from the
  running alkane OS and reboots - no stock firmware file needed, boot regions
  mtd0-5 never written. The magic is tested byte-by-byte (this vendor U-Boot's
  `itest.l *<mem>` mis-compares; `itest.b` works).
- stock.rs: dispatch board==a113d to aml_ubi for install_from_stock /
  restore_to_stock; add restore_aml_flag() for the firmware-free A113D restore.
- CLI: a113d is a supported install target; `afw restore-stock` works with no
  --stock-firmware for a113d (flag flip).

zynq-7010 readable path (install validated; restore awaits the NAND-ECC match):
- zynq_nand.rs + uimage.rs: uImage-wrapped NAND install-from-stock over the DSH
  root primitive, on-board stock backup carve/restore. Install is confirmed to
  persist and boot; restore-to-stock still needs stock-compatible ECC and is NOT
  presented as done.

stock_method.rs carries DSH-authored a113d root-on-stock support (sealed; method
not described here). 92/92 alkane-flash tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B1W6qKwKxq3oUPDKWicM6i
2026-11-14 00:43:30 -06:00

4195 lines
134 KiB
Rust

// SPDX-License-Identifier: MIT
//! Network-only method bodies for crossing a board between stock and alkane
//! (install-from-stock and restore-to-stock).
//!
//! The method is plain, self-contained Rust. It uses only the standard library
//! plus ordinary local command-line tools (ssh, sshpass, curl). There is no
//! external helper and no runtime dependency on any other tool. The board is
//! reached over the network only; no serial console is used.
//!
//! The public interface this implements lives in `stock.rs` (`StockMethod`,
//! `StockError`). This file provides `method()` returning a
//! `&'static dyn StockMethod`.
//!
//! Brick safety for zynq: /dev/mtd0 below 0x1a00000 holds BOOT.bin (FSBL,
//! bitstream and U-Boot). Every write target in this module is checked to sit
//! at or above that boundary before any erase or write is issued.
use crate::stock::{
HeldSlot, InPlaceOptions, InPlaceOutcome, InPlaceReceipt, RestoreImages, StockError,
StockMethod,
};
use alkane_artifacts::afw::VerifiedAfw;
use std::borrow::Cow;
use std::env;
use std::fs;
use std::io::{ErrorKind, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
const BOARD: &str = "zynq-7010";
const BLK: u64 = 0x20000;
const BOOTBIN_PRESERVE: u64 = 0x1A00000;
const ABS_DTB: u64 = 0x1A00000;
const ABS_KERNEL: u64 = 0x2000000;
const ABS_ROOTFS: u64 = 0x2800000;
const DTB_SLOT: u64 = 0x20000;
const KERNEL_SLOT: u64 = 0x800000;
const ROOTFS_SLOT: u64 = 0x2000000;
// A complete genuine-stock backup kept on the board by a from-stock install.
// The area sits in the vendor `reserve` partition after the alkane MAC region,
// clear of the stock `configs` UBI, the alkane boot slots and BOOT.bin.
const STOCK_BACKUP_BASE: u64 = 0x5200000;
const STOCK_BACKUP_END: u64 = 0x6000000;
const STOCK_BACKUP_HEADER: u64 = 0x20000;
const STOCK_BACKUP_MAGIC: &str = "ALKANE-STOCK-BACKUP 1";
// ---------------------------------------------------------------- stock assets
//
// The stock payloads are not compiled into the toolkit. They are fetched over
// the network on first use and cached on this machine; every cached file is
// re-checked against the SHA-256 below before it is used.
const STOCK_ASSETS_BASE_DEFAULT: &str =
"https://gitea.bluefla.re/blueflare/alkane-stock-assets/releases/download/zynq-7010-v1";
struct StockAsset {
file: &'static str,
sha256: &'static str,
}
// Restore writes the genuine Bitmain kernel and rootfs supplied by the caller.
// Two small per-board pieces are not in Bitmain's distributable firmware and are
// fetched: the NAND-exposing helper, and the kernel device tree (factory-
// provisioned, preserved by every vendor update, so never shipped in an OTA/SD
// package). The dtb is what pairs the genuine kernel/rootfs to the board's
// partition layout; writing the wrong one reboot-loops the board.
const ASSET_DTB: StockAsset = StockAsset {
file: "blob-1.bin",
sha256: "10a0199be8a638c4bf319a623362a89b6bee38f732ab00204df499a2f25ad2ea",
};
const ASSET_MTD_PATCH: StockAsset = StockAsset {
file: "blob-4.bin",
sha256: "51cfa6806ac0618d67a3d6f2383bc755c67507958c578fc899a25e589c9cf444",
};
fn assets_base() -> String {
env::var("ALKANE_STOCK_ASSETS_BASE")
.ok()
.map(|value| value.trim().trim_end_matches('/').to_string())
.filter(|value| !value.is_empty())
.unwrap_or_else(|| STOCK_ASSETS_BASE_DEFAULT.to_string())
}
fn stock_token() -> Option<String> {
env::var("ALKANE_RELEASE_TOKEN")
.ok()
.filter(|token| !token.is_empty())
.or_else(|| {
env::var("GITEA_TOKEN")
.ok()
.filter(|token| !token.is_empty())
})
}
fn asset_cache_dir() -> Result<PathBuf, StockError> {
let base = env::var_os("XDG_CACHE_HOME")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.or_else(|| {
env::var_os("HOME")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.map(|path| path.join(".cache"))
})
.unwrap_or_else(env::temp_dir);
let dir = base.join("alkane-toolkit").join("stock-assets");
fs::create_dir_all(&dir)
.map_err(|e| StockError::Io(format!("could not create the asset cache: {e}")))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
}
Ok(dir)
}
fn create_private_file(path: &Path) -> Result<(), StockError> {
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
.map(|_| ())
.map_err(|e| StockError::Io(format!("could not create a temporary file: {e}")))
}
#[cfg(not(unix))]
{
fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map(|_| ())
.map_err(|e| StockError::Io(format!("could not create a temporary file: {e}")))
}
}
fn write_private_new(path: &Path, data: &[u8]) -> Result<(), StockError> {
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
.map_err(|e| StockError::Io(format!("could not write a temporary file: {e}")))?;
file.write_all(data)
.map_err(|e| StockError::Io(format!("could not write a temporary file: {e}")))
}
#[cfg(not(unix))]
{
fs::write(path, data)
.map_err(|e| StockError::Io(format!("could not write a temporary file: {e}")))
}
}
/// A token-bearing curl config file, created 0600 and removed on drop. The
/// token itself never appears on a command line or in a process argument.
struct AssetTokenConfig {
path: Option<PathBuf>,
}
impl AssetTokenConfig {
fn new(dir: &Path) -> Result<Self, StockError> {
let Some(token) = stock_token() else {
return Ok(Self { path: None });
};
let path = dir.join(format!(".curl-auth-{}.cfg", random_token()));
let header = format!(
"header = {}\n",
curl_quote(&format!("Authorization: token {token}"))
);
write_private_new(&path, header.as_bytes())?;
Ok(Self { path: Some(path) })
}
fn apply(&self, command: &mut Command) {
if let Some(path) = &self.path {
command.arg("--config").arg(path);
}
}
}
impl Drop for AssetTokenConfig {
fn drop(&mut self) {
if let Some(path) = &self.path {
let _ = fs::remove_file(path);
}
}
}
fn fetch_stock_asset(asset: &StockAsset, dest: &Path) -> Result<(), StockError> {
let dir = dest
.parent()
.ok_or_else(|| StockError::Io("asset cache path is invalid".into()))?;
let partial = dir.join(format!(".{}.{}.part", asset.file, random_token()));
create_private_file(&partial)?;
let config = match AssetTokenConfig::new(dir) {
Ok(config) => config,
Err(e) => {
let _ = fs::remove_file(&partial);
return Err(e);
}
};
let url = format!("{}/{}", assets_base(), asset.file);
let mut command = Command::new("curl");
command
.arg("-fsSL")
.arg("--max-time")
.arg("600")
.arg("--retry")
.arg("2")
.arg("-o")
.arg(&partial);
config.apply(&mut command);
command.arg(&url);
let output = match command.output() {
Ok(output) => output,
Err(e) => {
let _ = fs::remove_file(&partial);
return Err(StockError::Network(format!("could not run curl: {e}")));
}
};
if !output.status.success() {
let _ = fs::remove_file(&partial);
let stderr = String::from_utf8_lossy(&output.stderr);
let denied = stderr.contains("401") || stderr.contains("404");
if denied && stock_token().is_none() {
return Err(StockError::Network(
"the stock asset download was denied; a Gitea token is required (set ALKANE_RELEASE_TOKEN or GITEA_TOKEN)"
.into(),
));
}
return Err(StockError::Network(format!(
"could not download stock asset {}: {}",
asset.file,
stderr.trim()
)));
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(&partial, fs::Permissions::from_mode(0o600));
}
let data = fs::read(&partial)
.map_err(|e| StockError::Io(format!("could not read a downloaded asset: {e}")))?;
if sha256_hex(&data) != asset.sha256 {
let _ = fs::remove_file(&partial);
return Err(StockError::Method("asset integrity check failed".into()));
}
fs::rename(&partial, dest)
.map_err(|e| StockError::Io(format!("could not cache a downloaded asset: {e}")))?;
Ok(())
}
/// Return the bytes of a stock asset, using the local cache when it still
/// matches the embedded SHA-256 and fetching it otherwise.
fn stock_asset(asset: &StockAsset) -> Result<Vec<u8>, StockError> {
let dir = asset_cache_dir()?;
let path = dir.join(asset.file);
match fs::read(&path) {
Ok(data) => {
if sha256_hex(&data) == asset.sha256 {
return Ok(data);
}
let _ = fs::remove_file(&path);
}
Err(e) if e.kind() == ErrorKind::NotFound => {}
Err(e) => {
return Err(StockError::Io(format!(
"could not read a cached stock asset: {e}"
)))
}
}
fetch_stock_asset(asset, &path)?;
let data = fs::read(&path)
.map_err(|e| StockError::Io(format!("could not read a cached stock asset: {e}")))?;
if sha256_hex(&data) != asset.sha256 {
let _ = fs::remove_file(&path);
return Err(StockError::Method("asset integrity check failed".into()));
}
Ok(data)
}
// ---------------------------------------------------------------- SHA-256
struct Sha256 {
state: [u32; 8],
length: u64,
buffer: [u8; 64],
used: usize,
}
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,
];
fn new() -> Self {
Self {
state: [
0x6a09_e667,
0xbb67_ae85,
0x3c6e_f372,
0xa54f_f53a,
0x510e_527f,
0x9b05_688c,
0x1f83_d9ab,
0x5be0_cd19,
],
length: 0,
buffer: [0u8; 64],
used: 0,
}
}
fn update(&mut self, mut data: &[u8]) {
self.length = self.length.wrapping_add(data.len() as u64);
if self.used > 0 {
let take = (64 - self.used).min(data.len());
self.buffer[self.used..self.used + take].copy_from_slice(&data[..take]);
self.used += take;
data = &data[take..];
if self.used == 64 {
let block = self.buffer;
self.compress(&block);
self.used = 0;
}
}
while data.len() >= 64 {
let mut block = [0u8; 64];
block.copy_from_slice(&data[..64]);
self.compress(&block);
data = &data[64..];
}
if !data.is_empty() {
self.buffer[..data.len()].copy_from_slice(data);
self.used = data.len();
}
}
fn compress(&mut self, block: &[u8]) {
let mut w = [0u32; 64];
for (i, chunk) in block.chunks_exact(4).enumerate().take(16) {
w[i] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.state;
for i in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ ((!e) & g);
let t1 = h
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(Self::K[i])
.wrapping_add(w[i]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let t2 = s0.wrapping_add(maj);
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
self.state[0] = self.state[0].wrapping_add(a);
self.state[1] = self.state[1].wrapping_add(b);
self.state[2] = self.state[2].wrapping_add(c);
self.state[3] = self.state[3].wrapping_add(d);
self.state[4] = self.state[4].wrapping_add(e);
self.state[5] = self.state[5].wrapping_add(f);
self.state[6] = self.state[6].wrapping_add(g);
self.state[7] = self.state[7].wrapping_add(h);
}
fn finalize(mut self) -> [u8; 32] {
let bit_length = self.length.wrapping_mul(8);
self.update(&[0x80]);
while self.used != 56 {
self.update(&[0]);
}
self.update(&bit_length.to_be_bytes());
let mut out = [0u8; 32];
for (i, word) in self.state.iter().enumerate() {
out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
}
out
}
}
fn sha256_hex(data: &[u8]) -> String {
let digest = {
let mut hasher = Sha256::new();
hasher.update(data);
hasher.finalize()
};
let mut out = String::with_capacity(64);
for byte in digest {
out.push_str(&format!("{byte:02x}"));
}
out
}
// ---------------------------------------------------------------- local I/O
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(tag: &str) -> Result<Self, StockError> {
let base = env::temp_dir();
for _ in 0..16 {
let path = base.join(format!(
"alkane-{tag}-{}-{}",
std::process::id(),
random_token()
));
match fs::create_dir(&path) {
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}"
)))
}
}
}
Err(StockError::Io(
"could not create a temporary directory".into(),
))
}
fn path(&self) -> &Path {
&self.path
}
fn join(&self, name: &str) -> PathBuf {
self.path.join(name)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
fn write_private(path: &Path, data: &[u8]) -> Result<(), StockError> {
fs::write(path, data)
.map_err(|e| StockError::Io(format!("could not write a temporary file: {e}")))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(path, fs::Permissions::from_mode(0o600));
}
Ok(())
}
fn write_curl_config(path: &Path, lines: &[String]) -> Result<(), StockError> {
let mut text = String::new();
for line in lines {
text.push_str(line);
text.push('\n');
}
write_private(path, text.as_bytes())
}
fn curl_quote(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 2);
out.push('"');
for c in value.chars() {
match c {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
_ => out.push(c),
}
}
out.push('"');
out
}
fn random_token() -> String {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
format!("{:x}{:x}", std::process::id(), nanos)
}
fn validate_host(host: &str) -> Result<(), StockError> {
if host.is_empty() || host.len() > 253 {
return Err(StockError::Method("invalid target address".into()));
}
let valid = host
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | ':' | '-' | '_'));
if !valid {
return Err(StockError::Method("invalid target address".into()));
}
Ok(())
}
struct CmdResult {
status: Option<i32>,
stdout: Vec<u8>,
stderr: Vec<u8>,
timed_out: bool,
}
impl CmdResult {
fn ok(&self) -> bool {
!self.timed_out && self.status == Some(0)
}
}
fn run_command(
mut command: Command,
timeout: Duration,
input: Option<Vec<u8>>,
) -> Result<CmdResult, StockError> {
command.stdin(if input.is_some() {
Stdio::piped()
} else {
Stdio::null()
});
run_command_io(command, timeout, input)
}
/// Run a command with a file as its standard input. The file is handed to the
/// child directly, so a multi-megabyte payload is not copied through memory.
fn run_command_stream(
mut command: Command,
timeout: Duration,
input: fs::File,
) -> Result<CmdResult, StockError> {
command.stdin(Stdio::from(input));
run_command_io(command, timeout, None)
}
fn run_command_io(
mut command: Command,
timeout: Duration,
input: Option<Vec<u8>>,
) -> Result<CmdResult, StockError> {
command.stdout(Stdio::piped());
command.stderr(Stdio::piped());
let mut child = command
.spawn()
.map_err(|e| StockError::Io(format!("could not start a required local tool: {e}")))?;
let stdout_pipe = child.stdout.take();
let stderr_pipe = child.stderr.take();
let stdout_reader = stdout_pipe.map(|mut pipe| {
thread::spawn(move || {
let mut data = Vec::new();
let _ = pipe.read_to_end(&mut data);
data
})
});
let stderr_reader = stderr_pipe.map(|mut pipe| {
thread::spawn(move || {
let mut data = Vec::new();
let _ = pipe.read_to_end(&mut data);
data
})
});
let stdin_writer = if let Some(data) = input {
child.stdin.take().map(|mut pipe| {
thread::spawn(move || {
let _ = pipe.write_all(&data);
let _ = pipe.flush();
})
})
} else {
None
};
let start = Instant::now();
let mut timed_out = false;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break Some(status.code()),
Ok(None) => {
if start.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait();
timed_out = true;
break None;
}
thread::sleep(Duration::from_millis(50));
}
Err(e) => {
let _ = child.kill();
let _ = child.wait();
return Err(StockError::Io(format!("a required local tool failed: {e}")));
}
}
};
if let Some(writer) = stdin_writer {
let _ = writer.join();
}
let stdout = stdout_reader
.and_then(|reader| reader.join().ok())
.unwrap_or_default();
let stderr = stderr_reader
.and_then(|reader| reader.join().ok())
.unwrap_or_default();
Ok(CmdResult {
status: status.flatten(),
stdout,
stderr,
timed_out,
})
}
fn text(data: &[u8]) -> String {
String::from_utf8_lossy(data).into_owned()
}
// ---------------------------------------------------------------- SSH
fn ssh_command(host: &str, password: Option<&str>, remote: &str) -> Command {
ssh_command_as(host, "root", password, remote)
}
fn ssh_command_as(host: &str, user: &str, password: Option<&str>, remote: &str) -> Command {
let mut command;
if let Some(password) = password {
command = Command::new("sshpass");
command.arg("-e");
command.arg("ssh");
command.env("SSHPASS", password);
} else {
command = Command::new("ssh");
}
command.args([
"-F",
"/dev/null",
"-o",
"StrictHostKeyChecking=no",
"-o",
"UserKnownHostsFile=/dev/null",
"-o",
"ConnectTimeout=10",
"-o",
"NumberOfPasswordPrompts=1",
"-o",
"LogLevel=ERROR",
]);
if password.is_none() {
command.args(["-o", "BatchMode=yes"]);
}
command.arg(format!("{user}@{host}"));
command.arg(remote);
command
}
fn ssh_exec_as(
host: &str,
user: &str,
password: Option<&str>,
remote: &str,
timeout: Duration,
) -> Result<CmdResult, StockError> {
let result = run_command(ssh_command_as(host, user, password, remote), timeout, None)?;
if result.timed_out {
return Err(StockError::Network("target did not respond".into()));
}
Ok(result)
}
/// True when the SSH failure is the login being refused rather than the target
/// being unreachable or a command failing after it ran.
fn is_login_refused(result: &CmdResult) -> bool {
if result.timed_out {
return false;
}
let lower = text(&result.stderr).to_lowercase();
lower.contains("permission denied")
|| lower.contains("authentication failed")
|| lower.contains("no supported authentication")
|| lower.contains("too many authentication failures")
|| lower.contains("root login rejected")
}
fn classify_ssh(result: &CmdResult) -> StockError {
let lower = text(&result.stderr).to_lowercase();
let auth = lower.contains("permission denied")
|| lower.contains("authentication failed")
|| lower.contains("no supported authentication")
|| lower.contains("too many authentication failures");
if auth {
return StockError::Auth("target rejected the credential".into());
}
StockError::Network("could not reach the target".into())
}
fn ssh_exec(
host: &str,
password: Option<&str>,
remote: &str,
timeout: Duration,
) -> Result<CmdResult, StockError> {
let result = run_command(ssh_command(host, password, remote), timeout, None)?;
if result.timed_out {
return Err(StockError::Network("target did not respond".into()));
}
Ok(result)
}
fn ssh_probe(host: &str, password: Option<&str>) -> Result<(), StockError> {
let result = ssh_exec(
host,
password,
"echo __ALKANE_OK__",
Duration::from_secs(20),
)?;
if result.ok() && text(&result.stdout).contains("__ALKANE_OK__") {
return Ok(());
}
Err(classify_ssh(&result))
}
fn ssh_push(
host: &str,
password: Option<&str>,
remote_path: &str,
data: &[u8],
timeout: Duration,
) -> Result<(), StockError> {
let remote = format!("cat > {remote_path}");
let result = run_command(
ssh_command(host, password, &remote),
timeout,
Some(data.to_vec()),
)?;
if result.timed_out {
return Err(StockError::Network("target transfer timed out".into()));
}
if !result.ok() {
return Err(classify_ssh(&result));
}
Ok(())
}
// Quote one argument for a POSIX shell. A single-quoted string is literal, so
// the only character needing work is the quote itself.
fn shell_quote(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 2);
out.push('\'');
for c in value.chars() {
if c == '\'' {
out.push_str("'\\''");
} else {
out.push(c);
}
}
out.push('\'');
out
}
// The combined output of a completed command: standard output followed by
// standard error, joined with a newline if both are non-empty.
fn command_output(result: &CmdResult) -> String {
let mut out = text(&result.stdout);
let error = text(&result.stderr);
if !error.is_empty() {
if !out.is_empty() && !out.ends_with('\n') {
out.push('\n');
}
out.push_str(&error);
}
out
}
fn command_exit_error(status: i32, output: String) -> StockError {
if output.is_empty() {
StockError::Method(format!("command exited with status {status}"))
} else {
StockError::Method(output)
}
}
// A command that reached the board and exited non-zero. Authentication and
// transport failures are classified as such; everything else carries the
// command's output.
fn command_failure(result: &CmdResult) -> StockError {
if result.timed_out {
return StockError::Network("target did not respond".into());
}
let lower = text(&result.stderr).to_lowercase();
let transport = lower.contains("permission denied")
|| lower.contains("authentication failed")
|| lower.contains("no supported authentication")
|| lower.contains("connection refused")
|| lower.contains("connection reset")
|| lower.contains("connection closed")
|| lower.contains("broken pipe")
|| lower.contains("no route to host")
|| lower.contains("could not resolve");
if result.status == Some(255) && transport {
return classify_ssh(result);
}
command_exit_error(result.status.unwrap_or(-1), command_output(result))
}
fn validate_remote_path(path: &str) -> Result<(), StockError> {
if path.is_empty() || path.contains('\0') || path.ends_with('/') {
return Err(StockError::Method("invalid remote path".into()));
}
Ok(())
}
fn remote_parent(path: &str) -> &str {
match path.rfind('/') {
Some(0) => "/",
Some(index) => &path[..index],
None => ".",
}
}
fn ssh_root_ready(host: &str, password: Option<&str>) -> Result<(), StockError> {
ssh_probe(host, password)
}
fn reboot_target(host: &str, password: Option<&str>) {
let _ = run_command(
ssh_command(
host,
password,
"sync; (echo b > /proc/sysrq-trigger) 2>/dev/null || reboot -f",
),
Duration::from_secs(15),
None,
);
}
fn resolve_password(password: Option<&str>) -> Option<String> {
if let Some(password) = password {
if !password.is_empty() {
return Some(password.to_string());
}
}
if let Ok(password) = env::var("ALKANE_BOARD_PASSWORD") {
if !password.is_empty() {
return Some(password);
}
}
if let Ok(path) = env::var("ALKANE_BOARD_PASSWORD_FILE") {
if let Ok(raw) = fs::read_to_string(path) {
let password = raw.trim_end_matches(['\n', '\r']).to_string();
if !password.is_empty() {
return Some(password);
}
}
}
None
}
fn web_password_candidates(password: Option<&str>) -> Vec<String> {
let mut candidates = Vec::new();
if let Some(password) = password {
if !password.is_empty() {
candidates.push(password.to_string());
}
}
if let Ok(password) = env::var("ALKANE_STOCK_WEB_PASSWORD") {
if !password.is_empty() && !candidates.iter().any(|c| c == &password) {
candidates.push(password);
}
}
if let Some(password) = resolve_password(None) {
if !candidates.iter().any(|c| c == &password) {
candidates.push(password);
}
}
if !candidates.iter().any(|c| c == "root") {
candidates.push("root".to_string());
}
candidates
}
// ---------------------------------------------------------------- network probes
fn tcp_banner(host: &str, port: u16, timeout: Duration) -> Option<Vec<u8>> {
let addrs = (host, port).to_socket_addrs().ok()?;
for addr in addrs {
if let Ok(mut stream) = TcpStream::connect_timeout(&addr, timeout) {
let _ = stream.set_read_timeout(Some(timeout));
let mut buf = [0u8; 256];
if let Ok(n) = stream.read(&mut buf) {
if n > 0 {
return Some(buf[..n].to_vec());
}
}
}
}
None
}
fn ssh_port_open(host: &str) -> bool {
tcp_banner(host, 22, Duration::from_millis(1500)).is_some()
}
fn is_alkane_ssh(host: &str) -> bool {
match tcp_banner(host, 22, Duration::from_millis(1500)) {
Some(banner) => text(&banner).to_lowercase().contains("dropbear"),
None => false,
}
}
fn is_stock_http(host: &str) -> bool {
let mut command = Command::new("curl");
command.args(["-sS", "-i", "--max-time", "6", &format!("http://{host}/")]);
match run_command(command, Duration::from_secs(12), None) {
Ok(result) => {
let lower = text(&result.stdout).to_lowercase();
lower.contains("lighttpd") && (lower.contains("antminer") || lower.contains("401"))
}
Err(_) => false,
}
}
fn wait_for<F>(mut predicate: F, timeout: Duration) -> bool
where
F: FnMut() -> bool,
{
let deadline = Instant::now() + timeout;
loop {
if predicate() {
return true;
}
if Instant::now() >= deadline {
return false;
}
thread::sleep(Duration::from_secs(3));
}
}
fn wait_alkane(host: &str, timeout: Duration) -> bool {
wait_for(|| is_alkane_ssh(host), timeout)
}
fn wait_stock(host: &str, timeout: Duration) -> bool {
wait_for(|| is_stock_http(host), timeout)
}
// ---------------------------------------------------------------- curl
fn run_curl(config: &Path, timeout: Duration) -> Result<CmdResult, StockError> {
let mut command = Command::new("curl");
command.arg("--config").arg(config);
run_command(command, timeout, None)
}
fn http_code(result: &CmdResult) -> u16 {
text(&result.stdout).trim().parse::<u16>().unwrap_or(0)
}
fn stock_web_auth(host: &str, password: &str, dir: &Path, tag: &str) -> Result<(), StockError> {
let config = dir.join(format!("auth-{tag}.cfg"));
let output = dir.join(format!("auth-{tag}.out"));
write_curl_config(
&config,
&[
"silent".to_string(),
"show-error".to_string(),
"digest".to_string(),
"max-time = 15".to_string(),
format!("url = {}", curl_quote(&format!("http://{host}/"))),
format!("user = {}", curl_quote(&format!("root:{password}"))),
format!("output = {}", curl_quote(&output.to_string_lossy())),
"write-out = \"%{http_code}\"".to_string(),
],
)?;
let result = run_curl(&config, Duration::from_secs(25))?;
match http_code(&result) {
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(),
)),
}
}
fn stock_web_upload(
host: &str,
password: &str,
dir: &Path,
body: &Path,
boundary: &str,
tag: &str,
) -> Result<(), StockError> {
stock_web_upload_with_timeout(host, password, dir, body, boundary, tag, 600)
}
fn stock_web_upload_with_timeout(
host: &str,
password: &str,
dir: &Path,
body: &Path,
boundary: &str,
tag: &str,
max_time_secs: u64,
) -> Result<(), StockError> {
let config = dir.join(format!("upload-{tag}.cfg"));
let output = dir.join(format!("upload-{tag}.out"));
write_curl_config(
&config,
&[
"silent".to_string(),
"show-error".to_string(),
"digest".to_string(),
"location".to_string(),
"max-redirs = 5".to_string(),
format!("max-time = {max_time_secs}"),
format!(
"url = {}",
curl_quote(&format!("http://{host}/cgi-bin/upgrade.cgi"))
),
format!("user = {}", curl_quote(&format!("root:{password}"))),
format!(
"header = {}",
curl_quote(&format!(
"Content-Type: multipart/form-data; boundary={boundary}"
))
),
"header = \"Expect:\"".to_string(),
format!(
"data-binary = {}",
curl_quote(&format!("@{}", body.display()))
),
format!("output = {}", curl_quote(&output.to_string_lossy())),
"write-out = \"%{http_code}\"".to_string(),
],
)?;
let result = run_curl(&config, Duration::from_secs(max_time_secs + 20))?;
match http_code(&result) {
200..=299 => Ok(()),
401 | 403 => Err(StockError::Auth("target rejected the credential".into())),
0 => Err(StockError::Network("target unreachable".into())),
_ => Err(StockError::Method("target transfer failed".into())),
}
}
fn stock_web_trigger(
host: &str,
password: &str,
dir: &Path,
cgi: &str,
tag: &str,
) -> Result<CmdResult, StockError> {
stock_web_trigger_with_timeout(host, password, dir, cgi, tag, 900)
}
fn stock_web_trigger_with_timeout(
host: &str,
password: &str,
dir: &Path,
cgi: &str,
tag: &str,
max_time_secs: u64,
) -> Result<CmdResult, StockError> {
let config = dir.join(format!("trigger-{tag}.cfg"));
write_curl_config(
&config,
&[
"silent".to_string(),
"show-error".to_string(),
"digest".to_string(),
"location".to_string(),
"max-redirs = 5".to_string(),
format!("max-time = {max_time_secs}"),
format!(
"url = {}",
curl_quote(&format!("http://{host}/cgi-bin/{cgi}"))
),
format!("user = {}", curl_quote(&format!("root:{password}"))),
],
)?;
run_curl(&config, Duration::from_secs(max_time_secs + 20))
}
// ---------------------------------------------------------------- AFW
fn afw_payload<'a>(afw: &'a VerifiedAfw, image: &str, file: &str) -> Option<&'a [u8]> {
if let Some((_, data)) = afw.image(image) {
return Some(data);
}
if let Some(data) = afw.payload(file) {
return Some(data);
}
let short = file.strip_prefix("payload/").unwrap_or(file);
afw.payload(short)
}
fn load_install_images(afw: &VerifiedAfw) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>), StockError> {
if afw.manifest.board != BOARD {
return Err(StockError::Method("image is not for this target".into()));
}
let zimage = afw_payload(afw, "kernel", "payload/zImage")
.ok_or_else(|| StockError::Method("image is incomplete".into()))?;
let dtb = afw_payload(afw, "dtb", "payload/zynq-alkane.dtb")
.ok_or_else(|| StockError::Method("image is incomplete".into()))?;
let rootfs = afw_payload(afw, "rootfs", "payload/rootfs.cpio.gz")
.ok_or_else(|| StockError::Method("image is incomplete".into()))?;
if zimage.len() < 0x28 || zimage[0x24..0x28] != [0x18, 0x28, 0x6f, 0x01] {
return Err(StockError::Method("image is not a kernel".into()));
}
if dtb.len() < 8 || dtb[0..4] != [0xd0, 0x0d, 0xfe, 0xed] {
return Err(StockError::Method("image is not a device tree".into()));
}
if rootfs.len() < 2 || rootfs[0..2] != [0x1f, 0x8b] {
return Err(StockError::Method("image is not a root filesystem".into()));
}
let kernel = mk_uimage(zimage, 0x8000, 0x8000, 5, 2, 2, 0, b"alkane");
let rootfs_uimage = mk_uimage(rootfs, 0, 0, 5, 2, 3, 1, b"alkane-rootfs");
Ok((kernel, dtb.to_vec(), rootfs_uimage))
}
// ---------------------------------------------------------------- uImage
fn be32(dst: &mut [u8], value: u32) {
dst[..4].copy_from_slice(&value.to_be_bytes());
}
fn mk_uimage(
data: &[u8],
load: u32,
entry: u32,
os: u8,
arch: u8,
kind: u8,
compression: u8,
name: &[u8],
) -> Vec<u8> {
let mut header = [0u8; 64];
be32(&mut header[0..4], 0x2705_1956);
be32(&mut header[8..12], 0);
be32(&mut header[12..16], data.len() as u32);
be32(&mut header[16..20], load);
be32(&mut header[20..24], entry);
be32(&mut header[24..28], crc32(data));
header[28] = os;
header[29] = arch;
header[30] = kind;
header[31] = compression;
let count = name.len().min(32);
header[32..32 + count].copy_from_slice(&name[..count]);
let header_crc = crc32(&header);
be32(&mut header[4..8], header_crc);
let mut out = Vec::with_capacity(64 + data.len());
out.extend_from_slice(&header);
out.extend_from_slice(data);
out
}
// ---------------------------------------------------------------- MD5 / CRC32
struct Md5 {
state: [u32; 4],
length: u64,
buffer: [u8; 64],
used: usize,
}
impl Md5 {
fn new() -> Self {
Self {
state: [0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476],
length: 0,
buffer: [0u8; 64],
used: 0,
}
}
fn update(&mut self, mut data: &[u8]) {
self.length = self.length.wrapping_add(data.len() as u64);
if self.used > 0 {
let need = 64 - self.used;
let take = need.min(data.len());
self.buffer[self.used..self.used + take].copy_from_slice(&data[..take]);
self.used += take;
data = &data[take..];
if self.used == 64 {
let block = self.buffer;
self.compress(&block);
self.used = 0;
}
}
while data.len() >= 64 {
let mut block = [0u8; 64];
block.copy_from_slice(&data[..64]);
self.compress(&block);
data = &data[64..];
}
if !data.is_empty() {
self.buffer[..data.len()].copy_from_slice(data);
self.used = data.len();
}
}
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,
];
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,
];
let mut words = [0u32; 16];
for (i, chunk) in block.chunks_exact(4).enumerate() {
words[i] = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
}
let [mut a, mut b, mut c, mut d] = self.state;
for i in 0..64 {
let (f, g) = match i {
0..=15 => ((b & c) | ((!b) & d), i),
16..=31 => ((d & b) | ((!d) & c), (5 * i + 1) % 16),
32..=47 => (b ^ c ^ d, (3 * i + 5) % 16),
_ => (c ^ (b | (!d)), (7 * i) % 16),
};
let temp = d;
d = c;
c = b;
b = b.wrapping_add(
a.wrapping_add(f)
.wrapping_add(K[i])
.wrapping_add(words[g])
.rotate_left(S[i]),
);
a = temp;
}
self.state[0] = self.state[0].wrapping_add(a);
self.state[1] = self.state[1].wrapping_add(b);
self.state[2] = self.state[2].wrapping_add(c);
self.state[3] = self.state[3].wrapping_add(d);
}
fn finalize(mut self) -> [u8; 16] {
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
};
padding.extend(std::iter::repeat(0u8).take(pad_len));
padding.extend_from_slice(&bit_length.to_le_bytes());
let saved_length = self.length;
self.length = 0;
self.update(&padding);
self.length = saved_length;
let mut out = [0u8; 16];
for (i, word) in self.state.iter().enumerate() {
out[i * 4..i * 4 + 4].copy_from_slice(&word.to_le_bytes());
}
out
}
}
fn md5_hex(data: &[u8]) -> String {
let mut hasher = Md5::new();
hasher.update(data);
let digest = hasher.finalize();
let mut out = String::with_capacity(32);
for byte in digest {
out.push_str(&format!("{byte:02x}"));
}
out
}
fn padded_md5(data: &[u8], blocks: u64) -> String {
let mut hasher = Md5::new();
hasher.update(data);
let target = blocks * BLK;
let mut remaining = target.saturating_sub(data.len() as u64);
let pad = [0xffu8; 8192];
while remaining > 0 {
let take = remaining.min(pad.len() as u64) as usize;
hasher.update(&pad[..take]);
remaining -= take as u64;
}
let digest = hasher.finalize();
let mut out = String::with_capacity(32);
for byte in digest {
out.push_str(&format!("{byte:02x}"));
}
out
}
fn crc32(data: &[u8]) -> u32 {
let mut crc = 0xffff_ffffu32;
for byte in data {
crc ^= *byte as u32;
for _ in 0..8 {
if crc & 1 != 0 {
crc = (crc >> 1) ^ 0xedb8_8320;
} else {
crc >>= 1;
}
}
}
!crc
}
// ---------------------------------------------------------------- gzip / tar
fn gzip_store(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len() + data.len() / 65535 * 5 + 32);
out.extend_from_slice(&[0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0x00, 0xff]);
let mut position = 0;
loop {
let remaining = data.len() - position;
let take = remaining.min(65535);
let final_block = position + take == data.len();
out.push(if final_block { 1 } else { 0 });
let length = take as u16;
out.extend_from_slice(&length.to_le_bytes());
out.extend_from_slice(&(!length).to_le_bytes());
out.extend_from_slice(&data[position..position + take]);
position += take;
if final_block {
break;
}
}
out.extend_from_slice(&crc32(data).to_le_bytes());
out.extend_from_slice(&(data.len() as u32).to_le_bytes());
out
}
fn put_octal(field: &mut [u8], value: u64) {
let width = field.len() - 1;
let digits = format!("{:0width$o}", value, width = width);
let bytes = digits.as_bytes();
let take = bytes.len().min(width);
field[..width].fill(b'0');
field[width - take..width].copy_from_slice(&bytes[bytes.len() - take..]);
field[width] = 0;
}
fn tar_header(name: &str, mode: u32, size: u64, kind: u8, link: &str) -> [u8; 512] {
let mut header = [0u8; 512];
let name_bytes = name.as_bytes();
let count = name_bytes.len().min(100);
header[..count].copy_from_slice(&name_bytes[..count]);
put_octal(&mut header[100..108], mode as u64);
put_octal(&mut header[108..116], 0);
put_octal(&mut header[116..124], 0);
put_octal(&mut header[124..136], size);
put_octal(&mut header[136..148], 0);
header[148..156].fill(b' ');
header[156] = kind;
let link_bytes = link.as_bytes();
let link_count = link_bytes.len().min(100);
header[157..157 + link_count].copy_from_slice(&link_bytes[..link_count]);
header[257..263].copy_from_slice(b"ustar\0");
header[263..265].copy_from_slice(b"00");
let sum: u32 = header.iter().map(|byte| *byte as u32).sum();
let checksum = format!("{sum:06o}");
let checksum_bytes = checksum.as_bytes();
let checksum_count = checksum_bytes.len().min(6);
header[148..154].fill(b'0');
let start = 154 - checksum_count;
header[start..154].copy_from_slice(&checksum_bytes[checksum_bytes.len() - checksum_count..]);
header[154] = 0;
header[155] = b' ';
header
}
struct TarEntry {
name: String,
mode: u32,
kind: u8,
link: String,
data: Vec<u8>,
}
fn build_tar(entries: &[TarEntry]) -> Vec<u8> {
let mut out = Vec::new();
for entry in entries {
let size = if entry.kind == b'0' {
entry.data.len() as u64
} else {
0
};
let header = tar_header(&entry.name, entry.mode, size, entry.kind, &entry.link);
out.extend_from_slice(&header);
if entry.kind == b'0' {
out.extend_from_slice(&entry.data);
let padding = (512 - (entry.data.len() % 512)) % 512;
out.extend(std::iter::repeat(0u8).take(padding));
}
}
out.extend(std::iter::repeat(0u8).take(1024));
out
}
// ---------------------------------------------------------------- flash targets
struct Mtd {
device: String,
offset: u64,
size: u64,
}
struct FlashTarget {
name: &'static str,
file: &'static str,
device: String,
rel: u64,
absolute: u64,
slot: u64,
data: Cow<'static, [u8]>,
raw_md5: String,
padded_md5: String,
blocks: u64,
}
fn parse_number(value: &str) -> Option<u64> {
let value = value.trim();
if let Some(hex) = value.strip_prefix("0x") {
u64::from_str_radix(hex, 16).ok()
} else {
value.parse::<u64>().ok()
}
}
fn read_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockError> {
let script = "for d in /sys/class/mtd/mtd[0-9]*; do \
[ -e \"$d/name\" ] || continue; \
n=${d##*/}; \
printf '%s|%s|%s|%s\\n' \"$n\" \"$(cat $d/name 2>/dev/null)\" \
\"$(cat $d/offset 2>/dev/null)\" \"$(cat $d/size 2>/dev/null)\"; \
done";
let result = ssh_exec(host, password, script, Duration::from_secs(30))?;
if !result.ok() {
return Err(classify_ssh(&result));
}
let mut map = Vec::new();
for line in text(&result.stdout).lines() {
let mut parts = line.trim().split('|');
let name = match parts.next() {
Some(name) if name.starts_with("mtd") => name,
_ => continue,
};
if !name[3..].chars().all(|c| c.is_ascii_digit()) {
continue;
}
let _label = parts.next();
let offset = match parts.next().and_then(parse_number) {
Some(value) => value,
None => continue,
};
let size = match parts.next().and_then(parse_number) {
Some(value) => value,
None => continue,
};
map.push(Mtd {
device: format!("/dev/{name}"),
offset,
size,
});
}
if map.is_empty() {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
Ok(map)
}
fn map_covers_boot_regions(map: &[Mtd]) -> bool {
[ABS_DTB, ABS_KERNEL, ABS_ROOTFS]
.iter()
.all(|absolute| locate_mtd(map, *absolute).is_some())
}
fn apply_mtd_patch(host: &str, password: Option<&str>) -> Result<(), StockError> {
let mtd_patch = stock_asset(&ASSET_MTD_PATCH)?;
ssh_push(
host,
password,
"/tmp/.ak-mtdpatch",
&mtd_patch,
Duration::from_secs(60),
)?;
let result = ssh_exec(
host,
password,
"chmod +x /tmp/.ak-mtdpatch && /tmp/.ak-mtdpatch --write",
Duration::from_secs(120),
)?;
let _ = ssh_exec(
host,
password,
"rm -f /tmp/.ak-mtdpatch",
Duration::from_secs(15),
);
if !result.ok() {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
Ok(())
}
fn get_mtd_map(host: &str, password: Option<&str>) -> Result<Vec<Mtd>, StockError> {
let map = read_mtd_map(host, password)?;
if map_covers_boot_regions(&map) {
return Ok(map);
}
apply_mtd_patch(host, password)?;
let map = read_mtd_map(host, password)?;
if !map_covers_boot_regions(&map) {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
Ok(map)
}
/// Like `get_mtd_map`, but also requires `absolute` to be reachable. The
/// per-board storage helper re-registers the boot regions; on alkane that same
/// view includes the reserve area used for the on-board stock backup.
fn get_mtd_map_for_backup(
host: &str,
password: Option<&str>,
absolute: u64,
) -> Result<Vec<Mtd>, StockError> {
let map = read_mtd_map(host, password)?;
if map_covers_boot_regions(&map) && locate_mtd(&map, absolute).is_some() {
return Ok(map);
}
apply_mtd_patch(host, password)?;
let map = read_mtd_map(host, password)?;
if !map_covers_boot_regions(&map) || locate_mtd(&map, absolute).is_none() {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
Ok(map)
}
fn locate_mtd(map: &[Mtd], absolute: u64) -> Option<(&Mtd, u64)> {
for mtd in map {
if mtd.offset <= absolute && absolute < mtd.offset + mtd.size {
return Some((mtd, absolute - mtd.offset));
}
}
None
}
fn make_target(
name: &'static str,
file: &'static str,
device: String,
rel: u64,
absolute: u64,
slot: u64,
data: Cow<'static, [u8]>,
) -> Result<FlashTarget, StockError> {
if absolute < BOOTBIN_PRESERVE {
return Err(StockError::Method(
"refusing to write the boot region".into(),
));
}
if device == "/dev/mtd0" && rel < BOOTBIN_PRESERVE {
return Err(StockError::Method(
"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 rel % BLK != 0 || slot == 0 || slot % BLK != 0 {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
let blocks = (data.len() as u64).div_ceil(BLK);
if blocks == 0 || blocks * BLK > slot {
return Err(StockError::Method("image does not fit target slot".into()));
}
let raw_md5 = md5_hex(data.as_ref());
let padded_md5 = padded_md5(data.as_ref(), blocks);
Ok(FlashTarget {
name,
file,
device,
rel,
absolute,
slot,
data,
raw_md5,
padded_md5,
blocks,
})
}
fn targets_from_map(
map: &[Mtd],
images: Vec<(&'static str, &'static str, u64, u64, Cow<'static, [u8]>)>,
) -> Result<Vec<FlashTarget>, StockError> {
let mut targets = Vec::with_capacity(images.len());
for (name, file, absolute, slot, data) in images {
let (mtd, rel) = locate_mtd(map, absolute)
.ok_or_else(|| StockError::Method("target storage layout unsupported".into()))?;
if rel.checked_add(slot).map_or(true, |end| end > mtd.size) {
return Err(StockError::Method("image does not fit target slot".into()));
}
targets.push(make_target(
name,
file,
mtd.device.clone(),
rel,
absolute,
slot,
data,
)?);
}
Ok(targets)
}
fn stock_web_targets(
kernel: Vec<u8>,
dtb: Vec<u8>,
rootfs: Vec<u8>,
) -> Result<Vec<FlashTarget>, StockError> {
let images = vec![
(
"rootfs",
"afw-rootfs.uimg",
ABS_ROOTFS,
ROOTFS_SLOT,
Cow::Owned(rootfs),
),
("dtb", "afw-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)),
(
"kernel",
"afw-kernel.uimg",
ABS_KERNEL,
KERNEL_SLOT,
Cow::Owned(kernel),
),
];
let map = vec![
Mtd {
device: "/dev/mtd0".to_string(),
offset: 0,
size: 0x2800000,
},
Mtd {
device: "/dev/mtd1".to_string(),
offset: 0x2800000,
size: 0x2000000,
},
];
targets_from_map(&map, images)
}
// ---------------------------------------------------------------- scripts
// Runs as root inside the from-stock web helper, before any alkane image is
// written. It leaves the genuine stock boot chain in the reserve area and
// writes the manifest last. Any failure exits through `fail`, so the stock
// board is never touched unless the backup is complete.
const STOCK_BACKUP_WEB_SCRIPT: &str = r#"
ak_base=0x5200000
ak_end=0x6000000
ak_hdr=131072
ak_blk=131072
ak_src_dtb=0x1a00000
ak_src_kernel=0x2000000
ak_src_ramdisk=0x2800000
ak_num() {
printf '%d\n' "$(( $1 ))"
}
ak_mtd_for() {
ak_abs=$(ak_num "$1") || return 1
for ak_d in /sys/class/mtd/mtd[0-9]*; do
[ -e "$ak_d/offset" ] || continue
ak_off=$(cat "$ak_d/offset" 2>/dev/null) || continue
ak_siz=$(cat "$ak_d/size" 2>/dev/null) || continue
[ -n "$ak_off" ] && [ -n "$ak_siz" ] || continue
ak_off=$(ak_num "$ak_off") || continue
ak_siz=$(ak_num "$ak_siz") || continue
if [ "$ak_abs" -ge "$ak_off" ] && [ "$ak_abs" -lt "$((ak_off + ak_siz))" ]; then
ak_name=$(basename "$ak_d")
printf '%s %s %s\n' "/dev/$ak_name" "$((ak_abs - ak_off))" "$ak_off"
return 0
fi
done
return 1
}
ak_be32() {
set -- $(od -An -tx1 -j "$2" -N4 "$1" 2>/dev/null)
[ "$#" -eq 4 ] || return 1
printf '%d\n' "$(( (0x$1 << 24) | (0x$2 << 16) | (0x$3 << 8) | 0x$4 ))"
}
ak_uimage_len() {
ak_magic=$(dd if="$1" bs=1 count=4 2>/dev/null | od -An -tx1 | tr -d ' \n')
[ "$ak_magic" = "27051956" ] || return 1
ak_total=$((64 + $(ak_be32 "$1" 12))) || return 1
[ "$ak_total" -gt 64 ] || return 1
ak_bytes=$(( ((ak_total + ak_blk - 1) / ak_blk) * ak_blk ))
[ "$((ak_bytes <= $2))" -eq 1 ] || return 1
printf '%d\n' "$ak_bytes"
}
set -- $(ak_mtd_for "$ak_base")
[ "$#" -eq 3 ] || fail bk-map
ak_dev=$1
ak_bakrel=$2
ak_devoff=$3
set -- $(ak_mtd_for "$ak_src_dtb")
[ "$#" -eq 3 ] || fail bk-src-dtb
ak_srcrel=$2
[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-dtb
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-dtb 2>/dev/null || fail bk-read-dtb
[ "$(wc -c < /tmp/.ak-bk-dtb 2>/dev/null)" = "$ak_hdr" ] || fail bk-short-dtb
ak_dtb_md5=$(md5sum /tmp/.ak-bk-dtb | cut -d' ' -f1) || fail bk-md5-dtb
ak_dtb_size=$ak_hdr
set -- $(ak_mtd_for "$ak_src_kernel")
[ "$#" -eq 3 ] || fail bk-src-kernel
ak_srcrel=$2
[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-kernel
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-kernel-head 2>/dev/null || fail bk-read-kernel
ak_kernel_size=$(ak_uimage_len /tmp/.ak-bk-kernel-head 0x800000) || fail bk-kernel
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count="$((ak_kernel_size / ak_blk))" of=/tmp/.ak-bk-kernel 2>/dev/null || fail bk-read-kernel
[ "$(wc -c < /tmp/.ak-bk-kernel 2>/dev/null)" = "$ak_kernel_size" ] || fail bk-short-kernel
ak_kernel_md5=$(md5sum /tmp/.ak-bk-kernel | cut -d' ' -f1) || fail bk-md5-kernel
set -- $(ak_mtd_for "$ak_src_ramdisk")
[ "$#" -eq 3 ] || fail bk-src-ramdisk
ak_srcrel=$2
[ "$((ak_srcrel % ak_blk))" -eq 0 ] || fail bk-align-ramdisk
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count=1 of=/tmp/.ak-bk-ramdisk-head 2>/dev/null || fail bk-read-ramdisk
ak_ramdisk_size=$(ak_uimage_len /tmp/.ak-bk-ramdisk-head 0x2000000) || fail bk-ramdisk
dd if="$1" bs="$ak_blk" skip="$((ak_srcrel / ak_blk))" count="$((ak_ramdisk_size / ak_blk))" of=/tmp/.ak-bk-ramdisk 2>/dev/null || fail bk-read-ramdisk
[ "$(wc -c < /tmp/.ak-bk-ramdisk 2>/dev/null)" = "$ak_ramdisk_size" ] || fail bk-short-ramdisk
ak_ramdisk_md5=$(md5sum /tmp/.ak-bk-ramdisk | cut -d' ' -f1) || fail bk-md5-ramdisk
ak_dtb_bak=$((ak_base + ak_hdr))
ak_kernel_bak=$((ak_dtb_bak + ak_dtb_size))
ak_ramdisk_bak=$((ak_kernel_bak + ak_kernel_size))
ak_end_used=$((ak_ramdisk_bak + ak_ramdisk_size))
[ "$((ak_end_used <= ak_end))" -eq 1 ] || fail bk-space
set -- $(ak_mtd_for "$ak_dtb_bak")
[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split
set -- $(ak_mtd_for "$ak_kernel_bak")
[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split
set -- $(ak_mtd_for "$ak_ramdisk_bak")
[ "$#" -eq 3 ] && [ "$1" = "$ak_dev" ] || fail bk-split
ak_blocks=$(( (ak_end_used - ak_base) / ak_blk ))
flash_erase "$ak_dev" "$ak_bakrel" "$ak_blocks" >/dev/null 2>&1 || fail bk-erase
nandwrite -p -s "$((ak_dtb_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-dtb >/dev/null 2>&1 || fail bk-write-dtb
nandwrite -p -s "$((ak_kernel_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-kernel >/dev/null 2>&1 || fail bk-write-kernel
nandwrite -p -s "$((ak_ramdisk_bak - ak_devoff))" "$ak_dev" /tmp/.ak-bk-ramdisk >/dev/null 2>&1 || fail bk-write-ramdisk
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_dtb_bak - ak_devoff) / ak_blk ))" count="$((ak_dtb_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1)
[ "$ak_v" = "$ak_dtb_md5" ] || fail bk-verify-dtb
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_kernel_bak - ak_devoff) / ak_blk ))" count="$((ak_kernel_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1)
[ "$ak_v" = "$ak_kernel_md5" ] || fail bk-verify-kernel
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$(( (ak_ramdisk_bak - ak_devoff) / ak_blk ))" count="$((ak_ramdisk_size / ak_blk))" 2>/dev/null | md5sum | cut -d' ' -f1)
[ "$ak_v" = "$ak_ramdisk_md5" ] || fail bk-verify-ramdisk
{
printf '%s\n' "ALKANE-STOCK-BACKUP 1"
printf 'dtb 0x1a00000 0x%x 0x%x %s\n' "$ak_dtb_bak" "$ak_dtb_size" "$ak_dtb_md5"
printf 'kernel 0x2000000 0x%x 0x%x %s\n' "$ak_kernel_bak" "$ak_kernel_size" "$ak_kernel_md5"
printf 'ramdisk 0x2800000 0x%x 0x%x %s\n' "$ak_ramdisk_bak" "$ak_ramdisk_size" "$ak_ramdisk_md5"
printf '%s\n' "end"
} > /tmp/.ak-bk-header || fail bk-header
nandwrite -p -s "$ak_bakrel" "$ak_dev" /tmp/.ak-bk-header >/dev/null 2>&1 || fail bk-write-header
ak_v=$(dd if="$ak_dev" bs="$ak_blk" skip="$((ak_bakrel / ak_blk))" count=1 2>/dev/null | head -c 19)
[ "$ak_v" = "ALKANE-STOCK-BACKUP" ] || fail bk-verify-header
rm -f /tmp/.ak-bk-dtb /tmp/.ak-bk-kernel /tmp/.ak-bk-kernel-head \
/tmp/.ak-bk-ramdisk /tmp/.ak-bk-ramdisk-head /tmp/.ak-bk-header
"#;
fn flash_script(
targets: &[FlashTarget],
token: &str,
web_cgi: Option<&str>,
with_stock_backup: bool,
) -> String {
let mut script = String::new();
script.push_str("#!/bin/sh\n");
script.push_str("set -u\n");
if web_cgi.is_some() {
script.push_str("printf 'Content-type: text/plain\\r\\n\\r\\n'\n");
}
script.push_str("fail(){ echo \"@@FAIL@@ $*\"; sync; exit 1; }\n");
if with_stock_backup {
script.push_str(STOCK_BACKUP_WEB_SCRIPT);
}
for target in targets {
let path = if web_cgi.is_some() {
format!("/tmp/.ak-{token}-{}", target.file)
} else {
format!("/tmp/rs/{}", target.file)
};
script.push_str(&format!("echo \"### {}\"\n", target.name));
script.push_str(&format!("f={path}\n"));
script.push_str(&format!(
"m=$(md5sum \"$f\" | cut -d' ' -f1); [ \"$m\" = \"{}\" ] || fail md5-{}\n",
target.raw_md5, target.name
));
script.push_str(&format!(
"flash_erase {} 0x{:x} 0x{:x} >/dev/null 2>&1 || fail erase-{}\n",
target.device,
target.rel,
target.slot / BLK,
target.name
));
script.push_str(&format!(
"nandwrite -p -s 0x{:x} {} \"$f\" >/dev/null 2>&1 || fail write-{}\n",
target.rel, target.device, target.name
));
script.push_str(&format!(
"v=$(dd if={} bs={} skip={} count={} 2>/dev/null | md5sum | cut -d' ' -f1)\n",
target.device,
BLK,
target.rel / BLK,
target.blocks
));
script.push_str(&format!(
"[ \"$v\" = \"{}\" ] || fail verify-{}-$v\n",
target.padded_md5, target.name
));
script.push_str(&format!("echo \"### {} ok\"\n", target.name));
}
if let Some(cgi) = web_cgi {
script.push_str("sync\n");
script.push_str("echo \"@@OK@@\"\n");
script.push_str(&format!("rm -f /www/pages/cgi-bin/{cgi}\n"));
script.push_str(&format!("rm -f /tmp/.ak-{token}-*\n"));
script.push_str("sync\n");
script.push_str(
"( sleep 2; sync; (echo b > /proc/sysrq-trigger) 2>/dev/null || reboot -f ) \
>/dev/null 2>&1 &\n",
);
} else {
script.push_str("sync\n");
script.push_str("echo \"@@OK@@\"\n");
}
script
}
fn web_base_entries() -> Vec<TarEntry> {
vec![
TarEntry {
name: "d".to_string(),
mode: 0o777,
kind: b'2',
link: "/tmp".to_string(),
data: Vec::new(),
},
TarEntry {
name: "p".to_string(),
mode: 0o777,
kind: b'2',
link: "/www/pages/cgi-bin".to_string(),
data: Vec::new(),
},
]
}
fn build_web_body(
targets: &[FlashTarget],
token: &str,
cgi: &str,
script: &str,
) -> (Vec<u8>, String) {
let mut entries = web_base_entries();
for target in targets {
entries.push(TarEntry {
name: format!("d/.ak-{token}-{}", target.file),
mode: 0o644,
kind: b'0',
link: String::new(),
data: target.data.as_ref().to_vec(),
});
}
entries.push(TarEntry {
name: format!("p/{cgi}"),
mode: 0o755,
kind: b'0',
link: String::new(),
data: script.as_bytes().to_vec(),
});
build_web_body_entries(entries)
}
fn build_web_body_entries(entries: Vec<TarEntry>) -> (Vec<u8>, String) {
let tar = build_tar(&entries);
let gz = gzip_store(&tar);
let boundary = format!("----alkane{}", random_token());
let mut body = Vec::with_capacity(gz.len() + 512);
body.extend_from_slice(
format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"file1\"; \
filename=\"image.tar.gz\"\r\nContent-Type: application/octet-stream\r\n\r\n"
)
.as_bytes(),
);
body.extend_from_slice(&gz);
body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
(body, boundary)
}
// ---------------------------------------------------------------- on-board stock backup
//
// A from-stock install copies the genuine stock device tree, kernel and ramdisk
// off their slots into the vendor `reserve` area before anything is overwritten.
// The copy is block-padded, carries a small text manifest with a digest for each
// member, and is written manifest-last so an interrupted install never leaves a
// backup that passes the presence check. Ownership/format stay inside this
// module; the public interface only reports complete/absent and restores.
#[derive(Clone, Debug)]
struct StockBackupEntry {
name: &'static str,
target_abs: u64,
backup_abs: u64,
size: u64,
md5: String,
}
#[derive(Clone, Debug)]
struct StockBackup {
entries: Vec<StockBackupEntry>,
}
fn parse_hex_u64(value: &str) -> Option<u64> {
let digits = value
.strip_prefix("0x")
.or_else(|| value.strip_prefix("0X"))?;
u64::from_str_radix(digits, 16).ok()
}
fn stock_entry_spec(name: &str) -> Option<(&'static str, u64, u64)> {
match name {
"dtb" => Some(("dtb", ABS_DTB, DTB_SLOT)),
"kernel" => Some(("kernel", ABS_KERNEL, KERNEL_SLOT)),
"ramdisk" => Some(("ramdisk", ABS_ROOTFS, ROOTFS_SLOT)),
_ => None,
}
}
fn parse_stock_backup(header: &[u8]) -> Option<StockBackup> {
let text = String::from_utf8_lossy(header);
let mut lines = text.lines();
let first = lines.next()?.trim_matches('\0').trim();
if first != STOCK_BACKUP_MAGIC {
return None;
}
let mut entries = Vec::new();
let mut ended = false;
for raw in lines {
let line = raw.trim_matches('\0').trim();
if line.is_empty() {
continue;
}
if line == "end" {
ended = true;
break;
}
let fields: Vec<&str> = line.split_whitespace().collect();
if fields.len() != 5 {
return None;
}
let (name, target_abs, slot) = stock_entry_spec(fields[0])?;
let declared_target = parse_hex_u64(fields[1])?;
let backup_abs = parse_hex_u64(fields[2])?;
let size = parse_hex_u64(fields[3])?;
let md5 = fields[4].to_ascii_lowercase();
if declared_target != target_abs
|| md5.len() != 32
|| !md5.chars().all(|c| c.is_ascii_hexdigit())
{
return None;
}
if size == 0 || size % BLK != 0 || size > slot || (name == "dtb" && size != DTB_SLOT) {
return None;
}
let backup_end = backup_abs.checked_add(size)?;
if backup_abs % BLK != 0
|| backup_abs < STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER
|| backup_end > STOCK_BACKUP_END
{
return None;
}
if entries
.iter()
.any(|entry: &StockBackupEntry| entry.name == name)
{
return None;
}
entries.push(StockBackupEntry {
name,
target_abs,
backup_abs,
size,
md5,
});
}
if !ended || entries.len() != 3 {
return None;
}
let mut spans: Vec<(u64, u64)> = entries
.iter()
.map(|entry| (entry.backup_abs, entry.backup_abs + entry.size))
.collect();
spans.sort_unstable();
for pair in spans.windows(2) {
if pair[0].1 > pair[1].0 {
return None;
}
}
Some(StockBackup { entries })
}
fn render_stock_backup(entries: &[StockBackupEntry]) -> Vec<u8> {
let mut text = String::new();
text.push_str(STOCK_BACKUP_MAGIC);
text.push('\n');
for entry in entries {
text.push_str(&format!(
"{} 0x{:x} 0x{:x} 0x{:x} {}\n",
entry.name, entry.target_abs, entry.backup_abs, entry.size, entry.md5
));
}
text.push_str("end\n");
text.into_bytes()
}
fn read_mtd_span(
host: &str,
password: Option<&str>,
map: &[Mtd],
absolute: u64,
size: u64,
label: &str,
) -> Result<Vec<u8>, StockError> {
if size == 0 || size % BLK != 0 {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
let (mtd, rel) = locate_mtd(map, absolute)
.ok_or_else(|| StockError::Method("target storage layout unsupported".into()))?;
if rel.checked_add(size).map_or(true, |end| end > mtd.size) {
return Err(StockError::Method(
"target storage layout unsupported".into(),
));
}
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null",
mtd.device,
BLK,
rel / BLK,
size / BLK
);
let result = ssh_exec(host, password, &remote, Duration::from_secs(600))?;
if !result.ok() {
return Err(StockError::Method(format!(
"could not read the on-board stock {label} backup"
)));
}
if result.stdout.len() as u64 != size {
return Err(StockError::Method(format!(
"the on-board stock {label} backup is short"
)));
}
Ok(result.stdout)
}
fn stock_uimage_span(
host: &str,
password: Option<&str>,
map: &[Mtd],
absolute: u64,
slot: u64,
label: &str,
) -> Result<Vec<u8>, StockError> {
let first = read_mtd_span(host, password, map, absolute, BLK, label)?;
if first.len() < 64 || first[..4] != [0x27, 0x05, 0x19, 0x56] {
return Err(StockError::Method(format!(
"the on-board stock {label} slot does not hold a stock image"
)));
}
let payload = u32::from_be_bytes([first[12], first[13], first[14], first[15]]) as u64;
let total = 64u64
.checked_add(payload)
.ok_or_else(|| StockError::Method(format!("the on-board stock {label} slot is invalid")))?;
let bytes = total.div_ceil(BLK) * BLK;
if total <= 64 || bytes > slot {
return Err(StockError::Method(format!(
"the on-board stock {label} slot does not hold a stock image"
)));
}
if bytes <= BLK {
return Ok(first[..bytes as usize].to_vec());
}
let rest = read_mtd_span(host, password, map, absolute + BLK, bytes - BLK, label)?;
let mut out = first;
out.extend_from_slice(&rest);
out.truncate(bytes as usize);
Ok(out)
}
fn read_validated_onboard_stock_backup(
host: &str,
password: Option<&str>,
map: &[Mtd],
) -> Result<Option<StockBackup>, StockError> {
let Some((mtd, rel)) = locate_mtd(map, STOCK_BACKUP_BASE) else {
return Ok(None);
};
if rel
.checked_add(STOCK_BACKUP_HEADER)
.map_or(true, |end| end > mtd.size)
{
return Ok(None);
}
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null",
mtd.device,
BLK,
rel / BLK,
STOCK_BACKUP_HEADER / BLK
);
let header = ssh_exec(host, password, &remote, Duration::from_secs(120))?;
if !header.ok() || header.stdout.len() as u64 != STOCK_BACKUP_HEADER {
return Ok(None);
}
let Some(backup) = parse_stock_backup(&header.stdout) else {
return Ok(None);
};
for entry in &backup.entries {
let Some((entry_mtd, entry_rel)) = locate_mtd(map, entry.backup_abs) else {
return Ok(None);
};
if entry_rel
.checked_add(entry.size)
.map_or(true, |end| end > entry_mtd.size)
{
return Ok(None);
}
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null | md5sum | cut -d' ' -f1",
entry_mtd.device,
BLK,
entry_rel / BLK,
entry.size / BLK
);
let result = ssh_exec(host, password, &remote, Duration::from_secs(300))?;
if !result.ok() {
return Ok(None);
}
if !text(&result.stdout).trim().eq_ignore_ascii_case(&entry.md5) {
return Ok(None);
}
}
Ok(Some(backup))
}
fn create_onboard_stock_backup(
host: &str,
password: Option<&str>,
map: &[Mtd],
) -> Result<(), StockError> {
let dtb = read_mtd_span(host, password, map, ABS_DTB, DTB_SLOT, "device tree")?;
if dtb.len() < 8 || dtb[..4] != [0xd0, 0x0d, 0xfe, 0xed] {
return Err(StockError::Method(
"the stock device tree slot is not usable for a backup".into(),
));
}
let kernel = stock_uimage_span(host, password, map, ABS_KERNEL, KERNEL_SLOT, "kernel")?;
let ramdisk = stock_uimage_span(host, password, map, ABS_ROOTFS, ROOTFS_SLOT, "ramdisk")?;
let mut prepared: Vec<(&'static str, u64, Vec<u8>)> = vec![
("dtb", ABS_DTB, dtb),
("kernel", ABS_KERNEL, kernel),
("ramdisk", ABS_ROOTFS, ramdisk),
];
let mut entries = Vec::with_capacity(prepared.len());
let mut next = STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER;
for (name, target_abs, data) in &prepared {
let size = data.len() as u64;
if next
.checked_add(size)
.map_or(true, |end| end > STOCK_BACKUP_END)
{
return Err(StockError::Method(
"the on-board stock backup area is too small".into(),
));
}
entries.push(StockBackupEntry {
name,
target_abs: *target_abs,
backup_abs: next,
size,
md5: md5_hex(data),
});
next += size;
}
let header = render_stock_backup(&entries);
let mut write: Vec<(&'static str, &'static str, u64, u64, Cow<'static, [u8]>)> = Vec::new();
write.push((
"backup-header-clear",
"stock-backup-empty.bin",
STOCK_BACKUP_BASE,
STOCK_BACKUP_HEADER,
Cow::Owned(vec![0u8; STOCK_BACKUP_HEADER as usize]),
));
for (entry, (_, _, data)) in entries.iter().zip(prepared.drain(..)) {
write.push((
match entry.name {
"dtb" => "backup-dtb",
"kernel" => "backup-kernel",
_ => "backup-ramdisk",
},
match entry.name {
"dtb" => "stock-backup.dtb",
"kernel" => "stock-backup-kernel.uimg",
_ => "stock-backup-ramdisk.uimg",
},
entry.backup_abs,
entry.size,
Cow::Owned(data),
));
}
write.push((
"backup-header",
"stock-backup.txt",
STOCK_BACKUP_BASE,
STOCK_BACKUP_HEADER,
Cow::Owned(header),
));
let targets = targets_from_map(map, write)?;
flash_via_ssh(host, password, &targets)?;
match read_validated_onboard_stock_backup(host, password, map)? {
Some(_) => Ok(()),
None => Err(StockError::Method(
"the on-board stock backup did not verify after it was written".into(),
)),
}
}
fn restore_from_onboard_backup_impl(
host: &str,
password: Option<&str>,
timeout: Duration,
) -> Result<(), StockError> {
validate_host(host)?;
if !ssh_port_open(host) {
if is_stock_http(host) {
return Ok(());
}
return Err(StockError::Network("target unreachable".into()));
}
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
let state = board_state(host, password)?;
if state == "stock" {
return Ok(());
}
let map = get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?;
let Some(backup) = read_validated_onboard_stock_backup(host, password, &map)? else {
return Err(StockError::Method(
"no complete on-board stock backup".into(),
));
};
let name = |wanted: &str| -> Result<&StockBackupEntry, StockError> {
backup
.entries
.iter()
.find(|entry| entry.name == wanted)
.ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))
};
let dtb_entry = name("dtb")?;
let kernel_entry = name("kernel")?;
let ramdisk_entry = name("ramdisk")?;
let dtb = read_mtd_span(
host,
password,
&map,
dtb_entry.backup_abs,
dtb_entry.size,
"device tree",
)?;
let kernel = read_mtd_span(
host,
password,
&map,
kernel_entry.backup_abs,
kernel_entry.size,
"kernel",
)?;
let ramdisk = read_mtd_span(
host,
password,
&map,
ramdisk_entry.backup_abs,
ramdisk_entry.size,
"ramdisk",
)?;
let write = vec![
(
"ramdisk",
"stock-rootfs.uimg",
ABS_ROOTFS,
ROOTFS_SLOT,
Cow::Owned(ramdisk),
),
("dtb", "stock-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)),
(
"kernel",
"stock-kernel.uimg",
ABS_KERNEL,
KERNEL_SLOT,
Cow::Owned(kernel),
),
];
let targets = targets_from_map(&map, write)?;
flash_via_ssh(host, password, &targets)?;
reboot_target(host, password);
let _ = wait_stock(host, timeout);
Ok(())
}
fn onboard_stock_backup_present_impl(
host: &str,
password: Option<&str>,
) -> Result<bool, StockError> {
validate_host(host)?;
if !ssh_port_open(host) {
if is_stock_http(host) {
return Ok(false);
}
return Err(StockError::Network("target unreachable".into()));
}
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
let map = get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?;
Ok(read_validated_onboard_stock_backup(host, password, &map)?.is_some())
}
// ---------------------------------------------------------------- install / restore
fn choose_web_password(
host: &str,
password: Option<&str>,
dir: &Path,
tag: &str,
) -> Result<String, StockError> {
let candidates = web_password_candidates(password);
let mut last_auth = false;
for (index, candidate) in candidates.iter().enumerate() {
match stock_web_auth(host, candidate, dir, &format!("{tag}{index}")) {
Ok(()) => return Ok(candidate.clone()),
Err(StockError::Auth(_)) => {
last_auth = true;
continue;
}
Err(e) => return Err(e),
}
}
if last_auth {
Err(StockError::Auth("target rejected the credential".into()))
} else {
Err(StockError::Network("target unreachable".into()))
}
}
fn install_via_web(
host: &str,
password: Option<&str>,
kernel: Vec<u8>,
dtb: Vec<u8>,
rootfs: Vec<u8>,
) -> Result<(), StockError> {
let dir = TempDir::new("web")?;
let password = choose_web_password(host, password, dir.path(), "probe")?;
let targets = stock_web_targets(kernel, dtb, rootfs)?;
let token = random_token();
let cgi = format!("zz{token}.cgi");
let script = flash_script(&targets, &token, Some(&cgi), true);
let (body, boundary) = build_web_body(&targets, &token, &cgi, &script);
let body_path = dir.join("upload.body");
write_private(&body_path, &body)?;
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@@") {
return Err(StockError::Method("write failed".into()));
}
if wait_alkane(host, Duration::from_secs(240)) {
Ok(())
} else {
Err(StockError::Method("target did not return".into()))
}
}
// ---------------------------------------------------------------- root primitives
//
// These stay sealed inside this module. The public interface in `stock.rs`
// describes only the operation and its result; nothing here is part of it.
fn root_exec_via_ssh(host: &str, password: Option<&str>, cmd: &str) -> Result<String, StockError> {
let remote = format!("sh -c {}", shell_quote(cmd));
let result = ssh_exec(host, password, &remote, Duration::from_secs(3600))?;
if result.ok() {
Ok(command_output(&result))
} else {
Err(command_failure(&result))
}
}
fn root_exec_via_web(host: &str, password: Option<&str>, cmd: &str) -> Result<String, StockError> {
let dir = TempDir::new("root")?;
let password = choose_web_password(host, password, dir.path(), "root")?;
let token = random_token();
let cgi = format!("zz{token}.cgi");
let marker = format!("@@AKEXIT{token}@@");
let script = format!(
"#!/bin/sh\n\
printf 'Content-type: text/plain\\r\\n\\r\\n'\n\
trap 'rm -f /www/pages/cgi-bin/{cgi}' EXIT\n\
sh -c {quoted} 2>&1\n\
ak_code=$?\n\
printf '{marker}%d\\n' \"$ak_code\"\n",
cgi = cgi,
quoted = shell_quote(cmd),
marker = marker,
);
let mut entries = web_base_entries();
entries.push(TarEntry {
name: format!("p/{cgi}"),
mode: 0o755,
kind: b'0',
link: String::new(),
data: script.into_bytes(),
});
let (body, boundary) = build_web_body_entries(entries);
let body_path = dir.join("upload.body");
write_private(&body_path, &body)?;
stock_web_upload_with_timeout(
host,
&password,
dir.path(),
&body_path,
&boundary,
&token,
1800,
)?;
let trigger = stock_web_trigger_with_timeout(host, &password, dir.path(), &cgi, &token, 3600)?;
let output = text(&trigger.stdout);
if let Some(index) = output.rfind(&marker) {
let command_output = &output[..index];
let status = output[index + marker.len()..]
.trim()
.parse::<i32>()
.unwrap_or(-1);
if status == 0 {
return Ok(command_output.to_string());
}
return Err(command_exit_error(status, command_output.to_string()));
}
if trigger.timed_out {
return Err(StockError::Network("target did not respond".into()));
}
if !trigger.ok() {
return Err(StockError::Network("target unreachable".into()));
}
Err(StockError::Method("command channel did not respond".into()))
}
fn root_put_via_ssh(
host: &str,
password: Option<&str>,
data: &[u8],
remote_path: &str,
) -> Result<(), StockError> {
let dir = TempDir::new("put")?;
let payload = dir.join("payload");
write_private(&payload, data)?;
let parent = remote_parent(remote_path);
let prep = ssh_exec(
host,
password,
&format!("mkdir -p {}", shell_quote(parent)),
Duration::from_secs(60),
)?;
if !prep.ok() {
return Err(command_failure(&prep));
}
let token = random_token();
let temp_path = format!("{remote_path}.ak-tmp-{token}");
let remote = format!("cat > {}", shell_quote(&temp_path));
let input = fs::File::open(&payload)
.map_err(|e| StockError::Io(format!("could not read the payload: {e}")))?;
let result = run_command_stream(
ssh_command(host, password, &remote),
Duration::from_secs(1800),
input,
)?;
if result.timed_out {
let _ = ssh_exec(
host,
password,
&format!("rm -f {}", shell_quote(&temp_path)),
Duration::from_secs(15),
);
return Err(StockError::Network("target transfer timed out".into()));
}
if !result.ok() {
let _ = ssh_exec(
host,
password,
&format!("rm -f {}", shell_quote(&temp_path)),
Duration::from_secs(15),
);
return Err(command_failure(&result));
}
let finalize = format!(
"chmod 0644 {temp} && mv -f {temp} {path}",
temp = shell_quote(&temp_path),
path = shell_quote(remote_path),
);
let result = ssh_exec(host, password, &finalize, Duration::from_secs(60))?;
if !result.ok() {
let _ = ssh_exec(
host,
password,
&format!("rm -f {}", shell_quote(&temp_path)),
Duration::from_secs(15),
);
return Err(command_failure(&result));
}
Ok(())
}
fn root_put_via_web(
host: &str,
password: Option<&str>,
data: &[u8],
remote_path: &str,
) -> Result<(), StockError> {
let dir = TempDir::new("put")?;
let password = choose_web_password(host, password, dir.path(), "put")?;
let token = random_token();
let cgi = format!("zz{token}.cgi");
let marker = format!("@@AKPUT{token}@@");
let staged = format!("/tmp/.ak-put-{token}");
let temp_path = format!("{remote_path}.ak-tmp-{token}");
let parent = remote_parent(remote_path);
let script = format!(
"#!/bin/sh\n\
f={staged}\n\
t={temp}\n\
trap 'rm -f \"$f\" \"$t\" /www/pages/cgi-bin/{cgi}' EXIT\n\
mkdir -p {parent} || {{ printf '{marker}fail\\n'; exit 1; }}\n\
cp \"$f\" \"$t\" || {{ printf '{marker}fail\\n'; exit 1; }}\n\
chmod 0644 \"$t\" || {{ printf '{marker}fail\\n'; exit 1; }}\n\
mv -f \"$t\" {path} || {{ printf '{marker}fail\\n'; exit 1; }}\n\
printf '{marker}ok\\n'\n",
staged = shell_quote(&staged),
temp = shell_quote(&temp_path),
cgi = cgi,
parent = shell_quote(parent),
marker = marker,
path = shell_quote(remote_path),
);
let mut entries = web_base_entries();
entries.push(TarEntry {
name: format!("d/.ak-put-{token}"),
mode: 0o600,
kind: b'0',
link: String::new(),
data: data.to_vec(),
});
entries.push(TarEntry {
name: format!("p/{cgi}"),
mode: 0o755,
kind: b'0',
link: String::new(),
data: script.into_bytes(),
});
let (body, boundary) = build_web_body_entries(entries);
let body_path = dir.join("upload.body");
write_private(&body_path, &body)?;
stock_web_upload_with_timeout(
host,
&password,
dir.path(),
&body_path,
&boundary,
&token,
1800,
)?;
let trigger = stock_web_trigger_with_timeout(host, &password, dir.path(), &cgi, &token, 1800)?;
let output = text(&trigger.stdout);
if output.contains(&format!("{marker}ok")) {
return Ok(());
}
if output.contains(&format!("{marker}fail")) {
return Err(StockError::Method("could not write the remote file".into()));
}
if trigger.timed_out {
return Err(StockError::Network("target did not respond".into()));
}
if !trigger.ok() {
return Err(StockError::Network("target unreachable".into()));
}
Err(StockError::Method("command channel did not respond".into()))
}
// ---------------------------------------------------------------- stock daemon channel
//
// On this board class the stock image has no privileged login at all: root's
// shell is disabled, the SSH daemon refuses root logins, and the only account
// that logs in is unprivileged with no sudo. The vendor keeps every privileged
// operation (firmware updates, reboots, config writes) behind a root-owned
// helper that its own web layer talks to over loopback; that helper accepts a
// command line from a local client and runs it through a shell as root.
//
// This route therefore needs no exploit of its own: it logs in with the stock
// account, stages a short script under /tmp, hands the script to the vendor
// helper through the helper's own installed client, and reads the result back.
// Only /tmp is written; the stock system, the boot chain and the NAND layout
// are never touched. The alternative route (the web upload) is left in place
// for boards where it does work.
const STOCK_UNPRIV_USER_DEFAULT: &str = "miner";
const STOCK_UNPRIV_PASSWORD_DEFAULT: &str = "miner";
const STOCK_DAEMON_CLIENT: &str = "/usr/sbin/daemonc";
const STOCK_CHANNEL_READY: &str = "__ALKANE_STOCK_CHANNEL_READY__";
const STOCK_CHANNEL_ABSENT: &str = "__ALKANE_STOCK_CHANNEL_ABSENT__";
const STOCK_RUN_MARK: &str = "@@AKRUN";
/// The stock account this board class allows over SSH. Overridable so an
/// operator whose board was provisioned differently does not need a new build.
fn stock_unpriv_user() -> String {
env::var("ALKANE_STOCK_LOGIN_USER")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| is_plain_user(value))
.unwrap_or_else(|| STOCK_UNPRIV_USER_DEFAULT.to_string())
}
fn is_plain_user(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 32
&& value
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
}
/// Passwords to try for the unprivileged stock account, in order: the one the
/// caller supplied, then any from the environment, then the documented vendor
/// default for that account on this board class.
fn stock_unpriv_passwords(password: Option<&str>) -> Vec<String> {
let mut candidates = Vec::new();
let mut push = |value: &str| {
if !value.is_empty() && !candidates.iter().any(|known| known == value) {
candidates.push(value.to_string());
}
};
if let Some(password) = password {
push(password);
}
if let Ok(value) = env::var("ALKANE_STOCK_LOGIN_PASSWORD") {
push(&value);
}
if let Some(value) = resolve_password(None) {
push(&value);
}
push(STOCK_UNPRIV_PASSWORD_DEFAULT);
candidates
}
enum ChannelProbe {
Ready { uid: String },
Absent,
Denied,
Failed(StockError),
}
/// Stage `script` at `remote_script` and report whether the vendor helper is
/// present on this board and the login was accepted.
fn probe_stock_channel(
host: &str,
user: &str,
password: &str,
script: &str,
remote_script: &str,
) -> Result<ChannelProbe, StockError> {
let remote = format!(
"if [ ! -x {client} ]; then echo {absent}; exit 9; fi; \
cat > {path} && chmod 0644 {path} || exit 8; \
id -u; echo {ready}",
client = shell_quote(STOCK_DAEMON_CLIENT),
absent = STOCK_CHANNEL_ABSENT,
path = shell_quote(remote_script),
ready = STOCK_CHANNEL_READY,
);
let result = run_command(
ssh_command_as(host, user, Some(password), &remote),
Duration::from_secs(60),
Some(script.as_bytes().to_vec()),
)?;
let stdout = text(&result.stdout);
if result.ok() && stdout.contains(STOCK_CHANNEL_READY) {
let uid = stdout
.lines()
.find(|line| line.trim().parse::<u32>().is_ok())
.map(|line| line.trim().to_string())
.ok_or_else(|| StockError::Method("command channel did not respond".into()))?;
return Ok(ChannelProbe::Ready { uid });
}
if stdout.contains(STOCK_CHANNEL_ABSENT) {
return Ok(ChannelProbe::Absent);
}
if is_login_refused(&result) {
return Ok(ChannelProbe::Denied);
}
if result.timed_out {
return Err(StockError::Network("target did not respond".into()));
}
Ok(ChannelProbe::Failed(command_failure(&result)))
}
/// Run `script` as root through the stock daemon channel and return its
/// combined output. `Ok(NotApplicable)` means this is not a board with that
/// channel, so the caller should use another route.
fn stock_channel_run(
host: &str,
password: Option<&str>,
script: &str,
) -> Result<String, StockError> {
let user = stock_unpriv_user();
let token = random_token();
let remote_script = format!("/tmp/.ak-cmd-{token}");
let remote_out = format!("/tmp/.ak-out-{token}");
let remote_missing = format!("/tmp/.ak-none-{token}");
let mut denied = false;
for candidate in stock_unpriv_passwords(password) {
match probe_stock_channel(host, &user, &candidate, script, &remote_script)? {
ChannelProbe::Ready { uid } => {
return stock_channel_execute(
host,
&user,
&candidate,
&uid,
&token,
&remote_script,
&remote_out,
&remote_missing,
)
}
ChannelProbe::Absent => return Err(StockError::NotApplicable),
ChannelProbe::Denied => {
denied = true;
continue;
}
ChannelProbe::Failed(error) => return Err(error),
}
}
if denied {
Err(StockError::Auth("target rejected the credential".into()))
} else {
Err(StockError::NotApplicable)
}
}
/// Hand the staged script to the vendor helper. The helper is given a path
/// that does not exist first, so the vendor's own handler runs and exits
/// before anything of ours does; the script then runs as root, its output is
/// written to a private file that is handed back to the stock account, and
/// every staged file is removed again by the root side.
fn stock_channel_execute(
host: &str,
user: &str,
password: &str,
uid: &str,
token: &str,
remote_script: &str,
remote_out: &str,
remote_missing: &str,
) -> Result<String, StockError> {
let mark = format!("{STOCK_RUN_MARK}{token}=");
let inject = format!(
"{missing}; sh {script} > {out} 2>&1; \
echo \"{mark}$?\" >> {out}; \
chmod 0644 {out} && chown {uid} {out}; \
rm -f {script}",
missing = shell_quote(remote_missing),
script = shell_quote(remote_script),
out = shell_quote(remote_out),
mark = mark,
uid = shell_quote(uid),
);
let remote = format!(
"{} {}",
shell_quote(STOCK_DAEMON_CLIENT),
shell_quote(&inject)
);
let run = ssh_exec_as(
host,
user,
Some(password),
&remote,
Duration::from_secs(3600),
);
// Collect whatever the root side left, even when the call above failed or
// timed out, so the temporary files are removed either way.
let collect = format!(
"cat {out}; rm -f {out} {script}",
out = shell_quote(remote_out),
script = shell_quote(remote_script),
);
let read = ssh_exec_as(
host,
user,
Some(password),
&collect,
Duration::from_secs(120),
);
if let Ok(read) = &read {
if let Some((body, status)) = split_run_result(&text(&read.stdout), &mark) {
if status == 0 {
return Ok(body);
}
return Err(command_exit_error(status, body));
}
}
if let Err(error) = run {
return Err(error);
}
if let Err(error) = read {
return Err(error);
}
Err(StockError::Method("command channel did not respond".into()))
}
/// Split the collected file into the command output and the exit status the
/// root side appended after it. The status marker carries this call's token so
/// a command cannot forge it, and it is appended straight after the command's
/// last byte, so a command whose output has no trailing newline still parses.
fn split_run_result(output: &str, mark: &str) -> Option<(String, i32)> {
let index = output.rfind(mark)?;
let body = output[..index].to_string();
let rest = &output[index + mark.len()..];
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
let status = digits.parse::<i32>().ok()?;
Some((body, status))
}
fn stock_root_exec(host: &str, password: Option<&str>, cmd: &str) -> Result<String, StockError> {
if cmd.trim().is_empty() {
return Err(StockError::Method("empty command".into()));
}
let script = format!("#!/bin/sh\n{cmd}\n");
stock_channel_run(host, password, &script)
}
fn stock_root_put(
host: &str,
password: Option<&str>,
data: &[u8],
remote_path: &str,
) -> Result<(), StockError> {
let user = stock_unpriv_user();
let token = random_token();
let staged = format!("/tmp/.ak-put-{token}");
let scratch = format!("{remote_path}.ak-tmp-{token}");
let password = stage_stock_payload(host, &user, password, data, &staged)?;
if let Err(error) = verify_stock_payload(host, &user, &password, data.len(), &staged) {
let _ = ssh_exec_as(
host,
&user,
Some(&password),
&format!("rm -f {}", shell_quote(&staged)),
Duration::from_secs(30),
);
return Err(error);
}
let script = format!(
"#!/bin/sh\n\
src={src}\n\
dst={dst}\n\
tmp={tmp}\n\
dir={dir}\n\
mkdir -p \"$dir\" || {{ echo \"could not create the remote directory\"; exit 11; }}\n\
cp \"$src\" \"$tmp\" || {{ rm -f \"$tmp\"; echo \"could not copy the staged file\"; exit 12; }}\n\
chmod 0644 \"$tmp\" || {{ rm -f \"$tmp\"; echo \"could not set the file mode\"; exit 13; }}\n\
mv -f \"$tmp\" \"$dst\" || {{ rm -f \"$tmp\"; echo \"could not move the file into place\"; exit 14; }}\n\
n=$(wc -c < \"$dst\" 2>/dev/null)\n\
[ \"$n\" = {size} ] || {{ echo \"the written file is $n bytes, not {size}\"; exit 15; }}\n\
rm -f \"$src\"\n\
exit 0\n",
src = shell_quote(&staged),
dst = shell_quote(remote_path),
tmp = shell_quote(&scratch),
dir = shell_quote(remote_parent(remote_path)),
size = shell_quote(&data.len().to_string()),
);
let result = stock_channel_run(host, Some(&password), &script);
if result.is_err() {
// The staged copy belongs to the stock account, so it can always be
// removed even when the root side never ran.
let _ = ssh_exec_as(
host,
&user,
Some(&password),
&format!("rm -f {} {}", shell_quote(&staged), shell_quote(&scratch)),
Duration::from_secs(30),
);
}
result.map(|_| ())
}
/// Stream the payload to a temporary file owned by the stock account and
/// return the password that account accepted.
fn stage_stock_payload(
host: &str,
user: &str,
password: Option<&str>,
data: &[u8],
staged: &str,
) -> Result<String, StockError> {
let dir = TempDir::new("stockput")?;
let payload = dir.join("payload");
write_private(&payload, data)?;
for candidate in stock_unpriv_passwords(password) {
let remote = format!(
"cat > {path} && chmod 0644 {path}",
path = shell_quote(staged)
);
let input = fs::File::open(&payload)
.map_err(|e| StockError::Io(format!("could not read the payload: {e}")))?;
let result = run_command_stream(
ssh_command_as(host, user, Some(&candidate), &remote),
Duration::from_secs(1800),
input,
)?;
if result.ok() {
return Ok(candidate);
}
if result.timed_out {
return Err(StockError::Network("target transfer timed out".into()));
}
if is_login_refused(&result) {
continue;
}
return Err(command_failure(&result));
}
Err(StockError::Auth("target rejected the credential".into()))
}
fn verify_stock_payload(
host: &str,
user: &str,
password: &str,
size: usize,
staged: &str,
) -> Result<(), StockError> {
let remote = format!("wc -c < {path}", path = shell_quote(staged));
let result = ssh_exec_as(host, user, Some(password), &remote, Duration::from_secs(60))?;
if !result.ok() {
return Err(command_failure(&result));
}
let got = text(&result.stdout).trim().parse::<u64>().unwrap_or(0);
if got != size as u64 {
return Err(StockError::Method("target transfer was short".into()));
}
Ok(())
}
fn root_exec_impl(host: &str, password: Option<&str>, cmd: &str) -> Result<String, StockError> {
validate_host(host)?;
let resolved = resolve_password(password);
let ssh_password = resolved.as_deref();
match ssh_root_ready(host, ssh_password) {
Ok(()) => root_exec_via_ssh(host, ssh_password, cmd),
Err(ssh_error) => match stock_root_exec(host, password, cmd) {
Err(StockError::NotApplicable) | Err(StockError::Auth(_)) => {
if is_stock_http(host) {
root_exec_via_web(host, password, cmd)
} else {
Err(ssh_error)
}
}
other => other,
},
}
}
fn root_put_impl(
host: &str,
password: Option<&str>,
data: &[u8],
remote_path: &str,
) -> Result<(), StockError> {
validate_host(host)?;
validate_remote_path(remote_path)?;
let resolved = resolve_password(password);
let ssh_password = resolved.as_deref();
match ssh_root_ready(host, ssh_password) {
Ok(()) => root_put_via_ssh(host, ssh_password, data, remote_path),
Err(ssh_error) => match stock_root_put(host, password, data, remote_path) {
Err(StockError::NotApplicable) | Err(StockError::Auth(_)) => {
if is_stock_http(host) {
root_put_via_web(host, password, data, remote_path)
} else {
Err(ssh_error)
}
}
other => other,
},
}
}
/// The alkane write set for this board, placed on the given storage map:
/// rootfs, then dtb, then kernel (so an interrupted write never leaves a new
/// rootfs under an old kernel). `kernel` and `rootfs` are the uImage-wrapped
/// forms from `load_install_images`.
fn alkane_targets(
map: &[Mtd],
kernel: Vec<u8>,
dtb: Vec<u8>,
rootfs: Vec<u8>,
) -> Result<Vec<FlashTarget>, StockError> {
let images = vec![
(
"rootfs",
"afw-rootfs.uimg",
ABS_ROOTFS,
ROOTFS_SLOT,
Cow::Owned(rootfs),
),
("dtb", "afw-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)),
(
"kernel",
"afw-kernel.uimg",
ABS_KERNEL,
KERNEL_SLOT,
Cow::Owned(kernel),
),
];
targets_from_map(map, images)
}
fn install_via_ssh(
host: &str,
password: Option<&str>,
kernel: Vec<u8>,
dtb: Vec<u8>,
rootfs: Vec<u8>,
backup_stock: bool,
) -> Result<(), StockError> {
let map = if backup_stock {
get_mtd_map_for_backup(host, password, STOCK_BACKUP_BASE)?
} else {
get_mtd_map(host, password)?
};
if backup_stock {
create_onboard_stock_backup(host, password, &map)?;
}
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
flash_via_ssh(host, password, &targets)?;
reboot_target(host, password);
if wait_alkane(host, Duration::from_secs(240)) {
Ok(())
} else {
Err(StockError::Method("target did not return".into()))
}
}
fn flash_via_ssh(
host: &str,
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),
)?;
if !prep.ok() {
return Err(classify_ssh(&prep));
}
for target in targets {
let remote = format!("/tmp/rs/{}", target.file);
let timeout = Duration::from_secs(300);
ssh_push(host, password, &remote, target.data.as_ref(), timeout)?;
}
let script = flash_script(targets, "", None, false);
let remote_script = "/tmp/rs/go.sh";
ssh_push(
host,
password,
remote_script,
script.as_bytes(),
Duration::from_secs(30),
)?;
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(());
}
if output.contains("@@FAIL@@") || result.ok() {
return Err(StockError::Method("write failed".into()));
}
Err(classify_ssh(&result))
}
/// Read each target's whole slot as it is now and keep it under `dir`, before
/// anything is erased. Any short read or local write failure is an error, so
/// the caller aborts with nothing written.
fn hold_slots(
host: &str,
password: Option<&str>,
targets: &[FlashTarget],
dir: &Path,
) -> Result<Vec<HeldSlot>, StockError> {
fs::create_dir_all(dir)
.map_err(|e| StockError::Io(format!("could not create the backup directory: {e}")))?;
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let safe_host: String = host
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '.' {
c
} else {
'_'
}
})
.collect();
let mut held = Vec::with_capacity(targets.len());
for target in targets {
let remote = format!(
"dd if={} bs={} skip={} count={} 2>/dev/null",
target.device,
BLK,
target.rel / BLK,
target.slot / BLK
);
let result = ssh_exec(host, password, &remote, Duration::from_secs(600))?;
if !result.ok() {
return Err(classify_ssh(&result));
}
if result.stdout.len() as u64 != target.slot {
return Err(StockError::Method(format!(
"backup of the {} slot was short ({} of {} bytes); nothing was written",
target.name,
result.stdout.len(),
target.slot
)));
}
let absolute = target.absolute;
let path = dir.join(format!(
"zynq-{safe_host}-{}-0x{absolute:x}-{stamp}.img",
target.name
));
write_private_new(&path, &result.stdout)?;
held.push(HeldSlot {
name: target.name.to_string(),
absolute,
size: target.slot,
path,
md5: md5_hex(&result.stdout),
});
}
Ok(held)
}
fn render_map(map: &[Mtd]) -> String {
let mut out = String::new();
for mtd in map {
out.push_str(&format!(
" {} 0x{:08x}..0x{:08x} (0x{:x})\n",
mtd.device,
mtd.offset,
mtd.offset + mtd.size,
mtd.size
));
}
out
}
fn render_targets(targets: &[FlashTarget]) -> String {
let mut out = String::new();
for t in targets {
out.push_str(&format!(
" {:<6} -> {} +0x{:x} (abs 0x{:x}) slot 0x{:x}, {} bytes, md5 {}\n",
t.name,
t.device,
t.rel,
t.absolute,
t.slot,
t.data.len(),
t.raw_md5
));
}
out
}
/// Planned images in absolute NAND terms, independent of how the board's
/// partitions are currently registered.
fn render_absolute_plan(kernel: &[u8], dtb: &[u8], rootfs: &[u8]) -> String {
let mut out = String::new();
for (name, absolute, slot, data) in [
("rootfs", ABS_ROOTFS, ROOTFS_SLOT, rootfs),
("dtb", ABS_DTB, DTB_SLOT, dtb),
("kernel", ABS_KERNEL, KERNEL_SLOT, kernel),
] {
out.push_str(&format!(
" {:<6} -> abs 0x{:x} slot 0x{:x}, {} bytes, md5 {}\n",
name,
absolute,
slot,
data.len(),
md5_hex(data)
));
}
out
}
fn update_in_place_impl(
host: &str,
afw: &VerifiedAfw,
password: Option<&str>,
options: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError> {
validate_host(host)?;
let (kernel, dtb, rootfs) = load_install_images(afw)?;
if !ssh_port_open(host) {
return Err(StockError::Network("target unreachable".into()));
}
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
let state = board_state(host, password)?;
if state != "alkane" {
return Err(StockError::Method(format!(
"the board is not running alkane (detected: {state}); a board on stock is installed with --from-stock"
)));
}
if options.dry_run {
let map = read_mtd_map(host, password)?;
let mut report = String::new();
report.push_str(&format!("board {host}: running alkane\n"));
report.push_str("storage as registered now:\n");
report.push_str(&render_map(&map));
if map_covers_boot_regions(&map) {
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
report.push_str("boot regions are registered; writes would go to:\n");
report.push_str(&render_targets(&targets));
} else {
report.push_str(
"boot regions are NOT registered (normal on alkane); the update re-registers \
them first, as a restore does, then writes:\n",
);
report.push_str(&render_absolute_plan(&kernel, &dtb, &rootfs));
}
report.push_str(&format!(
"BOOT.bin (abs 0x0..0x{BOOTBIN_PRESERVE:x}) is never written.\n"
));
if options.backup_dir.is_some() {
report.push_str("each slot would be saved locally before any erase.\n");
}
return Ok(InPlaceOutcome::DryRun(report));
}
let map = get_mtd_map(host, password)?;
let targets = alkane_targets(&map, kernel, dtb, rootfs)?;
let backups = match &options.backup_dir {
Some(dir) => hold_slots(host, password, &targets, dir)?,
None => Vec::new(),
};
flash_via_ssh(host, password, &targets)?;
if !options.reboot {
return Ok(InPlaceOutcome::Updated(InPlaceReceipt {
backups,
rebooted: false,
}));
}
reboot_target(host, password);
// Wait for the board to actually go down before waiting for it to return,
// so a slow reboot is not mistaken for the old system still answering.
let _ = wait_for(|| !ssh_port_open(host), Duration::from_secs(60));
if wait_alkane(host, Duration::from_secs(300)) {
Ok(InPlaceOutcome::Updated(InPlaceReceipt {
backups,
rebooted: true,
}))
} else {
Err(StockError::Method(
"images were written and read back, but the board did not return as alkane after reboot"
.into(),
))
}
}
/// HTTP GET / and report (status-200, marker present case-insensitively).
fn http_marker(host: &str, marker: &str) -> (String, bool) {
let mut command = Command::new("curl");
command.args(["-sS", "-i", "--max-time", "6", &format!("http://{host}/")]);
match run_command(command, Duration::from_secs(12), None) {
Ok(result) if result.ok() => {
let body = text(&result.stdout);
let status = body.lines().next().unwrap_or("").trim().to_string();
let is_200 = status.contains(" 200");
let has = body.to_lowercase().contains(&marker.to_lowercase());
let title = body
.split("<title>")
.nth(1)
.and_then(|rest| rest.split("</title>").next())
.unwrap_or("")
.trim()
.to_string();
let detail = format!(
"{status}; title \"{title}\"; marker {marker} {}",
if has { "present" } else { "absent" }
);
(detail, is_200 && has)
}
Ok(result) => (
format!("no HTTP answer ({})", text(&result.stderr).trim()),
false,
),
Err(e) => (format!("{e}"), false),
}
}
pub(crate) fn live_check(
host: &str,
password: Option<&str>,
marker: &str,
kernel_version: &str,
timeout: Duration,
) -> Result<crate::stock::LiveCheck, StockError> {
validate_host(host)?;
let resolved = resolve_password(password);
let password = resolved.as_deref();
let deadline = Instant::now() + timeout;
let mut attempts = 0;
loop {
attempts += 1;
let (http, http_ok) = http_marker(host, marker);
let (ssh, ssh_ok, cmdline) = match ssh_exec(
host,
password,
"uname -r; echo '##'; cat /proc/cmdline; echo '##'; \
cat /etc/os-release /etc/issue 2>/dev/null; hostname; [ -d /etc/alkane ] && echo alkane-etc",
Duration::from_secs(20),
) {
Ok(result) if result.ok() => {
let out = text(&result.stdout);
let mut parts = out.split("##\n");
let kernel = parts.next().unwrap_or("").trim().to_string();
let cmdline = parts.next().unwrap_or("").trim().to_string();
let os = parts.next().unwrap_or("").to_lowercase();
let is_alkane = os.contains("alkane");
let kernel_ok =
!kernel.is_empty() && (kernel_version.is_empty() || kernel.contains(kernel_version));
(
format!(
"kernel {kernel}; os {}{}",
if is_alkane { "alkane" } else { "not alkane" },
if kernel_ok { "" } else { " (expected the installed kernel)" }
),
is_alkane && kernel_ok,
cmdline,
)
}
Ok(result) => (format!("{}", classify_ssh(&result)), false, String::new()),
Err(e) => (format!("{e}"), false, String::new()),
};
let done = (http_ok && ssh_ok) || Instant::now() >= deadline;
if done {
return Ok(crate::stock::LiveCheck {
attempts,
http,
http_ok,
ssh,
ssh_ok,
cmdline,
});
}
thread::sleep(Duration::from_secs(5));
}
}
fn board_state(host: &str, password: Option<&str>) -> Result<String, StockError> {
let result = ssh_exec(
host,
password,
"uname -r; cat /etc/os-release 2>/dev/null; hostname 2>/dev/null",
Duration::from_secs(20),
)?;
if !result.ok() {
return Err(classify_ssh(&result));
}
let lower = text(&result.stdout).to_lowercase();
if lower.contains("angstrom") || lower.contains("bitmain") {
return Ok("stock".to_string());
}
if lower.contains("alkane") {
return Ok("alkane".to_string());
}
if let Some(line) = lower.lines().next() {
if let Some(major) = line.split('.').next().and_then(|v| v.parse::<u32>().ok()) {
if major >= 6 {
return Ok("alkane".to_string());
}
if major == 4 {
return Ok("stock".to_string());
}
}
}
Ok("unknown".to_string())
}
struct Method;
impl StockMethod for Method {
fn install_from_stock(
&self,
host: &str,
_afw_path: &Path,
afw: &VerifiedAfw,
password: Option<&str>,
) -> Result<(), StockError> {
validate_host(host)?;
let (kernel, dtb, rootfs) = load_install_images(afw)?;
// A board that answers as our OS is updated in place over SSH.
if is_alkane_ssh(host) {
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
return install_via_ssh(host, password, kernel, dtb, rootfs, false);
}
// A board on genuine stock is reached through its own web gate.
if !is_stock_http(host) {
if ssh_port_open(host) {
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
let stock = board_state(host, password)? == "stock";
return install_via_ssh(host, password, kernel, dtb, rootfs, stock);
}
return Err(StockError::Network("target unreachable".into()));
}
install_via_web(host, password, kernel, dtb, rootfs)
}
fn restore_to_stock(
&self,
host: &str,
images: &RestoreImages,
password: Option<&str>,
) -> Result<(), StockError> {
validate_host(host)?;
if !ssh_port_open(host) {
if is_stock_http(host) {
return Ok(());
}
return Err(StockError::Network("target unreachable".into()));
}
let resolved = resolve_password(password);
let password = resolved.as_deref();
ssh_probe(host, password)?;
let state = board_state(host, password)?;
if state == "stock" {
return Ok(());
}
// The kernel device tree is not in Bitmain's distributable firmware, so
// use the correct per-board dtb (fetched + verified) rather than anything
// from the caller's package. The genuine kernel and rootfs come from the
// package the caller parsed.
let dtb = stock_asset(&ASSET_DTB)?;
// The brick-sensitive boot regions are not exposed to Linux on alkane;
// get_mtd_map re-registers them so the stock images can be written back.
let map = get_mtd_map(host, password)?;
let write = vec![
(
"rootfs",
"stock-rootfs.uimg",
ABS_ROOTFS,
ROOTFS_SLOT,
Cow::Owned(images.rootfs.to_vec()),
),
("dtb", "stock-dtb.bin", ABS_DTB, DTB_SLOT, Cow::Owned(dtb)),
(
"kernel",
"stock-kernel.uimg",
ABS_KERNEL,
KERNEL_SLOT,
Cow::Owned(images.kernel.to_vec()),
),
];
let targets = targets_from_map(&map, write)?;
flash_via_ssh(host, password, &targets)?;
// The stock images were written and read back before this point. On
// reboot the board comes up on stock, where it uses its stock MAC and
// typically takes a different DHCP lease, so it often does not return on
// the same address: a timeout waiting here is not a failure. Wait
// best-effort (fast path if the address is unchanged) and succeed either
// way; the caller verifies the board presents stock independently.
reboot_target(host, password);
let _ = wait_stock(host, Duration::from_secs(90));
Ok(())
}
fn root_exec(
&self,
host: &str,
password: Option<&str>,
cmd: &str,
) -> Result<String, StockError> {
root_exec_impl(host, password, cmd)
}
fn root_put(
&self,
host: &str,
password: Option<&str>,
data: &[u8],
remote_path: &str,
) -> Result<(), StockError> {
root_put_impl(host, password, data, remote_path)
}
fn update_in_place(
&self,
host: &str,
afw: &VerifiedAfw,
password: Option<&str>,
options: &InPlaceOptions,
) -> Result<InPlaceOutcome, StockError> {
update_in_place_impl(host, afw, password, options)
}
fn onboard_stock_backup_present(
&self,
host: &str,
password: Option<&str>,
) -> Result<bool, StockError> {
onboard_stock_backup_present_impl(host, password)
}
fn restore_from_onboard_backup(
&self,
host: &str,
password: Option<&str>,
timeout: Duration,
) -> Result<(), StockError> {
restore_from_onboard_backup_impl(host, password, timeout)
}
}
static METHOD: Method = Method;
pub fn method() -> &'static dyn StockMethod {
&METHOD
}
// ---------------------------------------------------------------- tests
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shell_quote_round_trips_awkward_arguments() {
for value in [
"/tmp/plain",
"/tmp/with space",
"/tmp/with'quote",
"a$b`c`d\"e\\f",
"line\nbreak",
"",
] {
assert_eq!(
shell_quote(value),
format!("'{}'", value.replace('\'', "'\\''"))
);
}
}
#[test]
fn run_result_splits_output_from_status() {
let marker = format!("{STOCK_RUN_MARK}abc123=");
assert_eq!(
split_run_result(&format!("uid=0(root)\n{marker}0\n"), &marker),
Some(("uid=0(root)\n".to_string(), 0))
);
// A command whose output does not end in a newline still parses.
assert_eq!(
split_run_result(&format!("no-newline{marker}3"), &marker),
Some(("no-newline".to_string(), 3))
);
// The last marker wins; earlier ones are ordinary output.
assert_eq!(
split_run_result(&format!("{marker}9\nreal{marker}0\n"), &marker),
Some((format!("{marker}9\nreal"), 0))
);
assert_eq!(split_run_result("nothing here\n", &marker), None);
assert_eq!(split_run_result(&format!("body{marker}"), &marker), None);
// A marker from another call is not accepted.
let other = format!("{STOCK_RUN_MARK}other=");
assert_eq!(split_run_result(&format!("out{other}0\n"), &marker), None);
}
#[test]
fn stock_login_defaults_included_and_deduplicated() {
let candidates = stock_unpriv_passwords(Some("supplied"));
assert_eq!(candidates.first().map(String::as_str), Some("supplied"));
assert!(candidates
.iter()
.any(|value| value == STOCK_UNPRIV_PASSWORD_DEFAULT));
let mut seen = candidates.clone();
seen.sort();
seen.dedup();
assert_eq!(seen.len(), candidates.len());
assert!(is_plain_user(STOCK_UNPRIV_USER_DEFAULT));
assert!(!is_plain_user("bad user"));
assert!(!is_plain_user("bad;user"));
assert!(!is_plain_user(""));
}
#[test]
fn remote_paths_are_split_and_validated() {
assert_eq!(remote_parent("/tmp/a/b"), "/tmp/a");
assert_eq!(remote_parent("/tmp"), "/");
assert_eq!(remote_parent("relative"), ".");
assert!(validate_remote_path("/tmp/a").is_ok());
assert!(validate_remote_path("").is_err());
assert!(validate_remote_path("/tmp/").is_err());
assert!(validate_remote_path("/tmp/\0bad").is_err());
}
#[cfg(unix)]
#[test]
fn streamed_command_input_is_transferred_whole() {
let dir = TempDir::new("streamtest").expect("temp dir");
let payload = vec![0xA5u8; 2 * 1024 * 1024 + 17];
let input = dir.join("input");
let output = dir.join("output");
write_private(&input, &payload).expect("write input");
let mut command = Command::new("sh");
command
.arg("-c")
.arg(format!("cat > {}", shell_quote(&output.to_string_lossy())));
let file = fs::File::open(&input).expect("open input");
let result =
run_command_stream(command, Duration::from_secs(30), file).expect("stream command");
assert!(result.ok());
assert_eq!(fs::read(&output).expect("read output"), payload);
}
#[test]
fn md5_known_vectors() {
assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e");
assert_eq!(md5_hex(b"abc"), "900150983cd24fb0d6963f7d28e17f72");
assert_eq!(
md5_hex(b"The quick brown fox jumps over the lazy dog"),
"9e107d9d372bb6826bd81d3542a419d6"
);
}
#[test]
fn sha256_known_vectors() {
assert_eq!(
sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(
sha256_hex(b"The quick brown fox jumps over the lazy dog"),
"d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
);
assert_eq!(
sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
);
}
#[test]
// The fetch path shells out to curl (as the whole method relies on local
// ssh/sshpass/curl). The Windows CI runs the test binary under Wine, where
// curl is not on PATH, so the test cannot run there.
#[cfg_attr(
windows,
ignore = "needs curl on PATH; the Windows CI runs tests under Wine without it"
)]
fn fetch_pipeline_caches_verifies_and_redownloads() {
let work = TempDir::new("fetchtest").expect("temp dir");
let source = work.path().join("source");
fs::create_dir_all(&source).expect("source dir");
let payload = b"stock asset payload";
fs::write(source.join("blob-test.bin"), payload).expect("source asset");
let hash: &'static str = Box::leak(sha256_hex(payload).into_boxed_str());
let asset = StockAsset {
file: "blob-test.bin",
sha256: hash,
};
let cache = work.path().join("cache");
env::set_var(
"ALKANE_STOCK_ASSETS_BASE",
format!("file://{}", source.display()),
);
env::set_var("XDG_CACHE_HOME", &cache);
assert_eq!(stock_asset(&asset).expect("first fetch"), payload);
let cached = cache
.join("alkane-toolkit")
.join("stock-assets")
.join("blob-test.bin");
assert!(cached.is_file());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(
fs::metadata(&cached)
.expect("metadata")
.permissions()
.mode()
& 0o777,
0o600
);
}
// A bad cache entry is dropped and fetched again.
fs::write(&cached, b"corrupt").expect("corrupt cache");
assert_eq!(stock_asset(&asset).expect("re-fetch"), payload);
// A mismatch on download leaves no cached file behind.
fs::remove_file(&cached).expect("remove cache");
fs::write(source.join("blob-test.bin"), b"tampered").expect("tamper source");
match stock_asset(&asset) {
Err(StockError::Method(message)) => {
assert_eq!(message, "asset integrity check failed")
}
other => panic!("expected an integrity failure, got {other:?}"),
}
assert!(!cached.exists());
env::remove_var("ALKANE_STOCK_ASSETS_BASE");
env::remove_var("XDG_CACHE_HOME");
}
#[test]
fn crc32_known_vector() {
assert_eq!(crc32(b"123456789"), 0xcbf4_3926);
}
#[test]
fn uimage_header_is_consistent() {
let image = mk_uimage(b"payload", 0x8000, 0x8000, 5, 2, 2, 0, b"test");
assert_eq!(image.len(), 64 + 7);
assert_eq!(&image[0..4], &[0x27, 0x05, 0x19, 0x56]);
let mut header = [0u8; 64];
header.copy_from_slice(&image[..64]);
let stored = u32::from_be_bytes([header[4], header[5], header[6], header[7]]);
header[4..8].fill(0);
assert_eq!(stored, crc32(&header));
let data_crc = u32::from_be_bytes([header[24], header[25], header[26], header[27]]);
assert_eq!(data_crc, crc32(b"payload"));
}
fn mtd(device: &str, offset: u64, size: u64) -> Mtd {
Mtd {
device: device.to_string(),
offset,
size,
}
}
/// The storage map the current alkane image registers: only the two small
/// config partitions, at absolute offsets. The boot regions are absent.
fn alkane_protected_map() -> Vec<Mtd> {
vec![
mtd("/dev/mtd0", 0x4800000, 0x800000), // stock-cfg (read-only)
mtd("/dev/mtd1", 0x5000000, 0x100000), // alkane-cfg
]
}
fn images() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
(
vec![0xAA; 0x300000],
vec![0xBB; 0x3000],
vec![0xCC; 0x400000],
)
}
#[test]
fn protected_alkane_map_yields_no_write_targets() {
// On the current alkane layout the boot regions are not registered, so
// nothing may be planned at all - in particular nothing on stock-cfg or
// alkane-cfg (the old tier-2 path erased alkane-cfg here).
let map = alkane_protected_map();
assert!(!map_covers_boot_regions(&map));
let (k, d, r) = images();
assert!(alkane_targets(&map, k, d, r).is_err());
}
#[test]
fn registered_boot_regions_place_targets_on_the_stock_uboot_slots() {
// Whole NAND registered as one device (as after re-registration).
let map = vec![mtd("/dev/mtd2", 0x0, 0x8000000)];
assert!(map_covers_boot_regions(&map));
let (k, d, r) = images();
let targets = alkane_targets(&map, k, d, r).unwrap();
let names: Vec<_> = targets.iter().map(|t| t.name).collect();
assert_eq!(names, ["rootfs", "dtb", "kernel"]);
let at = |n: &str| targets.iter().find(|t| t.name == n).unwrap();
assert_eq!(
(at("rootfs").rel, at("rootfs").absolute),
(0x2800000, 0x2800000)
);
assert_eq!((at("dtb").rel, at("dtb").absolute), (0x1A00000, 0x1A00000));
assert_eq!(
(at("kernel").rel, at("kernel").absolute),
(0x2000000, 0x2000000)
);
for t in &targets {
assert!(t.absolute >= BOOTBIN_PRESERVE);
}
}
#[test]
fn split_boot_partitions_resolve_relative_offsets() {
// Boot regions registered as separate partitions: offsets become
// partition-relative, absolute stays the NAND address.
let map = vec![
mtd("/dev/mtd2", 0x1A00000, 0x600000),
mtd("/dev/mtd3", 0x2000000, 0x800000),
mtd("/dev/mtd4", 0x2800000, 0x2000000),
];
let (k, d, r) = images();
let targets = alkane_targets(&map, k, d, r).unwrap();
let at = |n: &str| targets.iter().find(|t| t.name == n).unwrap();
assert_eq!((at("dtb").device.as_str(), at("dtb").rel), ("/dev/mtd2", 0));
assert_eq!(
(at("kernel").device.as_str(), at("kernel").rel),
("/dev/mtd3", 0)
);
assert_eq!(
(at("rootfs").device.as_str(), at("rootfs").rel),
("/dev/mtd4", 0)
);
}
#[test]
fn a_slot_that_overruns_its_partition_is_refused() {
// Rootfs slot (0x2000000) does not fit a 1 MiB partition at its offset.
let map = vec![
mtd("/dev/mtd2", 0x1A00000, 0x600000),
mtd("/dev/mtd3", 0x2000000, 0x800000),
mtd("/dev/mtd4", 0x2800000, 0x100000),
];
let (k, d, r) = images();
assert!(alkane_targets(&map, k, d, r).is_err());
}
#[test]
fn nothing_is_ever_placed_inside_bootbin() {
let target = make_target(
"x",
"x.bin",
"/dev/mtd2".to_string(),
0x100000,
0x100000,
0x20000,
Cow::Owned(vec![0u8; 16]),
);
assert!(target.is_err());
}
#[test]
fn gzip_and_tar_are_well_formed() {
let entries = vec![
TarEntry {
name: "d".to_string(),
mode: 0o777,
kind: b'2',
link: "/tmp".to_string(),
data: Vec::new(),
},
TarEntry {
name: "p".to_string(),
mode: 0o777,
kind: b'2',
link: "/www/pages/cgi-bin".to_string(),
data: Vec::new(),
},
TarEntry {
name: "d/test.bin".to_string(),
mode: 0o644,
kind: b'0',
link: String::new(),
data: b"hello".to_vec(),
},
];
let tar = build_tar(&entries);
assert_eq!(tar.len() % 512, 0);
let gz = gzip_store(&tar);
assert_eq!(&gz[..2], &[0x1f, 0x8b]);
let dir = TempDir::new("test").expect("temp dir");
let path = dir.join("test.tar.gz");
fs::write(&path, &gz).expect("write");
let result = Command::new("tar").arg("-tzf").arg(&path).output();
if let Ok(result) = result {
if result.status.success() {
let listing = text(&result.stdout);
assert!(listing.contains("d/test.bin"));
assert!(listing.contains("p"));
}
}
}
#[test]
fn every_default_target_is_above_bootbin() {
for (_, _, absolute, _, _) in [
("rootfs", "", ABS_ROOTFS, ROOTFS_SLOT, ()),
("dtb", "", ABS_DTB, DTB_SLOT, ()),
("kernel", "", ABS_KERNEL, KERNEL_SLOT, ()),
] {
assert!(absolute >= BOOTBIN_PRESERVE);
}
}
#[test]
fn stock_backup_manifest_round_trips_and_rejects_incomplete() {
let base = STOCK_BACKUP_BASE + STOCK_BACKUP_HEADER;
let entries = vec![
StockBackupEntry {
name: "dtb",
target_abs: ABS_DTB,
backup_abs: base,
size: DTB_SLOT,
md5: "0".repeat(32),
},
StockBackupEntry {
name: "kernel",
target_abs: ABS_KERNEL,
backup_abs: base + DTB_SLOT,
size: BLK,
md5: "1".repeat(32),
},
StockBackupEntry {
name: "ramdisk",
target_abs: ABS_ROOTFS,
backup_abs: base + DTB_SLOT + BLK,
size: BLK,
md5: "2".repeat(32),
},
];
let header = render_stock_backup(&entries);
let mut padded = header.clone();
padded.resize(STOCK_BACKUP_HEADER as usize, 0xff);
let parsed = parse_stock_backup(&padded).expect("manifest parses");
assert_eq!(parsed.entries.len(), 3);
assert_eq!(parsed.entries[1].size, BLK);
let text = String::from_utf8(header).unwrap();
let missing = text.replace(
&format!(
"kernel 0x{:x} 0x{:x} 0x{:x} {}\n",
ABS_KERNEL,
base + DTB_SLOT,
BLK,
"1".repeat(32)
),
"",
);
assert!(parse_stock_backup(missing.as_bytes()).is_none());
}
}