921 lines
30 KiB
Rust
921 lines
30 KiB
Rust
// SPDX-License-Identifier: MIT
|
|
//! CV1835 install, restore and live verification over the network.
|
|
//!
|
|
//! Order of operations for an install: verify the bundle, preflight the board,
|
|
//! hold the current p1 over SSH, stage the new p1, write it once, read the whole
|
|
//! partition back, and only then reboot. Any doubt before the first write stops
|
|
//! the sequence. A read-back mismatch stops before reboot and prints the exact
|
|
//! restore command.
|
|
|
|
use crate::boards::cv1835::{Cv1835Plan, CvPlanError};
|
|
use crate::md5::md5_hex;
|
|
use crate::preflight::{preflight, PreflightError, PreflightOptions, PreflightReport};
|
|
use crate::transport::{Remote, RemoteError, SshOptions, SshTransport};
|
|
use alkane_artifacts::afw::{AfwError, VerifiedAfw};
|
|
use sha2::{Digest, Sha256};
|
|
use std::fs;
|
|
use std::io::{Read, Write};
|
|
use std::net::{TcpStream, ToSocketAddrs};
|
|
use std::path::{Path, PathBuf};
|
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
|
use thiserror::Error;
|
|
|
|
const REMOTE_BACKUP: &str = "/tmp/.alkane-p1-backup.img";
|
|
const REMOTE_STAGE: &str = "/tmp/.alkane-p1-stage.img";
|
|
|
|
#[derive(Debug, Error)]
|
|
pub enum InstallError {
|
|
#[error("preflight failed; do not write\n{0}")]
|
|
Preflight(String),
|
|
#[error("install and restore need --confirm FLASH")]
|
|
Confirm,
|
|
#[error("verified .afw: {0}")]
|
|
Afw(#[from] AfwError),
|
|
#[error("cv1835 plan: {0}")]
|
|
Plan(#[from] CvPlanError),
|
|
#[error("preflight: {0}")]
|
|
PreflightError(#[from] PreflightError),
|
|
#[error("remote: {0}")]
|
|
Remote(#[from] RemoteError),
|
|
#[error("I/O: {0}")]
|
|
Io(#[from] std::io::Error),
|
|
#[error("backup {0} is not the 16 MiB p1 size")]
|
|
BackupSize(PathBuf),
|
|
#[error("backup md5 does not match the live p1; refusing to continue")]
|
|
BackupMismatch,
|
|
#[error("staged image md5 does not match the verified bundle; nothing written")]
|
|
StageMismatch,
|
|
#[error("p1 read-back md5 mismatch; do not reboot. Restore with: {0}")]
|
|
Readback(String),
|
|
#[error("restore read-back md5 mismatch; the board may still hold the new image")]
|
|
RestoreReadback,
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct InstallOptions {
|
|
pub dry_run: bool,
|
|
pub confirm: Option<String>,
|
|
pub no_reboot: bool,
|
|
pub backup_dir: PathBuf,
|
|
pub held_backup: Option<PathBuf>,
|
|
pub allow_unknown_source: bool,
|
|
pub check_golden: bool,
|
|
}
|
|
|
|
impl Default for InstallOptions {
|
|
fn default() -> Self {
|
|
Self {
|
|
dry_run: false,
|
|
confirm: None,
|
|
no_reboot: false,
|
|
backup_dir: default_backup_dir(),
|
|
held_backup: None,
|
|
allow_unknown_source: false,
|
|
check_golden: false,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct InstallReceipt {
|
|
pub backup_path: PathBuf,
|
|
pub backup_md5: String,
|
|
pub backup_sha256: String,
|
|
pub image_md5: String,
|
|
pub rebooted: bool,
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub enum InstallOutcome {
|
|
DryRun(Box<PreflightReport>),
|
|
Installed(InstallReceipt),
|
|
}
|
|
|
|
pub fn install(
|
|
_afw: &VerifiedAfw,
|
|
plan: &Cv1835Plan,
|
|
remote: &mut dyn Remote,
|
|
options: &InstallOptions,
|
|
host: &str,
|
|
) -> Result<InstallOutcome, InstallError> {
|
|
let report = preflight(
|
|
plan,
|
|
remote,
|
|
&PreflightOptions {
|
|
host,
|
|
held_backup: options.held_backup.as_deref(),
|
|
check_golden: options.check_golden,
|
|
allow_unknown_source: options.allow_unknown_source,
|
|
},
|
|
)?;
|
|
if !report.ok() {
|
|
return Err(InstallError::Preflight(report.render()));
|
|
}
|
|
if options.dry_run {
|
|
return Ok(InstallOutcome::DryRun(Box::new(report)));
|
|
}
|
|
if options.confirm.as_deref() != Some("FLASH") {
|
|
return Err(InstallError::Confirm);
|
|
}
|
|
|
|
fs::create_dir_all(&options.backup_dir)?;
|
|
let epoch = SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.unwrap_or_default()
|
|
.as_secs();
|
|
let backup_path = options.backup_dir.join(format!("p1-{epoch}.img"));
|
|
let device = &plan.partition.device;
|
|
|
|
// Hold the current p1 as root, then pull it over the unprivileged SSH
|
|
// session. The daemon channel is blind, so this two-step path is required.
|
|
let remote_backup = REMOTE_BACKUP;
|
|
remote.root_command(
|
|
&format!("dd if={device} of={remote_backup} bs=1M 2>&1; chmod 644 {remote_backup}"),
|
|
Duration::from_secs(180),
|
|
)?;
|
|
remote.pull(remote_backup, &backup_path, Duration::from_secs(240))?;
|
|
let _ = remote.root_command(&format!("rm -f {remote_backup}"), Duration::from_secs(15));
|
|
let backup_data = fs::read(&backup_path)?;
|
|
if backup_data.len() as u64 != plan.partition.size {
|
|
return Err(InstallError::BackupSize(backup_path));
|
|
}
|
|
let backup_md5 = md5_hex(&backup_data);
|
|
if report.live_md5 != "unreadable" && backup_md5 != report.live_md5 {
|
|
return Err(InstallError::BackupMismatch);
|
|
}
|
|
let backup_sha256: String = Sha256::digest(&backup_data)
|
|
.iter()
|
|
.map(|byte| format!("{byte:02x}"))
|
|
.collect();
|
|
write_sidecars(
|
|
&backup_path,
|
|
&backup_md5,
|
|
&backup_sha256,
|
|
&plan.partition,
|
|
&plan.expected_sha256,
|
|
epoch,
|
|
)?;
|
|
|
|
stage_and_write(plan, remote, &backup_path)?;
|
|
|
|
let rebooted = if options.no_reboot {
|
|
false
|
|
} else {
|
|
remote.reboot()?;
|
|
true
|
|
};
|
|
Ok(InstallOutcome::Installed(InstallReceipt {
|
|
backup_path,
|
|
backup_md5,
|
|
backup_sha256,
|
|
image_md5: plan.expected_md5.clone(),
|
|
rebooted,
|
|
}))
|
|
}
|
|
|
|
fn stage_and_write(
|
|
plan: &Cv1835Plan,
|
|
remote: &mut dyn Remote,
|
|
backup_path: &Path,
|
|
) -> Result<(), InstallError> {
|
|
let mut staged =
|
|
tempfile::NamedTempFile::new_in(backup_path.parent().unwrap_or_else(|| Path::new(".")))?;
|
|
staged.write_all(&plan.data)?;
|
|
staged.flush()?;
|
|
remote.push(staged.path(), REMOTE_STAGE, Duration::from_secs(240))?;
|
|
let staged_md5 =
|
|
remote.root_command(&format!("md5sum {REMOTE_STAGE}"), Duration::from_secs(60))?;
|
|
let staged_md5 = String::from_utf8_lossy(&staged_md5)
|
|
.split_whitespace()
|
|
.next()
|
|
.unwrap_or("")
|
|
.to_ascii_lowercase();
|
|
if staged_md5 != plan.expected_md5 {
|
|
let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15));
|
|
return Err(InstallError::StageMismatch);
|
|
}
|
|
|
|
remote.root_command(
|
|
&format!(
|
|
"dd if={REMOTE_STAGE} of={} bs=1M conv=fsync 2>&1; sync",
|
|
plan.partition.device
|
|
),
|
|
Duration::from_secs(240),
|
|
)?;
|
|
let readback = remote.root_command(
|
|
&format!("md5sum {}", plan.partition.device),
|
|
Duration::from_secs(90),
|
|
)?;
|
|
let readback = String::from_utf8_lossy(&readback)
|
|
.split_whitespace()
|
|
.next()
|
|
.unwrap_or("")
|
|
.to_ascii_lowercase();
|
|
let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15));
|
|
if readback != plan.expected_md5 {
|
|
return Err(InstallError::Readback(restore_command(
|
|
&plan.partition.device,
|
|
backup_path,
|
|
)));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct RestoreOptions {
|
|
pub confirm: Option<String>,
|
|
pub no_reboot: bool,
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct RestoreReceipt {
|
|
pub backup_path: PathBuf,
|
|
pub image_md5: String,
|
|
pub rebooted: bool,
|
|
}
|
|
|
|
pub fn restore(
|
|
backup: &Path,
|
|
remote: &mut dyn Remote,
|
|
options: &RestoreOptions,
|
|
) -> Result<RestoreReceipt, InstallError> {
|
|
if options.confirm.as_deref() != Some("FLASH") {
|
|
return Err(InstallError::Confirm);
|
|
}
|
|
let data = fs::read(backup)?;
|
|
if data.len() != 16 * 1024 * 1024 {
|
|
return Err(InstallError::BackupSize(backup.to_path_buf()));
|
|
}
|
|
let md5 = md5_hex(&data);
|
|
let sha256: String = Sha256::digest(&data)
|
|
.iter()
|
|
.map(|byte| format!("{byte:02x}"))
|
|
.collect();
|
|
if let Some(sidecar) = read_sidecar(backup) {
|
|
if sidecar != sha256 {
|
|
return Err(InstallError::BackupMismatch);
|
|
}
|
|
}
|
|
|
|
let root_uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
|
|
.trim()
|
|
.to_owned();
|
|
if root_uid != "0" {
|
|
return Err(InstallError::Preflight(format!(
|
|
"root channel returned uid {root_uid}"
|
|
)));
|
|
}
|
|
let size = remote.user_command(
|
|
"cat /sys/class/block/mmcblk0p1/size 2>/dev/null || true",
|
|
Duration::from_secs(15),
|
|
)?;
|
|
let sectors: u64 = String::from_utf8_lossy(&size).trim().parse().unwrap_or(0);
|
|
if sectors.saturating_mul(512) != 16 * 1024 * 1024 {
|
|
return Err(InstallError::Preflight(
|
|
"the board does not expose a 16 MiB /dev/mmcblk0p1".to_owned(),
|
|
));
|
|
}
|
|
|
|
let staged = tempfile::NamedTempFile::new()?;
|
|
fs::write(staged.path(), &data)?;
|
|
remote.push(staged.path(), REMOTE_STAGE, Duration::from_secs(240))?;
|
|
let staged_md5 =
|
|
remote.root_command(&format!("md5sum {REMOTE_STAGE}"), Duration::from_secs(60))?;
|
|
let staged_md5 = String::from_utf8_lossy(&staged_md5)
|
|
.split_whitespace()
|
|
.next()
|
|
.unwrap_or("")
|
|
.to_ascii_lowercase();
|
|
if staged_md5 != md5 {
|
|
let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15));
|
|
return Err(InstallError::StageMismatch);
|
|
}
|
|
remote.root_command(
|
|
&format!("dd if={REMOTE_STAGE} of=/dev/mmcblk0p1 bs=1M conv=fsync 2>&1; sync"),
|
|
Duration::from_secs(240),
|
|
)?;
|
|
let readback = remote.root_command("md5sum /dev/mmcblk0p1", Duration::from_secs(90))?;
|
|
let readback = String::from_utf8_lossy(&readback)
|
|
.split_whitespace()
|
|
.next()
|
|
.unwrap_or("")
|
|
.to_ascii_lowercase();
|
|
let _ = remote.root_command(&format!("rm -f {REMOTE_STAGE}"), Duration::from_secs(15));
|
|
if readback != md5 {
|
|
return Err(InstallError::RestoreReadback);
|
|
}
|
|
let rebooted = if options.no_reboot {
|
|
false
|
|
} else {
|
|
remote.reboot()?;
|
|
true
|
|
};
|
|
Ok(RestoreReceipt {
|
|
backup_path: backup.to_path_buf(),
|
|
image_md5: md5,
|
|
rebooted,
|
|
})
|
|
}
|
|
|
|
fn restore_command(device: &str, backup: &Path) -> String {
|
|
format!(
|
|
"alkane-cli afw restore --host <ip> --held-backup {} --confirm FLASH (the held copy of {device} is at {})",
|
|
backup.display(),
|
|
backup.display()
|
|
)
|
|
}
|
|
|
|
fn default_backup_dir() -> PathBuf {
|
|
alkane_core::platform::config_path("backups")
|
|
}
|
|
|
|
fn write_sidecars(
|
|
path: &Path,
|
|
md5: &str,
|
|
sha256: &str,
|
|
partition: &alkane_artifacts::afw::AfwPartition,
|
|
image_sha256: &str,
|
|
epoch: u64,
|
|
) -> Result<(), InstallError> {
|
|
let file_name = path
|
|
.file_name()
|
|
.map(|name| name.to_string_lossy().into_owned())
|
|
.unwrap_or_else(|| "p1.img".to_owned());
|
|
fs::write(
|
|
path.with_extension("img.sha256"),
|
|
format!("{sha256} {file_name}\n"),
|
|
)?;
|
|
let metadata = serde_json::json!({
|
|
"board": "cv1835",
|
|
"partition": partition.name,
|
|
"device": partition.device,
|
|
"size": partition.size,
|
|
"md5": md5,
|
|
"sha256": sha256,
|
|
"afw_sha256": image_sha256,
|
|
"created_unix": epoch,
|
|
});
|
|
fs::write(
|
|
path.with_extension("img.json"),
|
|
serde_json::to_vec_pretty(&metadata).unwrap_or_default(),
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn read_sidecar(path: &Path) -> Option<String> {
|
|
let text = fs::read_to_string(path.with_extension("img.sha256")).ok()?;
|
|
text.split_whitespace().next().map(str::to_owned)
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct LiveReport {
|
|
pub attempts: u32,
|
|
pub http: String,
|
|
pub http_ok: bool,
|
|
pub ssh: String,
|
|
pub ssh_ok: bool,
|
|
pub api: String,
|
|
pub api_ok: bool,
|
|
}
|
|
|
|
impl LiveReport {
|
|
pub fn ok(&self) -> bool {
|
|
self.http_ok && self.ssh_ok && self.api_ok
|
|
}
|
|
|
|
pub fn render(&self) -> String {
|
|
format!(
|
|
"verify-live attempts {}\n http {}: {}\n ssh {}: {}\n api {}: {}\nresult {}",
|
|
self.attempts,
|
|
if self.http_ok { "ok" } else { "FAIL" },
|
|
self.http,
|
|
if self.ssh_ok { "ok" } else { "FAIL" },
|
|
self.ssh,
|
|
if self.api_ok { "ok" } else { "FAIL" },
|
|
self.api,
|
|
if self.ok() { "PASS" } else { "FAIL" }
|
|
)
|
|
}
|
|
}
|
|
|
|
pub fn verify_live(
|
|
host: &str,
|
|
marker: &str,
|
|
kernel_version: &str,
|
|
timeout: Duration,
|
|
ssh_options: &SshOptions,
|
|
) -> LiveReport {
|
|
let deadline = Instant::now() + timeout;
|
|
let mut attempts = 0;
|
|
loop {
|
|
attempts += 1;
|
|
let (http, http_ok) = match http_get(host, "/", Duration::from_secs(5)) {
|
|
Ok(body) => {
|
|
let ok = body.contains(marker);
|
|
(
|
|
if ok {
|
|
format!("marker {marker} present")
|
|
} else {
|
|
format!("marker {marker} absent ({} bytes)", body.len())
|
|
},
|
|
ok,
|
|
)
|
|
}
|
|
Err(error) => (error, false),
|
|
};
|
|
let (ssh, ssh_ok) = match SshTransport::connect(ssh_options.clone(), false) {
|
|
Ok(mut session) => match session.user_command("uname -r", Duration::from_secs(15)) {
|
|
Ok(output) => {
|
|
let kernel = String::from_utf8_lossy(&output).trim().to_owned();
|
|
let ok = !kernel.is_empty()
|
|
&& (kernel_version.is_empty() || kernel.contains(kernel_version));
|
|
(
|
|
format!(
|
|
"kernel {kernel}{}",
|
|
if ok {
|
|
""
|
|
} else {
|
|
" (expected the installed kernel)"
|
|
}
|
|
),
|
|
ok,
|
|
)
|
|
}
|
|
Err(error) => (format!("{error}"), false),
|
|
},
|
|
Err(error) => (format!("{error}"), false),
|
|
};
|
|
let (api, api_ok) = match api_version(host, Duration::from_secs(5)) {
|
|
Ok(body) => {
|
|
let ok = body.contains("\"STATUS\"")
|
|
|| body.contains("\"VERSION\"")
|
|
|| body.to_lowercase().contains("version");
|
|
(format!("{} bytes", body.len()), ok)
|
|
}
|
|
Err(error) => (error, false),
|
|
};
|
|
if http_ok && ssh_ok && api_ok {
|
|
return LiveReport {
|
|
attempts,
|
|
http,
|
|
http_ok,
|
|
ssh,
|
|
ssh_ok,
|
|
api,
|
|
api_ok,
|
|
};
|
|
}
|
|
if Instant::now() >= deadline {
|
|
return LiveReport {
|
|
attempts,
|
|
http,
|
|
http_ok,
|
|
ssh,
|
|
ssh_ok,
|
|
api,
|
|
api_ok,
|
|
};
|
|
}
|
|
std::thread::sleep(Duration::from_secs(5));
|
|
}
|
|
}
|
|
|
|
pub(crate) fn http_get(host: &str, path: &str, timeout: Duration) -> Result<String, String> {
|
|
let address = (host, 80_u16)
|
|
.to_socket_addrs()
|
|
.map_err(|error| format!("resolve: {error}"))?
|
|
.next()
|
|
.ok_or_else(|| "no address".to_owned())?;
|
|
let mut stream = TcpStream::connect_timeout(&address, timeout)
|
|
.map_err(|error| format!("connect: {error}"))?;
|
|
stream
|
|
.set_read_timeout(Some(timeout))
|
|
.map_err(|error| error.to_string())?;
|
|
let request = format!("GET {path} HTTP/1.0\r\nHost: {host}\r\nConnection: close\r\n\r\n");
|
|
stream
|
|
.write_all(request.as_bytes())
|
|
.map_err(|error| error.to_string())?;
|
|
let mut data = Vec::new();
|
|
let mut buffer = [0_u8; 8192];
|
|
loop {
|
|
match stream.read(&mut buffer) {
|
|
Ok(0) => break,
|
|
Ok(read) => {
|
|
data.extend_from_slice(&buffer[..read]);
|
|
if data.len() > 512 * 1024 {
|
|
break;
|
|
}
|
|
}
|
|
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
|
|
Err(error) if error.kind() == std::io::ErrorKind::TimedOut => break,
|
|
Err(error) => return Err(error.to_string()),
|
|
}
|
|
}
|
|
let text = String::from_utf8_lossy(&data).into_owned();
|
|
let status_ok = text
|
|
.lines()
|
|
.next()
|
|
.map(|line| line.contains(" 200 ") || line.ends_with(" 200"))
|
|
.unwrap_or(false);
|
|
if status_ok {
|
|
Ok(text)
|
|
} else {
|
|
Err(text.lines().next().unwrap_or("no HTTP response").to_owned())
|
|
}
|
|
}
|
|
|
|
pub(crate) fn api_version(host: &str, timeout: Duration) -> Result<String, String> {
|
|
let address = (host, 4028_u16)
|
|
.to_socket_addrs()
|
|
.map_err(|error| format!("resolve: {error}"))?
|
|
.next()
|
|
.ok_or_else(|| "no address".to_owned())?;
|
|
let mut stream = TcpStream::connect_timeout(&address, timeout)
|
|
.map_err(|error| format!("connect: {error}"))?;
|
|
stream
|
|
.set_read_timeout(Some(timeout))
|
|
.map_err(|error| error.to_string())?;
|
|
stream
|
|
.write_all(b"{\"command\":\"version\"}\n")
|
|
.map_err(|error| error.to_string())?;
|
|
let mut data = Vec::new();
|
|
let mut buffer = [0_u8; 4096];
|
|
loop {
|
|
match stream.read(&mut buffer) {
|
|
Ok(0) => break,
|
|
Ok(read) => {
|
|
data.extend_from_slice(&buffer[..read]);
|
|
if data.len() > 64 * 1024 {
|
|
break;
|
|
}
|
|
}
|
|
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => break,
|
|
Err(error) if error.kind() == std::io::ErrorKind::TimedOut => break,
|
|
Err(error) => return Err(error.to_string()),
|
|
}
|
|
}
|
|
let text = String::from_utf8_lossy(&data).trim().to_owned();
|
|
if text.is_empty() {
|
|
Err("no API response".to_owned())
|
|
} else {
|
|
Ok(text)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn derives_backup_sidecar_names() {
|
|
let path = Path::new("/tmp/p1-1.img");
|
|
assert_eq!(
|
|
path.with_extension("img.sha256"),
|
|
Path::new("/tmp/p1-1.img.sha256")
|
|
);
|
|
assert_eq!(
|
|
path.with_extension("img.json"),
|
|
Path::new("/tmp/p1-1.img.json")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn restore_command_names_the_held_copy() {
|
|
let command = restore_command("/dev/mmcblk0p1", Path::new("/tmp/p1.img"));
|
|
assert!(command.contains("afw restore"));
|
|
assert!(command.contains("/tmp/p1.img"));
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod network_tests {
|
|
use super::*;
|
|
use alkane_artifacts::afw::{AfwImage, AfwManifest, AfwMember, AfwPartition, BootloaderPolicy};
|
|
use serde_json::json;
|
|
use std::collections::HashMap;
|
|
|
|
const P1: usize = 16 * 1024 * 1024;
|
|
const REV: &str = "0000000000000000000000000000000000000000";
|
|
|
|
struct MockRemote {
|
|
partition: Vec<u8>,
|
|
files: HashMap<String, Vec<u8>>,
|
|
commands: Vec<String>,
|
|
rebooted: bool,
|
|
readback_corrupt: bool,
|
|
}
|
|
|
|
impl MockRemote {
|
|
fn new(partition: Vec<u8>) -> Self {
|
|
Self {
|
|
partition,
|
|
files: HashMap::new(),
|
|
commands: Vec::new(),
|
|
rebooted: false,
|
|
readback_corrupt: false,
|
|
}
|
|
}
|
|
|
|
fn md5(&self, data: &[u8]) -> String {
|
|
md5_hex(data)
|
|
}
|
|
}
|
|
|
|
impl Remote for MockRemote {
|
|
fn channel(&self) -> &str {
|
|
"mock"
|
|
}
|
|
|
|
fn root_method(&self) -> &'static str {
|
|
"direct"
|
|
}
|
|
|
|
fn user_command(
|
|
&mut self,
|
|
command: &str,
|
|
_timeout: Duration,
|
|
) -> Result<Vec<u8>, RemoteError> {
|
|
self.commands.push(command.to_owned());
|
|
let text = if command.contains("uname -r") {
|
|
"6.18.48\n__MODEL__\nAlkane CV1835\n__RELEASE__\nalkane\n".to_owned()
|
|
} else if command.contains("test -b") {
|
|
"block".to_owned()
|
|
} else if command.contains("/sys/class/block/mmcblk0p1/size") {
|
|
"32768".to_owned()
|
|
} else if command.contains("for c in dd") {
|
|
"dd\nmd5sum\nsync\n".to_owned()
|
|
} else if command.contains("df -k") {
|
|
"Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/root 100000 1 90000 1% /tmp\n".to_owned()
|
|
} else if command.contains("mmcblk0boot0") {
|
|
"yes".to_owned()
|
|
} else {
|
|
String::new()
|
|
};
|
|
Ok(text.into_bytes())
|
|
}
|
|
|
|
fn root_command(
|
|
&mut self,
|
|
command: &str,
|
|
_timeout: Duration,
|
|
) -> Result<Vec<u8>, RemoteError> {
|
|
self.commands.push(command.to_owned());
|
|
if command.starts_with("id -u") || command == "id" {
|
|
return Ok(b"0\n".to_vec());
|
|
}
|
|
if let Some(rest) = command.strip_prefix("md5sum /dev/mmcblk0p1") {
|
|
let _ = rest;
|
|
let mut data = self.partition.clone();
|
|
if self.readback_corrupt && self.files.contains_key(REMOTE_STAGE) {
|
|
if let Some(last) = data.last_mut() {
|
|
*last ^= 0xff;
|
|
}
|
|
self.readback_corrupt = false;
|
|
}
|
|
return Ok(format!("{} /dev/mmcblk0p1\n", self.md5(&data)).into_bytes());
|
|
}
|
|
if let Some(rest) = command.strip_prefix("md5sum ") {
|
|
let path = rest.split_whitespace().next().unwrap_or("");
|
|
let data = self.files.get(path).cloned().unwrap_or_default();
|
|
return Ok(format!("{} {path}\n", self.md5(&data)).into_bytes());
|
|
}
|
|
if let Some(rest) = command.strip_prefix("dd if=") {
|
|
let mut parts = rest.splitn(2, " of=");
|
|
let source = parts.next().unwrap_or("");
|
|
let target = parts
|
|
.next()
|
|
.unwrap_or("")
|
|
.split_whitespace()
|
|
.next()
|
|
.unwrap_or("");
|
|
if source == "/dev/mmcblk0p1" {
|
|
self.files.insert(target.to_owned(), self.partition.clone());
|
|
} else if target == "/dev/mmcblk0p1" {
|
|
if let Some(data) = self.files.get(source).cloned() {
|
|
self.partition = data;
|
|
}
|
|
}
|
|
return Ok(Vec::new());
|
|
}
|
|
if command.starts_with("rm -f ") {
|
|
let path = command.trim_start_matches("rm -f ").trim();
|
|
self.files.remove(path);
|
|
return Ok(Vec::new());
|
|
}
|
|
Ok(Vec::new())
|
|
}
|
|
|
|
fn push(
|
|
&mut self,
|
|
local: &Path,
|
|
remote: &str,
|
|
_timeout: Duration,
|
|
) -> Result<(), RemoteError> {
|
|
self.files.insert(remote.to_owned(), fs::read(local)?);
|
|
Ok(())
|
|
}
|
|
|
|
fn pull(
|
|
&mut self,
|
|
remote: &str,
|
|
local: &Path,
|
|
_timeout: Duration,
|
|
) -> Result<(), RemoteError> {
|
|
let data = self
|
|
.files
|
|
.get(remote)
|
|
.cloned()
|
|
.ok_or_else(|| RemoteError::Daemon("missing file".to_owned()))?;
|
|
fs::write(local, data)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn reboot(&mut self) -> Result<(), RemoteError> {
|
|
self.rebooted = true;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn p1_image() -> Vec<u8> {
|
|
let mut fit = vec![0_u8; P1];
|
|
fit[..4].copy_from_slice(b"\xd0\x0d\xfe\xed");
|
|
let marker = b"config@cv1835_miner_emmc";
|
|
fit[0x100..0x100 + marker.len()].copy_from_slice(marker);
|
|
fit
|
|
}
|
|
|
|
fn verified(data: &[u8]) -> VerifiedAfw {
|
|
let manifest = AfwManifest {
|
|
schema: 2,
|
|
format: "afw".to_owned(),
|
|
board: "cv1835".to_owned(),
|
|
arch: "arm64".to_owned(),
|
|
version: "0.1.0".to_owned(),
|
|
build_date: "2026-11-04T00:00:00Z".to_owned(),
|
|
sdk_revision: REV.to_owned(),
|
|
os_revision: REV.to_owned(),
|
|
payload_type: "os".to_owned(),
|
|
bootloader_policy: BootloaderPolicy::Preserve,
|
|
signature: alkane_artifacts::afw::AfwSignature {
|
|
kind: "unsigned".to_owned(),
|
|
member: None,
|
|
public_key_hex: None,
|
|
},
|
|
partitions: vec![
|
|
AfwPartition {
|
|
name: "p1".to_owned(),
|
|
device: "/dev/mmcblk0p1".to_owned(),
|
|
offset: 0,
|
|
size: P1 as u64,
|
|
secure: false,
|
|
boot_critical: true,
|
|
write_order: 1,
|
|
image: Some("p1".to_owned()),
|
|
},
|
|
AfwPartition {
|
|
name: "boot0".to_owned(),
|
|
device: "/dev/mmcblk0boot0".to_owned(),
|
|
offset: 0,
|
|
size: 4 * 1024 * 1024,
|
|
secure: true,
|
|
boot_critical: true,
|
|
write_order: 0,
|
|
image: None,
|
|
},
|
|
],
|
|
images: vec![AfwImage {
|
|
name: "p1".to_owned(),
|
|
file: "payload/p1.fit".to_owned(),
|
|
role: "boot".to_owned(),
|
|
format: "fit".to_owned(),
|
|
size: P1 as u64,
|
|
sha256: Sha256::digest(data)
|
|
.iter()
|
|
.map(|byte| format!("{byte:02x}"))
|
|
.collect(),
|
|
partition: Some("p1".to_owned()),
|
|
install: true,
|
|
}],
|
|
boot_switch: json!({"method": "partition-overwrite"}),
|
|
preflight: json!({"required_commands": ["dd", "md5sum", "sync"],
|
|
"source_os": ["stock-bitmain", "vnish", "braiins", "ouros", "alkane"],
|
|
"min_free_bytes": 33554432}),
|
|
recovery: json!({"network": "afw restore", "golden_lba_bytes": 0x300000u64 * 512}),
|
|
marker: "Alkane".to_owned(),
|
|
kernel_version: "6.18.48".to_owned(),
|
|
notes: None,
|
|
};
|
|
VerifiedAfw {
|
|
manifest,
|
|
members: vec![AfwMember {
|
|
name: "payload/p1.fit".to_owned(),
|
|
data: data.to_vec(),
|
|
}],
|
|
manifest_sha256: "0".repeat(64),
|
|
archive_sha256: "0".repeat(64),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn installs_p1_holds_a_backup_and_verifies_before_reboot() {
|
|
let original = vec![0x11_u8; P1];
|
|
let new = p1_image();
|
|
let afw = verified(&new);
|
|
let plan = Cv1835Plan::from_afw(&afw).unwrap();
|
|
let mut remote = MockRemote::new(original.clone());
|
|
let temp = tempfile::tempdir().unwrap();
|
|
let options = InstallOptions {
|
|
dry_run: false,
|
|
confirm: Some("FLASH".to_owned()),
|
|
no_reboot: true,
|
|
backup_dir: temp.path().to_path_buf(),
|
|
held_backup: None,
|
|
allow_unknown_source: true,
|
|
check_golden: false,
|
|
};
|
|
let outcome = install(&afw, &plan, &mut remote, &options, "10.255.1.1").unwrap();
|
|
let InstallOutcome::Installed(receipt) = outcome else {
|
|
panic!("expected an install");
|
|
};
|
|
assert_eq!(remote.partition, new);
|
|
assert_eq!(receipt.backup_md5, md5_hex(&original));
|
|
assert!(receipt.backup_path.is_file());
|
|
assert!(!remote.rebooted);
|
|
assert!(remote
|
|
.commands
|
|
.iter()
|
|
.any(|command| command.starts_with("dd if=/tmp/.alkane-p1-stage.img")));
|
|
}
|
|
|
|
#[test]
|
|
fn dry_run_never_writes_the_partition() {
|
|
let original = vec![0x22_u8; P1];
|
|
let new = p1_image();
|
|
let afw = verified(&new);
|
|
let plan = Cv1835Plan::from_afw(&afw).unwrap();
|
|
let mut remote = MockRemote::new(original.clone());
|
|
let temp = tempfile::tempdir().unwrap();
|
|
let options = InstallOptions {
|
|
dry_run: true,
|
|
confirm: None,
|
|
no_reboot: false,
|
|
backup_dir: temp.path().to_path_buf(),
|
|
held_backup: None,
|
|
allow_unknown_source: true,
|
|
check_golden: false,
|
|
};
|
|
let outcome = install(&afw, &plan, &mut remote, &options, "10.255.1.1").unwrap();
|
|
assert!(matches!(outcome, InstallOutcome::DryRun(_)));
|
|
assert_eq!(remote.partition, original);
|
|
assert!(!remote
|
|
.commands
|
|
.iter()
|
|
.any(|command| command.starts_with("dd if=/tmp/.alkane-p1-stage.img")));
|
|
}
|
|
|
|
#[test]
|
|
fn a_readback_mismatch_stops_before_reboot() {
|
|
let original = vec![0x33_u8; P1];
|
|
let new = p1_image();
|
|
let afw = verified(&new);
|
|
let plan = Cv1835Plan::from_afw(&afw).unwrap();
|
|
let mut remote = MockRemote::new(original);
|
|
remote.readback_corrupt = true;
|
|
let temp = tempfile::tempdir().unwrap();
|
|
let options = InstallOptions {
|
|
dry_run: false,
|
|
confirm: Some("FLASH".to_owned()),
|
|
no_reboot: false,
|
|
backup_dir: temp.path().to_path_buf(),
|
|
held_backup: None,
|
|
allow_unknown_source: true,
|
|
check_golden: false,
|
|
};
|
|
let result = install(&afw, &plan, &mut remote, &options, "10.255.1.1");
|
|
assert!(matches!(result, Err(InstallError::Readback(_))));
|
|
assert!(!remote.rebooted);
|
|
}
|
|
|
|
#[test]
|
|
fn confirm_is_required_before_any_device_write() {
|
|
let original = vec![0x44_u8; P1];
|
|
let new = p1_image();
|
|
let afw = verified(&new);
|
|
let plan = Cv1835Plan::from_afw(&afw).unwrap();
|
|
let mut remote = MockRemote::new(original.clone());
|
|
let temp = tempfile::tempdir().unwrap();
|
|
let options = InstallOptions {
|
|
dry_run: false,
|
|
confirm: None,
|
|
no_reboot: false,
|
|
backup_dir: temp.path().to_path_buf(),
|
|
held_backup: None,
|
|
allow_unknown_source: true,
|
|
check_golden: false,
|
|
};
|
|
let result = install(&afw, &plan, &mut remote, &options, "10.255.1.1");
|
|
assert!(matches!(result, Err(InstallError::Confirm)));
|
|
assert_eq!(remote.partition, original);
|
|
}
|
|
}
|