Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
684be52d5a | ||
|
|
76de56fef5 | ||
|
|
ae9e2c67cc | ||
|
|
400edbe913 | ||
|
|
462ced01a6 | ||
|
|
c79ee1315d | ||
|
|
cce24b6880 | ||
|
|
b1316b2bd9 | ||
|
|
9f6eccc5ac | ||
|
|
4d1adeb05e | ||
|
|
628c0630a5 | ||
|
|
3d1fd36811 | ||
|
|
7f2ea8a8dc | ||
|
|
b26f389460 | ||
|
|
b46f15b340 | ||
|
|
c9d32f9793 | ||
|
|
5cf9d44d7e |
@@ -159,6 +159,7 @@ jobs:
|
||||
run: |
|
||||
cargo test -p alkane-gui --offline
|
||||
cargo test --workspace --exclude alkane-gui --exclude wx-rs --offline
|
||||
python3 tools/report-relay/test_relay.py
|
||||
|
||||
- name: Microbenchmarks
|
||||
if: steps.surface.outputs.surface == 'full'
|
||||
|
||||
Generated
+5
@@ -40,6 +40,8 @@ name = "alkane-artifacts"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"alkane-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror",
|
||||
]
|
||||
@@ -50,6 +52,8 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"alkane-artifacts",
|
||||
"alkane-core",
|
||||
"alkane-flash",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -74,6 +78,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"alkane-artifacts",
|
||||
"alkane-core",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
|
||||
@@ -19,6 +19,7 @@ license = "MIT"
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
sha2 = "0.10"
|
||||
serde_json = "1"
|
||||
|
||||
# Release binary: small, self-contained, and fast enough for a fleet GUI whose
|
||||
# hot path is network I/O, not CPU (round 18 #12). opt-level "s" + fat LTO +
|
||||
|
||||
@@ -47,6 +47,50 @@ and Intel, macOS 11 or later; see [docs/macos.md](docs/macos.md).
|
||||
Discovery is read-only. Control and restore actions change miners. Check the
|
||||
selected devices before applying them.
|
||||
|
||||
## Headless .afw install (CV1835 and AM335x)
|
||||
|
||||
`alkane-cli` is the headless engine; the GUI uses the same engine. A verified
|
||||
`.afw` is a full OS bundle for exactly one board. The CV1835 installer writes
|
||||
only `/dev/mmcblk0p1` over SSH, holds the current p1 first, reads the whole
|
||||
partition back, and reboots only after the read-back matches.
|
||||
|
||||
The AM335x installer writes mtd8 (type-3 ramdisk), mtd6 (dtb) and mtd7
|
||||
(legacy kernel uImage) with `flash_erase` + `nandwrite`. It never touches
|
||||
mtd0-5 (SPL/U-Boot/bootenv), holds a backup of each target before writing it,
|
||||
and reads every target back before reboot. Its `verify-live` checks SSH
|
||||
(kernel string), the HTTP marker on port 80, the API on port 4028, and the
|
||||
eth0 DHCP lease.
|
||||
|
||||
```sh
|
||||
alkane-cli afw verify BUNDLE.afw --allow-unsigned
|
||||
alkane-cli afw plan BUNDLE.afw --host 10.255.1.167
|
||||
alkane-cli afw preflight BUNDLE.afw --host 10.255.1.167
|
||||
alkane-cli afw install BUNDLE.afw --host 10.255.1.167 --dry-run
|
||||
alkane-cli afw install BUNDLE.afw --host 10.255.1.167 --confirm FLASH
|
||||
alkane-cli afw verify-live BUNDLE.afw --host 10.255.1.167
|
||||
alkane-cli afw restore --host 10.255.1.167 --held-backup p1.img --confirm FLASH
|
||||
```
|
||||
|
||||
For AM335x the same subcommands infer the board from the bundle; restore names
|
||||
the three held copies explicitly:
|
||||
|
||||
```sh
|
||||
alkane-cli afw plan BUNDLE.afw --host 10.255.1.64
|
||||
alkane-cli afw preflight BUNDLE.afw --host 10.255.1.64
|
||||
alkane-cli afw install BUNDLE.afw --host 10.255.1.64 --dry-run
|
||||
alkane-cli afw install BUNDLE.afw --host 10.255.1.64 --confirm FLASH
|
||||
alkane-cli afw verify-live BUNDLE.afw --host 10.255.1.64 --timeout 300
|
||||
alkane-cli afw restore --board am335x --host 10.255.1.64 \
|
||||
--held-backup mtd8.img --held-kernel mtd7.img --held-dtb mtd6.img --confirm FLASH
|
||||
```
|
||||
|
||||
On stock Bitmain CV1835 the SSH login is the unprivileged `miner` account; the
|
||||
toolkit obtains root through the stock update-daemon loopback channel, not a
|
||||
serial console. Credentials come only from `ALKANE_BOARD_PASSWORD` or
|
||||
`ALKANE_BOARD_PASSWORD_FILE`, or from `--password-file` / `--identity-file`.
|
||||
No credential value is printed. `--allow-unsigned` is bench-only; site use
|
||||
needs an Ed25519-signed bundle.
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
|
||||
@@ -6,5 +6,7 @@ license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
alkane-core = { path = "../alkane-core" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,226 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Fetch the latest alkane-os `.afw` release from a Gitea repository.
|
||||
//!
|
||||
//! GitHub is retired for this project; releases live on the self-hosted Gitea.
|
||||
//! This resolves `releases/latest`, picks the `.afw` asset for a board, and
|
||||
//! downloads it so the normal verify -> plan -> preflight -> install flow runs on
|
||||
//! it exactly as it would on a local file. TLS is required, so this shells out to
|
||||
//! `curl` (as the GUI already does) rather than the plaintext TCP path used for
|
||||
//! liveness checks.
|
||||
//!
|
||||
//! A private repo needs a token; it is read from the environment at run time
|
||||
//! (`ALKANE_RELEASE_TOKEN`, else `GITEA_TOKEN`) and passed to curl through a
|
||||
//! 0600 config file, never on the command line. No token is embedded or stored.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::Value;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum FetchError {
|
||||
#[error("curl failed: {0}")]
|
||||
Curl(String),
|
||||
#[error("release metadata did not parse: {0}")]
|
||||
Parse(String),
|
||||
#[error("no .afw asset for board {0} in the latest release")]
|
||||
NoAsset(String),
|
||||
#[error("io: {0}")]
|
||||
Io(String),
|
||||
}
|
||||
|
||||
/// Where releases come from. Defaults to the alkane-os repo on the self-hosted
|
||||
/// Gitea; the base URL and token are read from the environment.
|
||||
pub struct ReleaseSource {
|
||||
pub base_url: String,
|
||||
pub owner: String,
|
||||
pub repo: String,
|
||||
pub token: Option<String>,
|
||||
}
|
||||
|
||||
impl ReleaseSource {
|
||||
/// The alkane-os release source, honoring `ALKANE_RELEASE_BASE` and a token
|
||||
/// from `ALKANE_RELEASE_TOKEN` or `GITEA_TOKEN`.
|
||||
pub fn alkane_os() -> Self {
|
||||
let base_url = std::env::var("ALKANE_RELEASE_BASE")
|
||||
.ok()
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or_else(|| "https://gitea.bluefla.re".to_string());
|
||||
let token = std::env::var("ALKANE_RELEASE_TOKEN")
|
||||
.ok()
|
||||
.or_else(|| std::env::var("GITEA_TOKEN").ok())
|
||||
.filter(|t| !t.is_empty());
|
||||
Self {
|
||||
base_url,
|
||||
owner: "blueflare".to_string(),
|
||||
repo: "alkane-os".to_string(),
|
||||
token,
|
||||
}
|
||||
}
|
||||
|
||||
/// The releases list (newest first). Unlike `releases/latest`, this includes
|
||||
/// pre-releases, so an early/bench channel is still found by `--latest`.
|
||||
fn api_list(&self) -> String {
|
||||
format!(
|
||||
"{}/api/v1/repos/{}/{}/releases?limit=50",
|
||||
self.base_url.trim_end_matches('/'),
|
||||
self.owner,
|
||||
self.repo
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the first `.afw` asset for `board` across a newest-first list of
|
||||
/// releases. Returns (name, url).
|
||||
fn pick_asset(releases: &Value, board: &str) -> Option<(String, String)> {
|
||||
let needle = format!("-{board}-");
|
||||
for release in releases.as_array()? {
|
||||
let Some(assets) = release.get("assets").and_then(Value::as_array) else {
|
||||
continue;
|
||||
};
|
||||
for asset in assets {
|
||||
let name = asset.get("name").and_then(Value::as_str).unwrap_or("");
|
||||
if name.ends_with(".afw") && name.contains(&needle) {
|
||||
if let Some(url) = asset.get("browser_download_url").and_then(Value::as_str) {
|
||||
return Some((name.to_string(), url.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A temp curl `--config` file carrying the auth header, removed on drop so the
|
||||
/// token never lands in a process argument or a lingering file.
|
||||
struct TokenConfig {
|
||||
path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl TokenConfig {
|
||||
fn new(token: &Option<String>) -> Result<Self, FetchError> {
|
||||
let Some(token) = token else {
|
||||
return Ok(Self { path: None });
|
||||
};
|
||||
let path = std::env::temp_dir().join(format!("alkane-fetch-{}.cfg", std::process::id()));
|
||||
write_private(&path, &format!("header = \"Authorization: token {token}\"\n"))?;
|
||||
Ok(Self { path: Some(path) })
|
||||
}
|
||||
|
||||
fn apply(&self, cmd: &mut Command) {
|
||||
if let Some(path) = &self.path {
|
||||
cmd.arg("--config").arg(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TokenConfig {
|
||||
fn drop(&mut self) {
|
||||
if let Some(path) = &self.path {
|
||||
let _ = fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn write_private(path: &Path, contents: &str) -> Result<(), FetchError> {
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.map_err(|e| FetchError::Io(e.to_string()))?;
|
||||
file.write_all(contents.as_bytes()).map_err(|e| FetchError::Io(e.to_string()))
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn write_private(path: &Path, contents: &str) -> Result<(), FetchError> {
|
||||
fs::write(path, contents).map_err(|e| FetchError::Io(e.to_string()))
|
||||
}
|
||||
|
||||
fn curl_bytes(src: &ReleaseSource, url: &str) -> Result<Vec<u8>, FetchError> {
|
||||
let config = TokenConfig::new(&src.token)?;
|
||||
let mut cmd = Command::new("curl");
|
||||
cmd.arg("-fsSL").arg("--max-time").arg("120");
|
||||
config.apply(&mut cmd);
|
||||
cmd.arg(url);
|
||||
let out = cmd.output().map_err(|e| FetchError::Curl(e.to_string()))?;
|
||||
if !out.status.success() {
|
||||
return Err(FetchError::Curl(format!(
|
||||
"{} ({})",
|
||||
String::from_utf8_lossy(&out.stderr).trim(),
|
||||
out.status
|
||||
)));
|
||||
}
|
||||
Ok(out.stdout)
|
||||
}
|
||||
|
||||
fn curl_download(src: &ReleaseSource, url: &str, dest: &Path) -> Result<(), FetchError> {
|
||||
let config = TokenConfig::new(&src.token)?;
|
||||
let mut cmd = Command::new("curl");
|
||||
cmd.arg("-fsSL").arg("--max-time").arg("600").arg("-o").arg(dest);
|
||||
config.apply(&mut cmd);
|
||||
cmd.arg(url);
|
||||
let out = cmd.output().map_err(|e| FetchError::Curl(e.to_string()))?;
|
||||
if !out.status.success() {
|
||||
return Err(FetchError::Curl(format!(
|
||||
"{} ({})",
|
||||
String::from_utf8_lossy(&out.stderr).trim(),
|
||||
out.status
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve the latest release's `.afw` asset for `board`: returns (name, url).
|
||||
/// Scans the newest-first releases list (so a pre-release counts as latest).
|
||||
pub fn latest_afw_asset(src: &ReleaseSource, board: &str) -> Result<(String, String), FetchError> {
|
||||
let body = curl_bytes(src, &src.api_list())?;
|
||||
let releases: Value = serde_json::from_slice(&body).map_err(|e| FetchError::Parse(e.to_string()))?;
|
||||
pick_asset(&releases, board).ok_or_else(|| FetchError::NoAsset(board.to_string()))
|
||||
}
|
||||
|
||||
/// Download the latest `.afw` for `board` into `dest_dir`; returns its path.
|
||||
pub fn fetch_latest_afw(src: &ReleaseSource, board: &str, dest_dir: &Path) -> Result<PathBuf, FetchError> {
|
||||
let (name, url) = latest_afw_asset(src, board)?;
|
||||
fs::create_dir_all(dest_dir).map_err(|e| FetchError::Io(e.to_string()))?;
|
||||
let dest = dest_dir.join(&name);
|
||||
curl_download(src, &url, &dest)?;
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn source_defaults_to_alkane_os_on_gitea() {
|
||||
std::env::remove_var("ALKANE_RELEASE_BASE");
|
||||
let src = ReleaseSource::alkane_os();
|
||||
assert_eq!(src.owner, "blueflare");
|
||||
assert_eq!(src.repo, "alkane-os");
|
||||
assert!(src.api_list().contains("/api/v1/repos/blueflare/alkane-os/releases"));
|
||||
assert!(src.api_list().starts_with("https://gitea.bluefla.re"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pick_asset_takes_the_newest_matching_afw() {
|
||||
// Newest-first list of releases; the board's .afw in the first release wins.
|
||||
let releases = serde_json::json!([
|
||||
{"tag_name": "v0.1.0-bench1", "assets": [
|
||||
{"name": "SHA256SUMS", "browser_download_url": "u0"},
|
||||
{"name": "alkane-os-0.1.0-am335x-arm.afw", "browser_download_url": "u1"},
|
||||
{"name": "alkane-os-0.1.0-zynq-7010-armv7.afw", "browser_download_url": "u2"},
|
||||
]},
|
||||
{"tag_name": "v0.0.9", "assets": [
|
||||
{"name": "alkane-os-0.0.9-zynq-7010-armv7.afw", "browser_download_url": "old"},
|
||||
]},
|
||||
]);
|
||||
assert_eq!(pick_asset(&releases, "zynq-7010"), Some(("alkane-os-0.1.0-zynq-7010-armv7.afw".into(), "u2".into())));
|
||||
assert_eq!(pick_asset(&releases, "cv1835"), None);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Verify local firmware artifacts before an install path consumes them.
|
||||
|
||||
pub mod afw;
|
||||
pub mod fetch;
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashSet;
|
||||
use std::fs::File;
|
||||
|
||||
@@ -7,3 +7,5 @@ license.workspace = true
|
||||
[dependencies]
|
||||
alkane-core = { path = "../alkane-core" }
|
||||
alkane-artifacts = { path = "../alkane-artifacts" }
|
||||
alkane-flash = { path = "../alkane-flash" }
|
||||
serde_json.workspace = true
|
||||
|
||||
+1065
-18
File diff suppressed because it is too large
Load Diff
@@ -7,6 +7,7 @@ license.workspace = true
|
||||
[dependencies]
|
||||
alkane-core = { path = "../alkane-core" }
|
||||
alkane-artifacts = { path = "../alkane-artifacts" }
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
thiserror.workspace = true
|
||||
tempfile = "3"
|
||||
|
||||
@@ -0,0 +1,797 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Amlogic A113D / AXG (Antminer S21 Pro-class) board module: tier-2 network
|
||||
//! UPDATE of a board already running alkane. Our OS is staged as FILES in the
|
||||
//! nvdata UBI volume: alkane/{vmlinux.bin, devicetree.dtb, uramdisk.image.gz}.
|
||||
//! (The legacy vendor path name "anthillos" from AnthillOS is no longer used;
|
||||
//! our own bootcmd loads from alkane/.)
|
||||
//!
|
||||
//! The running alkane image exposes ONLY the nvdata region as an MTD (the board
|
||||
//! DT declares a single `nvdata` fixed-partition; the FIP bootloader and the
|
||||
//! stock boot/recovery/misc/config regions are deliberately undeclared, so they
|
||||
//! are never registered as MTD devices and cannot be written from Linux). This
|
||||
//! module attaches UBI to that one nvdata MTD, mounts the UBIFS volume, and
|
||||
//! overwrites the three files under alkane/. It performs no raw mtd0-5 write and
|
||||
//! never changes the bootloader: the brick-sensitive regions are physically
|
||||
//! unreachable.
|
||||
//!
|
||||
//! The first from-stock install (via the vendor toolkit, past the signed
|
||||
//! bootloader) is the dsh-owned path and is NOT this module. This is the
|
||||
//! repeatable alkane-to-alkane update.
|
||||
|
||||
use crate::md5::md5_hex;
|
||||
use crate::preflight::{classify, parse_digest};
|
||||
use crate::transport::{Remote, RemoteError};
|
||||
use alkane_artifacts::afw::{AfwImage, BootloaderPolicy, VerifiedAfw};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const BOARD: &str = "a113d";
|
||||
pub const ARCH: &str = "arm64";
|
||||
/// The UBI volume subdirectory our boot chain reads our OS files from. This is
|
||||
/// alkane's own name; the board's `ourbootcmd` loads from here.
|
||||
pub const ALKANE_DIR: &str = "alkane";
|
||||
/// nvdata UBI usable size; the three files together must fit (0xB900000).
|
||||
pub const NVDATA_USABLE: u64 = 0xB900000;
|
||||
/// The only MTD partition our DT exposes. mtd0-5 (FIP + stock boot) are not
|
||||
/// declared in the DT at all, so they are not MTD devices on a running image.
|
||||
pub const NVDATA_LABEL: &str = "nvdata";
|
||||
|
||||
/// Authoritative file targets: (image, on-board basename, ceiling, format).
|
||||
/// Written rootfs -> dtb -> kernel so a mid-write interruption never leaves a
|
||||
/// new rootfs beside an old kernel (the kernel file lands last).
|
||||
const TARGETS: [(&str, &str, u64, &str); 3] = [
|
||||
("rootfs", "uramdisk.image.gz", 0x6000000, "uimage"),
|
||||
("dtb", "devicetree.dtb", 0x100000, "fdt"),
|
||||
("kernel", "vmlinux.bin", 0x4000000, "arm64-image"),
|
||||
];
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum A113dPlanError {
|
||||
#[error("bundle is for {0}, not a113d")]
|
||||
WrongBoard(String),
|
||||
#[error("bundle arch is {0}, a113d needs arm64")]
|
||||
WrongArch(String),
|
||||
#[error("a113d requires bootloader_policy preserve (the FIP is never written)")]
|
||||
BootloaderPolicy,
|
||||
#[error("a113d bundle carries a bootloader/spl/fip/tpl member: {0}")]
|
||||
BootloaderMember(String),
|
||||
#[error("manifest is not an OS payload")]
|
||||
PayloadType,
|
||||
#[error("manifest marker is empty")]
|
||||
Marker,
|
||||
#[error("a113d must install exactly kernel, dtb and rootfs")]
|
||||
InstallCount,
|
||||
#[error("a113d is missing the {0} image")]
|
||||
MissingImage(String),
|
||||
#[error("a113d {image} format is {actual}, expected {expected}")]
|
||||
ImageFormat { image: String, actual: String, expected: &'static str },
|
||||
#[error("a113d {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
|
||||
ImageTooLarge { image: String, size: u64, ceiling: u64 },
|
||||
#[error("a113d images total {total} bytes, over the nvdata UBI (0x{usable:x})")]
|
||||
OverNvdata { total: u64, usable: u64 },
|
||||
#[error("a113d {image} is not an arm64 Image")]
|
||||
NotArm64 { image: String },
|
||||
#[error("a113d {image} is not an FDT")]
|
||||
NotFdt { image: String },
|
||||
#[error("a113d {image} is not a legacy uImage")]
|
||||
NotUimage { image: String },
|
||||
#[error("a113d refuses: preserved partition {0} (mtd0-5) carries an image")]
|
||||
PreservedCarriesImage(String),
|
||||
#[error("a113d refuses an unsafe destination for {image}: {dest}")]
|
||||
UnsafeDest { image: String, dest: String },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct A113dTarget {
|
||||
pub image_name: String,
|
||||
/// On-board basename inside the alkane directory (never a device path).
|
||||
pub dest: String,
|
||||
pub size: u64,
|
||||
pub data: Vec<u8>,
|
||||
pub expected_md5: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct A113dPlan {
|
||||
pub targets: Vec<A113dTarget>,
|
||||
pub marker: String,
|
||||
pub kernel_version: String,
|
||||
pub sdk_revision: String,
|
||||
pub os_revision: String,
|
||||
pub afw_sha256: String,
|
||||
pub min_free_bytes: u64,
|
||||
}
|
||||
|
||||
fn is_bootloaderish(image: &AfwImage) -> bool {
|
||||
let lowered = format!("{} {} {}", image.name, image.file, image.role).to_lowercase();
|
||||
image.role == "bootloader"
|
||||
|| lowered.contains("spl")
|
||||
|| lowered.contains("u-boot")
|
||||
|| lowered.contains("uboot")
|
||||
|| lowered.contains("fip")
|
||||
|| lowered.contains("tpl")
|
||||
}
|
||||
|
||||
/// A destination is safe only as a bare basename (no separators, no traversal,
|
||||
/// not a device path). This keeps every write inside the alkane/ directory.
|
||||
fn is_safe_dest(dest: &str) -> bool {
|
||||
!dest.is_empty()
|
||||
&& !dest.contains('/')
|
||||
&& !dest.contains("..")
|
||||
&& !dest.starts_with("/dev/")
|
||||
&& dest == dest.trim()
|
||||
}
|
||||
|
||||
impl A113dPlan {
|
||||
pub fn from_afw(afw: &VerifiedAfw) -> Result<Self, A113dPlanError> {
|
||||
let manifest = &afw.manifest;
|
||||
if manifest.board != BOARD {
|
||||
return Err(A113dPlanError::WrongBoard(manifest.board.clone()));
|
||||
}
|
||||
if manifest.arch != ARCH {
|
||||
return Err(A113dPlanError::WrongArch(manifest.arch.clone()));
|
||||
}
|
||||
if manifest.payload_type != "os" {
|
||||
return Err(A113dPlanError::PayloadType);
|
||||
}
|
||||
if manifest.bootloader_policy != BootloaderPolicy::Preserve {
|
||||
return Err(A113dPlanError::BootloaderPolicy);
|
||||
}
|
||||
if manifest.marker.is_empty() {
|
||||
return Err(A113dPlanError::Marker);
|
||||
}
|
||||
// FIP / bootloader members are never allowed - we reuse the board's.
|
||||
for image in &manifest.images {
|
||||
if is_bootloaderish(image) {
|
||||
return Err(A113dPlanError::BootloaderMember(image.file.clone()));
|
||||
}
|
||||
}
|
||||
// Defense in depth: only nvdata (mtd6) may carry an image; mtd0-5 preserved.
|
||||
for partition in &manifest.partitions {
|
||||
if partition.name != "nvdata" && partition.image.is_some() {
|
||||
return Err(A113dPlanError::PreservedCarriesImage(partition.name.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
let installs: Vec<&AfwImage> = manifest.images.iter().filter(|i| i.install).collect();
|
||||
if installs.len() != TARGETS.len() {
|
||||
return Err(A113dPlanError::InstallCount);
|
||||
}
|
||||
|
||||
let mut targets = Vec::with_capacity(TARGETS.len());
|
||||
let mut total = 0u64;
|
||||
for (image_name, dest, ceiling, expected_format) in TARGETS {
|
||||
let image = manifest
|
||||
.images
|
||||
.iter()
|
||||
.find(|i| i.name == image_name && i.install)
|
||||
.ok_or_else(|| A113dPlanError::MissingImage(image_name.to_owned()))?;
|
||||
if image.format != expected_format {
|
||||
return Err(A113dPlanError::ImageFormat {
|
||||
image: image_name.to_owned(),
|
||||
actual: image.format.clone(),
|
||||
expected: expected_format,
|
||||
});
|
||||
}
|
||||
if image.size > ceiling {
|
||||
return Err(A113dPlanError::ImageTooLarge {
|
||||
image: image_name.to_owned(),
|
||||
size: image.size,
|
||||
ceiling,
|
||||
});
|
||||
}
|
||||
if !is_safe_dest(dest) {
|
||||
return Err(A113dPlanError::UnsafeDest {
|
||||
image: image_name.to_owned(),
|
||||
dest: dest.to_owned(),
|
||||
});
|
||||
}
|
||||
let data = afw
|
||||
.image(image_name)
|
||||
.map(|(_, data)| data)
|
||||
.ok_or_else(|| A113dPlanError::MissingImage(image_name.to_owned()))?;
|
||||
match expected_format {
|
||||
"arm64-image" => {
|
||||
if !(data.len() >= 0x3C && data[0x38..0x3C] == *b"ARMd") {
|
||||
return Err(A113dPlanError::NotArm64 { image: image_name.to_owned() });
|
||||
}
|
||||
}
|
||||
"fdt" => {
|
||||
if !(data.len() >= 4 && data[0..4] == [0xd0, 0x0d, 0xfe, 0xed]) {
|
||||
return Err(A113dPlanError::NotFdt { image: image_name.to_owned() });
|
||||
}
|
||||
}
|
||||
"uimage" => {
|
||||
if !(data.len() >= 4 && data[0..4] == [0x27, 0x05, 0x19, 0x56]) {
|
||||
return Err(A113dPlanError::NotUimage { image: image_name.to_owned() });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
total += image.size;
|
||||
targets.push(A113dTarget {
|
||||
image_name: image_name.to_owned(),
|
||||
dest: dest.to_owned(),
|
||||
size: image.size,
|
||||
expected_md5: md5_hex(data),
|
||||
data: data.to_vec(),
|
||||
});
|
||||
}
|
||||
if total > NVDATA_USABLE {
|
||||
return Err(A113dPlanError::OverNvdata { total, usable: NVDATA_USABLE });
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
targets,
|
||||
marker: manifest.marker.clone(),
|
||||
kernel_version: manifest.kernel_version.clone(),
|
||||
sdk_revision: manifest.sdk_revision.clone(),
|
||||
os_revision: manifest.os_revision.clone(),
|
||||
afw_sha256: afw.archive_sha256.clone(),
|
||||
min_free_bytes: manifest
|
||||
.preflight
|
||||
.get("min_free_bytes")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(16 * 1024 * 1024),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = format!("board {BOARD} arch {ARCH}\n");
|
||||
out.push_str(
|
||||
"tier 2 update: attach UBI to the nvdata MTD, mount it, and overwrite the OS files \
|
||||
under alkane/; the FIP + stock boot/recovery/misc/config are not MTD devices at all, \
|
||||
so no raw NAND write is possible\n",
|
||||
);
|
||||
out.push_str("image format kernel=arm64-image, dtb=fdt, rootfs=uimage\n");
|
||||
for target in &self.targets {
|
||||
out.push_str(&format!(
|
||||
"write {} -> {ALKANE_DIR}/{} size {} B md5 {}\n",
|
||||
target.image_name, target.dest, target.size, target.expected_md5
|
||||
));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"marker {} kernel {} sdk {} os {}",
|
||||
self.marker,
|
||||
self.kernel_version,
|
||||
short(&self.sdk_revision),
|
||||
short(&self.os_revision),
|
||||
));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn short(rev: &str) -> &str {
|
||||
rev.get(..12).unwrap_or(rev)
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum A113dError {
|
||||
#[error("preflight failed:\n{0}")]
|
||||
Preflight(String),
|
||||
#[error("--confirm FLASH is required to write")]
|
||||
Confirm,
|
||||
#[error("the running image exposes no '{0}' MTD; it needs a NAND-enabled a113d kernel")]
|
||||
NoNvdataMtd(String),
|
||||
#[error("could not attach UBI to the nvdata MTD / find its volume")]
|
||||
UbiAttach,
|
||||
#[error("could not mount the nvdata UBIFS volume")]
|
||||
Mount,
|
||||
#[error("refusing an unsafe destination: {0}")]
|
||||
UnsafeDest(String),
|
||||
#[error("{0} staged md5 differs from the verified bundle")]
|
||||
StageMismatch(String),
|
||||
#[error("{0} read-back md5 mismatch; do not reboot")]
|
||||
Readback(String),
|
||||
#[error(transparent)]
|
||||
Remote(#[from] RemoteError),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct A113dCheck {
|
||||
pub name: String,
|
||||
pub ok: bool,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct A113dPreflight {
|
||||
pub host: String,
|
||||
pub checks: Vec<A113dCheck>,
|
||||
/// The nvdata MTD index (e.g. 0 for /dev/mtd0), when the running image
|
||||
/// exposes it. Used for `ubiattach -m <index>`.
|
||||
pub nvdata_mtd: Option<u32>,
|
||||
}
|
||||
|
||||
impl A113dPreflight {
|
||||
pub fn ok(&self) -> bool {
|
||||
self.checks.iter().all(|c| c.ok)
|
||||
}
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = format!("preflight {}\n", self.host);
|
||||
for c in &self.checks {
|
||||
out.push_str(&format!(
|
||||
"check {} {}: {}\n",
|
||||
c.name,
|
||||
if c.ok { "ok" } else { "FAIL" },
|
||||
c.detail
|
||||
));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"result {}",
|
||||
if self.ok() { "PASS" } else { "FAIL (do not write)" }
|
||||
));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse /proc/mtd for a partition labelled "nvdata" and return its mtd index.
|
||||
/// e.g. `mtd0: 0b900000 00020000 "nvdata"` -> Some(0).
|
||||
fn parse_nvdata_mtd(proc_mtd: &str) -> Option<u32> {
|
||||
for line in proc_mtd.lines() {
|
||||
let line = line.trim();
|
||||
if !line.starts_with("mtd") {
|
||||
continue;
|
||||
}
|
||||
let (dev, rest) = line.split_once(':')?;
|
||||
if rest.contains(&format!("\"{NVDATA_LABEL}\"")) {
|
||||
return dev.trim_start_matches("mtd").parse::<u32>().ok();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn preflight(
|
||||
plan: &A113dPlan,
|
||||
remote: &mut dyn Remote,
|
||||
host: &str,
|
||||
) -> Result<A113dPreflight, A113dError> {
|
||||
let mut checks = Vec::new();
|
||||
|
||||
let fingerprint = remote.user_command(
|
||||
"uname -r; echo __MODEL__; cat /proc/device-tree/model 2>/dev/null; echo; \
|
||||
echo __RELEASE__; cat /etc/os-release 2>/dev/null; cat /etc/alkane-release 2>/dev/null \
|
||||
|| true",
|
||||
Duration::from_secs(20),
|
||||
)?;
|
||||
let text = String::from_utf8_lossy(&fingerprint).into_owned();
|
||||
let mut it = text.split("__MODEL__");
|
||||
let kernel = it.next().unwrap_or("").trim().to_owned();
|
||||
let rest = it.next().unwrap_or("");
|
||||
let mut it2 = rest.split("__RELEASE__");
|
||||
let _model = it2.next().unwrap_or("");
|
||||
let release = it2.next().unwrap_or("");
|
||||
let source = classify(&kernel, release, &text);
|
||||
checks.push(A113dCheck {
|
||||
name: "source-os".to_owned(),
|
||||
ok: source == "alkane",
|
||||
detail: format!("{source} (update path requires alkane)"),
|
||||
});
|
||||
|
||||
let uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
|
||||
.trim()
|
||||
.to_owned();
|
||||
checks.push(A113dCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") });
|
||||
|
||||
let tools = remote.user_command(
|
||||
"for c in ubiattach ubidetach mount umount cp md5sum sync; do \
|
||||
command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done",
|
||||
Duration::from_secs(15),
|
||||
)?;
|
||||
let missing: Vec<String> = String::from_utf8_lossy(&tools)
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("missing:").map(str::to_owned))
|
||||
.collect();
|
||||
checks.push(A113dCheck {
|
||||
name: "commands".to_owned(),
|
||||
ok: missing.is_empty(),
|
||||
detail: if missing.is_empty() {
|
||||
"ubi/file tools present".to_owned()
|
||||
} else {
|
||||
format!("missing {}", missing.join(", "))
|
||||
},
|
||||
});
|
||||
|
||||
// The nvdata MTD must be exposed (NAND-enabled a113d kernel). If absent, the
|
||||
// running image cannot self-update - it needs the DT with the nvdata
|
||||
// fixed-partition. mtd0-5 are intentionally never exposed, so nvdata is the
|
||||
// ONLY mtd this board should ever present.
|
||||
let proc_mtd = String::from_utf8_lossy(
|
||||
&remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?,
|
||||
)
|
||||
.into_owned();
|
||||
let nvdata_mtd = parse_nvdata_mtd(&proc_mtd);
|
||||
checks.push(A113dCheck {
|
||||
name: "nvdata-mtd".to_owned(),
|
||||
ok: nvdata_mtd.is_some(),
|
||||
detail: match nvdata_mtd {
|
||||
Some(n) => format!("nvdata is /dev/mtd{n} (the only exposed MTD)"),
|
||||
None => format!("no 'nvdata' MTD exposed: {}", proc_mtd.replace('\n', " ")),
|
||||
},
|
||||
});
|
||||
|
||||
// Every destination is a bare basename - the structural brick guard.
|
||||
let dests_safe = plan.targets.iter().all(|t| is_safe_dest(&t.dest));
|
||||
checks.push(A113dCheck {
|
||||
name: "file-only".to_owned(),
|
||||
ok: dests_safe,
|
||||
detail: format!("all writes are files under {ALKANE_DIR}/ on the nvdata UBI"),
|
||||
});
|
||||
|
||||
Ok(A113dPreflight { host: host.to_owned(), checks, nvdata_mtd })
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct A113dInstallOptions {
|
||||
pub dry_run: bool,
|
||||
pub confirm: Option<String>,
|
||||
pub no_reboot: bool,
|
||||
pub backup_dir: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct A113dBackup {
|
||||
pub image_name: String,
|
||||
pub dest: String,
|
||||
pub path: Option<PathBuf>,
|
||||
pub md5: Option<String>,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct A113dReceipt {
|
||||
pub volume: String,
|
||||
pub backups: Vec<A113dBackup>,
|
||||
pub rebooted: bool,
|
||||
}
|
||||
|
||||
pub enum A113dOutcome {
|
||||
DryRun(Box<A113dPreflight>),
|
||||
Installed(A113dReceipt),
|
||||
}
|
||||
|
||||
const MNT: &str = "/tmp/.alkane-nvdata";
|
||||
|
||||
/// Attach UBI to the nvdata MTD and mount its single user volume read-write.
|
||||
/// Returns (ubi device number, volume name). The volume name is DISCOVERED, never
|
||||
/// assumed (vendor histories leave different names: umc_os_rootfs, nvdada_log,
|
||||
/// overlay, ...).
|
||||
fn attach_and_mount(
|
||||
remote: &mut dyn Remote,
|
||||
nvdata_mtd: u32,
|
||||
) -> Result<String, A113dError> {
|
||||
// Attach (idempotent: if ubi0 already exists, reuse it).
|
||||
let _ = remote.root_command(
|
||||
&format!(
|
||||
"if [ ! -d /sys/class/ubi/ubi0 ]; then ubiattach -m {nvdata_mtd} -d 0 >/dev/null 2>&1; fi"
|
||||
),
|
||||
Duration::from_secs(60),
|
||||
)?;
|
||||
// Discover the first user volume name under ubi0.
|
||||
let name = String::from_utf8_lossy(&remote.root_command(
|
||||
"for n in /sys/class/ubi/ubi0_*/name; do [ -f \"$n\" ] && cat \"$n\" && break; done",
|
||||
Duration::from_secs(20),
|
||||
)?)
|
||||
.trim()
|
||||
.to_owned();
|
||||
if name.is_empty() {
|
||||
return Err(A113dError::UbiAttach);
|
||||
}
|
||||
// Mount it read-write.
|
||||
remote.root_command(
|
||||
&format!("mkdir -p {MNT} && mount -t ubifs ubi0:{name} {MNT}"),
|
||||
Duration::from_secs(60),
|
||||
)?;
|
||||
// Confirm the mount actually took.
|
||||
let mounted =
|
||||
remote.user_command(&format!("mount | grep -c ' {MNT} '"), Duration::from_secs(20))?;
|
||||
if String::from_utf8_lossy(&mounted).trim() == "0" {
|
||||
return Err(A113dError::Mount);
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
fn unmount(remote: &mut dyn Remote) {
|
||||
let _ = remote.root_command(
|
||||
&format!("sync; umount {MNT} 2>/dev/null; ubidetach -d 0 2>/dev/null; rmdir {MNT} 2>/dev/null"),
|
||||
Duration::from_secs(60),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn install(
|
||||
plan: &A113dPlan,
|
||||
remote: &mut dyn Remote,
|
||||
options: &A113dInstallOptions,
|
||||
host: &str,
|
||||
) -> Result<A113dOutcome, A113dError> {
|
||||
let report = preflight(plan, remote, host)?;
|
||||
if !report.ok() {
|
||||
return Err(A113dError::Preflight(report.render()));
|
||||
}
|
||||
if options.dry_run {
|
||||
return Ok(A113dOutcome::DryRun(Box::new(report)));
|
||||
}
|
||||
if options.confirm.as_deref() != Some("FLASH") {
|
||||
return Err(A113dError::Confirm);
|
||||
}
|
||||
let nvdata_mtd = report
|
||||
.nvdata_mtd
|
||||
.ok_or_else(|| A113dError::NoNvdataMtd(NVDATA_LABEL.to_owned()))?;
|
||||
|
||||
fs::create_dir_all(&options.backup_dir)?;
|
||||
let epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
|
||||
|
||||
let volume = attach_and_mount(remote, nvdata_mtd)?;
|
||||
let alkane_dir = format!("{MNT}/{ALKANE_DIR}");
|
||||
let _ = remote.root_command(&format!("mkdir -p {alkane_dir}"), Duration::from_secs(20))?;
|
||||
|
||||
let mut backups = Vec::new();
|
||||
let result = (|| -> Result<(), A113dError> {
|
||||
for target in &plan.targets {
|
||||
// Structural guard at the point of writing: a bare basename only.
|
||||
if !is_safe_dest(&target.dest) {
|
||||
return Err(A113dError::UnsafeDest(target.dest.clone()));
|
||||
}
|
||||
let name = &target.image_name;
|
||||
let dest_path = format!("{alkane_dir}/{}", target.dest);
|
||||
|
||||
// Back up the existing file, if present.
|
||||
let have = remote.user_command(
|
||||
&format!("test -f {dest_path} && echo __YES__"),
|
||||
Duration::from_secs(15),
|
||||
)?;
|
||||
if String::from_utf8_lossy(&have).contains("__YES__") {
|
||||
let local = options.backup_dir.join(format!("{}-{epoch}.bak", target.dest));
|
||||
remote.pull(&dest_path, &local, Duration::from_secs(300))?;
|
||||
let data = fs::read(&local)?;
|
||||
backups.push(A113dBackup {
|
||||
image_name: name.clone(),
|
||||
dest: target.dest.clone(),
|
||||
md5: Some(md5_hex(&data)),
|
||||
size: data.len() as u64,
|
||||
path: Some(local),
|
||||
});
|
||||
} else {
|
||||
backups.push(A113dBackup {
|
||||
image_name: name.clone(),
|
||||
dest: target.dest.clone(),
|
||||
md5: None,
|
||||
size: 0,
|
||||
path: None,
|
||||
});
|
||||
}
|
||||
|
||||
// Stage the verified payload and prove its remote md5 before copying.
|
||||
let mut staged = tempfile::NamedTempFile::new()?;
|
||||
staged.write_all(&target.data)?;
|
||||
staged.flush()?;
|
||||
let remote_stage = format!("/tmp/.alkane-a113d-{name}.img");
|
||||
remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?;
|
||||
let staged_md5 = parse_digest(
|
||||
&remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?,
|
||||
32,
|
||||
)
|
||||
.unwrap_or_default();
|
||||
if staged_md5 != target.expected_md5 {
|
||||
let _ =
|
||||
remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
|
||||
return Err(A113dError::StageMismatch(name.clone()));
|
||||
}
|
||||
|
||||
// Copy into the UBIFS volume (file write only), then sync.
|
||||
remote.root_command(
|
||||
&format!("cp -f {remote_stage} {dest_path} && sync"),
|
||||
Duration::from_secs(300),
|
||||
)?;
|
||||
|
||||
// Read back the copied file and compare md5.
|
||||
let readback = parse_digest(
|
||||
&remote.root_command(&format!("md5sum {dest_path}"), Duration::from_secs(60))?,
|
||||
32,
|
||||
)
|
||||
.unwrap_or_default();
|
||||
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
|
||||
if readback != target.expected_md5 {
|
||||
return Err(A113dError::Readback(name.clone()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
// Always unmount/detach, success or failure, before returning or rebooting.
|
||||
unmount(remote);
|
||||
result?;
|
||||
|
||||
let rebooted = if options.no_reboot {
|
||||
false
|
||||
} else {
|
||||
remote.reboot()?;
|
||||
true
|
||||
};
|
||||
Ok(A113dOutcome::Installed(A113dReceipt { volume, backups, rebooted }))
|
||||
}
|
||||
|
||||
pub fn owns_board(board: &str) -> bool {
|
||||
board == BOARD
|
||||
}
|
||||
|
||||
/// True when no plan target would ever name a preserved raw partition. Used by
|
||||
/// tests to assert the structural guard holds for the fixed TARGETS table.
|
||||
pub fn no_raw_device_targets(plan: &A113dPlan) -> bool {
|
||||
plan.targets.iter().all(|t| is_safe_dest(&t.dest))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use alkane_artifacts::afw::{AfwManifest, AfwMember};
|
||||
use serde_json::json;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const REV: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||
|
||||
fn arm64_image(payload: &[u8]) -> Vec<u8> {
|
||||
let mut b = vec![0u8; 64];
|
||||
b[0x38..0x3C].copy_from_slice(b"ARMd");
|
||||
b.extend_from_slice(payload);
|
||||
b
|
||||
}
|
||||
|
||||
fn dtb() -> Vec<u8> {
|
||||
let mut b = vec![0u8; 2048];
|
||||
b[0..4].copy_from_slice(&[0xd0, 0x0d, 0xfe, 0xed]);
|
||||
b
|
||||
}
|
||||
|
||||
fn uramdisk() -> Vec<u8> {
|
||||
let mut b = vec![0u8; 64];
|
||||
b[0..4].copy_from_slice(&[0x27, 0x05, 0x19, 0x56]);
|
||||
b
|
||||
}
|
||||
|
||||
fn afw_with(
|
||||
kernel: Vec<u8>,
|
||||
dtb: Vec<u8>,
|
||||
rootfs: Vec<u8>,
|
||||
partitions: serde_json::Value,
|
||||
) -> VerifiedAfw {
|
||||
let image = |name: &str, file: &str, role: &str, fmt: &str, data: &[u8]| {
|
||||
let sha: String = Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect();
|
||||
json!({"name": name, "file": file, "role": role, "format": fmt,
|
||||
"size": data.len(), "sha256": sha, "partition": "nvdata", "install": true})
|
||||
};
|
||||
let value = json!({
|
||||
"schema": 2, "format": "afw", "board": "a113d", "arch": "arm64",
|
||||
"version": "0.1.0", "build_date": "2026-11-06T00:00:00Z",
|
||||
"sdk_revision": REV, "os_revision": REV, "payload_type": "os",
|
||||
"bootloader_policy": "preserve",
|
||||
"signature": {"type": "unsigned", "member": null, "public_key_hex": null},
|
||||
"partitions": partitions,
|
||||
"images": [
|
||||
image("kernel", "payload/vmlinux.bin", "kernel", "arm64-image", &kernel),
|
||||
image("dtb", "payload/devicetree.dtb", "dtb", "fdt", &dtb),
|
||||
image("rootfs", "payload/uramdisk.image.gz", "rootfs", "uimage", &rootfs),
|
||||
],
|
||||
"boot_switch": {}, "preflight": {"min_free_bytes": 16777216},
|
||||
"recovery": {}, "marker": "Alkane", "kernel_version": "6.18.48"
|
||||
});
|
||||
let manifest: AfwManifest = serde_json::from_value(value).unwrap();
|
||||
VerifiedAfw {
|
||||
manifest,
|
||||
members: vec![
|
||||
AfwMember { name: "payload/vmlinux.bin".to_owned(), data: kernel },
|
||||
AfwMember { name: "payload/devicetree.dtb".to_owned(), data: dtb },
|
||||
AfwMember { name: "payload/uramdisk.image.gz".to_owned(), data: rootfs },
|
||||
],
|
||||
manifest_sha256: "0".repeat(64),
|
||||
archive_sha256: "0".repeat(64),
|
||||
}
|
||||
}
|
||||
|
||||
fn preserved_partitions() -> serde_json::Value {
|
||||
json!([
|
||||
{"name":"bootloader","device":"/dev/mtd0","offset":0,"size":2097152,
|
||||
"secure":true,"boot_critical":true,"write_order":0,"image":null},
|
||||
{"name":"nvdata","device":"/dev/mtd6","offset":74448896,"size":193986560,
|
||||
"secure":false,"boot_critical":true,"write_order":1,"image":"kernel"}
|
||||
])
|
||||
}
|
||||
|
||||
fn good() -> VerifiedAfw {
|
||||
afw_with(arm64_image(b"k"), dtb(), uramdisk(), preserved_partitions())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_a_good_plan_as_file_copies() {
|
||||
let plan = A113dPlan::from_afw(&good()).unwrap();
|
||||
assert_eq!(plan.targets.len(), 3);
|
||||
// write order rootfs, dtb, kernel (kernel file lands last)
|
||||
assert_eq!(plan.targets[0].image_name, "rootfs");
|
||||
assert_eq!(plan.targets[2].image_name, "kernel");
|
||||
assert!(no_raw_device_targets(&plan));
|
||||
for t in &plan.targets {
|
||||
assert!(!t.dest.contains('/'), "{} has a path, not a basename", t.image_name);
|
||||
}
|
||||
assert!(plan.render().contains("alkane/"));
|
||||
assert!(plan.render().contains("no raw NAND write is possible"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_non_arm64_kernel() {
|
||||
let r = A113dPlan::from_afw(&afw_with(vec![0u8; 64], dtb(), uramdisk(), preserved_partitions()));
|
||||
assert!(matches!(r, Err(A113dPlanError::NotArm64 { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_an_oversize_kernel() {
|
||||
let big = arm64_image(&vec![0u8; 0x4000000]);
|
||||
let r = A113dPlan::from_afw(&afw_with(big, dtb(), uramdisk(), preserved_partitions()));
|
||||
assert!(matches!(r, Err(A113dPlanError::ImageTooLarge { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_fip_member() {
|
||||
let mut v = good();
|
||||
v.manifest.images[0].role = "bootloader".to_owned();
|
||||
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::BootloaderMember(_))));
|
||||
let mut v = good();
|
||||
v.manifest.images[1].file = "payload/fip.bin".to_owned();
|
||||
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::BootloaderMember(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_preserved_partition_carrying_an_image() {
|
||||
let partitions = json!([
|
||||
{"name":"bootloader","device":"/dev/mtd0","offset":0,"size":2097152,
|
||||
"secure":true,"boot_critical":true,"write_order":0,"image":"kernel"},
|
||||
{"name":"nvdata","device":"/dev/mtd6","offset":74448896,"size":193986560,
|
||||
"secure":false,"boot_critical":true,"write_order":1,"image":"kernel"}
|
||||
]);
|
||||
let v = afw_with(arm64_image(b"k"), dtb(), uramdisk(), partitions);
|
||||
assert!(matches!(
|
||||
A113dPlan::from_afw(&v),
|
||||
Err(A113dPlanError::PreservedCarriesImage(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_board_and_arch_are_refused() {
|
||||
let mut v = good();
|
||||
v.manifest.board = "zynq-7010".to_owned();
|
||||
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::WrongBoard(_))));
|
||||
let mut v = good();
|
||||
v.manifest.arch = "armv7".to_owned();
|
||||
assert!(matches!(A113dPlan::from_afw(&v), Err(A113dPlanError::WrongArch(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_target_is_a_basename_never_a_device() {
|
||||
for (image, dest, _ceiling, _fmt) in TARGETS {
|
||||
assert!(is_safe_dest(dest), "{image} dest {dest} is not a safe basename");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsafe_dest_is_rejected_by_guard() {
|
||||
assert!(!is_safe_dest("/dev/mtd0"));
|
||||
assert!(!is_safe_dest("../escape"));
|
||||
assert!(!is_safe_dest("sub/dir/file"));
|
||||
assert!(is_safe_dest("vmlinux.bin"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_the_nvdata_mtd_index() {
|
||||
let proc_mtd = "dev: size erasesize name\n\
|
||||
mtd0: 0b900000 00020000 \"nvdata\"\n";
|
||||
assert_eq!(parse_nvdata_mtd(proc_mtd), Some(0));
|
||||
// No nvdata line -> None (the no-NAND running image).
|
||||
assert_eq!(parse_nvdata_mtd("dev: size erasesize name\n"), None);
|
||||
// Different index is honored.
|
||||
assert_eq!(parse_nvdata_mtd("mtd3: 0b900000 00020000 \"nvdata\"\n"), Some(3));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,406 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! CV1835 board module: the only write is the 16 MiB p1 FIT.
|
||||
//!
|
||||
//! The vendor boot0, BL2, BL31 and U-Boot chain is preserved. The board plan is
|
||||
//! read from the verified `.afw` manifest, not guessed at runtime.
|
||||
|
||||
use crate::md5::md5_hex;
|
||||
use alkane_artifacts::afw::{
|
||||
AfwImage, AfwManifest, AfwPartition, BootloaderPolicy, VerifiedAfw, CV1835_P1_SIZE,
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const BOARD: &str = "cv1835";
|
||||
pub const ARCH: &str = "arm64";
|
||||
pub const P1_DEVICE: &str = "/dev/mmcblk0p1";
|
||||
pub const MARKER: &str = "CVBOOT";
|
||||
pub const UPDATE_DAEMON_PORT: u16 = 12887;
|
||||
pub const GOLDEN_LBA_BYTES: u64 = 0x300000 * 512;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CvPlanError {
|
||||
#[error("bundle is for {0}, not cv1835")]
|
||||
WrongBoard(String),
|
||||
#[error("bundle arch is {0}, cv1835 needs arm64")]
|
||||
WrongArch(String),
|
||||
#[error("cv1835 requires bootloader_policy preserve")]
|
||||
BootloaderPolicy,
|
||||
#[error("cv1835 bundle carries a bootloader member")]
|
||||
BootloaderMember,
|
||||
#[error("cv1835 bundle must install exactly p1")]
|
||||
MissingP1,
|
||||
#[error("cv1835 p1 is {0} bytes, not the 16 MiB padded FIT")]
|
||||
P1Size(u64),
|
||||
#[error("cv1835 p1 partition is not /dev/mmcblk0p1")]
|
||||
P1Device,
|
||||
#[error("cv1835 p1 partition must be 16 MiB, non-secure and written once")]
|
||||
P1Geometry,
|
||||
#[error("cv1835 p1 is not a bootable FIT: {0}")]
|
||||
Fit(String),
|
||||
#[error("manifest marker is empty")]
|
||||
Marker,
|
||||
#[error("manifest kernel_version is empty")]
|
||||
KernelVersion,
|
||||
#[error("manifest is not an OS payload")]
|
||||
PayloadType,
|
||||
#[error("manifest preflight is missing {0}")]
|
||||
Preflight(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Cv1835Plan {
|
||||
pub image: AfwImage,
|
||||
pub data: Vec<u8>,
|
||||
pub partition: AfwPartition,
|
||||
pub expected_md5: String,
|
||||
pub expected_sha256: String,
|
||||
pub marker: String,
|
||||
pub kernel_version: String,
|
||||
pub sdk_revision: String,
|
||||
pub os_revision: String,
|
||||
pub source_os: Vec<String>,
|
||||
pub required_commands: Vec<String>,
|
||||
pub min_free_bytes: u64,
|
||||
pub golden_lba_bytes: u64,
|
||||
}
|
||||
|
||||
impl Cv1835Plan {
|
||||
pub fn from_afw(afw: &VerifiedAfw) -> Result<Self, CvPlanError> {
|
||||
let manifest = &afw.manifest;
|
||||
if manifest.board != BOARD {
|
||||
return Err(CvPlanError::WrongBoard(manifest.board.clone()));
|
||||
}
|
||||
if manifest.arch != ARCH {
|
||||
return Err(CvPlanError::WrongArch(manifest.arch.clone()));
|
||||
}
|
||||
if manifest.payload_type != "os" {
|
||||
return Err(CvPlanError::PayloadType);
|
||||
}
|
||||
if manifest.bootloader_policy != BootloaderPolicy::Preserve {
|
||||
return Err(CvPlanError::BootloaderPolicy);
|
||||
}
|
||||
if manifest
|
||||
.images
|
||||
.iter()
|
||||
.any(|image| image.role == "bootloader")
|
||||
{
|
||||
return Err(CvPlanError::BootloaderMember);
|
||||
}
|
||||
if manifest.marker.is_empty() {
|
||||
return Err(CvPlanError::Marker);
|
||||
}
|
||||
if manifest.kernel_version.is_empty() {
|
||||
return Err(CvPlanError::KernelVersion);
|
||||
}
|
||||
|
||||
let install: Vec<&AfwImage> = manifest
|
||||
.images
|
||||
.iter()
|
||||
.filter(|image| image.install)
|
||||
.collect();
|
||||
if install.len() != 1 || install[0].name != "p1" {
|
||||
return Err(CvPlanError::MissingP1);
|
||||
}
|
||||
let image = install[0].clone();
|
||||
if image.format != "fit" {
|
||||
return Err(CvPlanError::Fit("format is not fit".to_owned()));
|
||||
}
|
||||
if image.size != CV1835_P1_SIZE {
|
||||
return Err(CvPlanError::P1Size(image.size));
|
||||
}
|
||||
let (_, data) = afw.install_image().ok_or(CvPlanError::MissingP1)?;
|
||||
if !data.starts_with(b"\xd0\x0d\xfe\xed") {
|
||||
return Err(CvPlanError::Fit("missing FDT/FIT magic".to_owned()));
|
||||
}
|
||||
if !contains(data, b"config@cv1835_miner_emmc") {
|
||||
return Err(CvPlanError::Fit(
|
||||
"missing config@cv1835_miner_emmc".to_owned(),
|
||||
));
|
||||
}
|
||||
if contains(data, b"signature@") {
|
||||
return Err(CvPlanError::Fit("carries signature@ nodes".to_owned()));
|
||||
}
|
||||
|
||||
let partition = manifest
|
||||
.partitions
|
||||
.iter()
|
||||
.find(|part| part.name == "p1")
|
||||
.ok_or(CvPlanError::P1Device)?
|
||||
.clone();
|
||||
if partition.device != P1_DEVICE {
|
||||
return Err(CvPlanError::P1Device);
|
||||
}
|
||||
if partition.size != CV1835_P1_SIZE
|
||||
|| partition.secure
|
||||
|| !partition.boot_critical
|
||||
|| partition.write_order != 1
|
||||
{
|
||||
return Err(CvPlanError::P1Geometry);
|
||||
}
|
||||
if manifest
|
||||
.partitions
|
||||
.iter()
|
||||
.any(|part| part.write_order > 0 && part.name != "p1")
|
||||
{
|
||||
return Err(CvPlanError::MissingP1);
|
||||
}
|
||||
|
||||
let source_os = json_strings(&manifest.preflight, "source_os");
|
||||
let required_commands = json_strings(&manifest.preflight, "required_commands");
|
||||
let min_free_bytes = manifest
|
||||
.preflight
|
||||
.get("min_free_bytes")
|
||||
.and_then(|value| value.as_u64())
|
||||
.unwrap_or(32 * 1024 * 1024);
|
||||
let golden_lba_bytes = manifest
|
||||
.recovery
|
||||
.get("golden_lba_bytes")
|
||||
.and_then(|value| value.as_u64())
|
||||
.unwrap_or(GOLDEN_LBA_BYTES);
|
||||
|
||||
Ok(Self {
|
||||
expected_md5: md5_hex(data),
|
||||
expected_sha256: image.sha256.clone(),
|
||||
image,
|
||||
data: data.to_vec(),
|
||||
partition,
|
||||
marker: manifest.marker.clone(),
|
||||
kernel_version: manifest.kernel_version.clone(),
|
||||
sdk_revision: manifest.sdk_revision.clone(),
|
||||
os_revision: manifest.os_revision.clone(),
|
||||
source_os,
|
||||
required_commands,
|
||||
min_free_bytes,
|
||||
golden_lba_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
format!(
|
||||
"board cv1835 arch arm64\n\
|
||||
partition {} {} {} B secure=false boot_critical=true write_order={}\n\
|
||||
image {} {} {} B sha256 {}\n\
|
||||
image md5 {}\n\
|
||||
bootloader preserve (vendor boot0/BL2/BL31/U-Boot kept)\n\
|
||||
boot switch partition-overwrite (p1 is the switch)\n\
|
||||
marker {} kernel {} sdk {} os {}",
|
||||
self.partition.name,
|
||||
self.partition.device,
|
||||
self.partition.size,
|
||||
self.partition.write_order,
|
||||
self.image.name,
|
||||
self.image.file,
|
||||
self.image.size,
|
||||
self.image.sha256,
|
||||
self.expected_md5,
|
||||
self.marker,
|
||||
self.kernel_version,
|
||||
short_revision(&self.sdk_revision),
|
||||
short_revision(&self.os_revision),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn short_revision(revision: &str) -> &str {
|
||||
revision.get(..12).unwrap_or(revision)
|
||||
}
|
||||
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
haystack
|
||||
.windows(needle.len())
|
||||
.any(|window| window == needle)
|
||||
}
|
||||
|
||||
fn json_strings(value: &serde_json::Value, key: &str) -> Vec<String> {
|
||||
value
|
||||
.get(key)
|
||||
.and_then(|item| item.as_array())
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|item| item.as_str().map(str::to_owned))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn manifest_from_json(value: serde_json::Value) -> Result<AfwManifest, serde_json::Error> {
|
||||
serde_json::from_value(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use alkane_artifacts::afw::AfwMember;
|
||||
use serde_json::json;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const P1: usize = CV1835_P1_SIZE as usize;
|
||||
const REV: &str = "0000000000000000000000000000000000000000";
|
||||
|
||||
fn sha_hex(data: &[u8]) -> String {
|
||||
Sha256::digest(data)
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
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 manifest_value(p1: &[u8]) -> serde_json::Value {
|
||||
json!({
|
||||
"schema": 2,
|
||||
"format": "afw",
|
||||
"board": "cv1835",
|
||||
"arch": "arm64",
|
||||
"version": "0.1.0",
|
||||
"build_date": "2026-11-04T00:00:00Z",
|
||||
"sdk_revision": REV,
|
||||
"os_revision": REV,
|
||||
"payload_type": "os",
|
||||
"bootloader_policy": "preserve",
|
||||
"signature": {"type": "unsigned", "member": null, "public_key_hex": null},
|
||||
"partitions": [
|
||||
{"name": "p1", "device": "/dev/mmcblk0p1", "offset": 0,
|
||||
"size": CV1835_P1_SIZE, "secure": false, "boot_critical": true,
|
||||
"write_order": 1, "image": "p1"},
|
||||
{"name": "boot0", "device": "/dev/mmcblk0boot0", "offset": 0,
|
||||
"size": 4194304, "secure": true, "boot_critical": true,
|
||||
"write_order": 0, "image": null}
|
||||
],
|
||||
"images": [
|
||||
{"name": "p1", "file": "payload/p1.fit", "role": "boot",
|
||||
"format": "fit", "size": p1.len(),
|
||||
"sha256": sha_hex(p1),
|
||||
"partition": "p1", "install": true}
|
||||
],
|
||||
"boot_switch": {"method": "partition-overwrite"},
|
||||
"preflight": {"required_commands": ["dd", "md5sum", "sync"],
|
||||
"source_os": ["stock-bitmain", "vnish", "braiins", "ouros", "alkane"],
|
||||
"min_free_bytes": 33554432},
|
||||
"recovery": {"network": "afw restore", "golden_lba_bytes": GOLDEN_LBA_BYTES},
|
||||
"marker": "CVBOOT",
|
||||
"kernel_version": "6.18.48"
|
||||
})
|
||||
}
|
||||
|
||||
fn afw(p1: &[u8]) -> VerifiedAfw {
|
||||
let manifest = manifest_from_json(manifest_value(p1)).unwrap();
|
||||
VerifiedAfw {
|
||||
manifest,
|
||||
members: vec![AfwMember {
|
||||
name: "payload/p1.fit".to_owned(),
|
||||
data: p1.to_vec(),
|
||||
}],
|
||||
manifest_sha256: "0".repeat(64),
|
||||
archive_sha256: "0".repeat(64),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_the_cv_plan() {
|
||||
let data = p1_image();
|
||||
let plan = Cv1835Plan::from_afw(&afw(&data)).unwrap();
|
||||
assert_eq!(plan.partition.device, "/dev/mmcblk0p1");
|
||||
assert_eq!(plan.image.size, CV1835_P1_SIZE);
|
||||
assert_eq!(plan.marker, "CVBOOT");
|
||||
assert!(plan
|
||||
.render()
|
||||
.contains("partition p1 /dev/mmcblk0p1 16777216"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_bundle_for_another_board() {
|
||||
let data = p1_image();
|
||||
let mut verified = afw(&data);
|
||||
verified.manifest.board = "zynq-7010".to_owned();
|
||||
assert!(matches!(
|
||||
Cv1835Plan::from_afw(&verified),
|
||||
Err(CvPlanError::WrongBoard(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_include_bootloader_policy() {
|
||||
let data = p1_image();
|
||||
let mut verified = afw(&data);
|
||||
verified.manifest.bootloader_policy = BootloaderPolicy::Include;
|
||||
assert!(matches!(
|
||||
Cv1835Plan::from_afw(&verified),
|
||||
Err(CvPlanError::BootloaderPolicy)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_bootloader_member() {
|
||||
let data = p1_image();
|
||||
let mut verified = afw(&data);
|
||||
verified.manifest.images.push(AfwImage {
|
||||
name: "u-boot".to_owned(),
|
||||
file: "payload/u-boot.img".to_owned(),
|
||||
role: "bootloader".to_owned(),
|
||||
format: "uimage".to_owned(),
|
||||
size: 4,
|
||||
sha256: "0".repeat(64),
|
||||
partition: None,
|
||||
install: false,
|
||||
});
|
||||
assert!(matches!(
|
||||
Cv1835Plan::from_afw(&verified),
|
||||
Err(CvPlanError::BootloaderMember)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_short_p1() {
|
||||
let data = vec![0_u8; 1024];
|
||||
let verified = afw(&data);
|
||||
assert!(matches!(
|
||||
Cv1835Plan::from_afw(&verified),
|
||||
Err(CvPlanError::P1Size(1024))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_secure_p1() {
|
||||
let data = p1_image();
|
||||
let mut verified = afw(&data);
|
||||
verified.manifest.partitions[0].secure = true;
|
||||
assert!(matches!(
|
||||
Cv1835Plan::from_afw(&verified),
|
||||
Err(CvPlanError::P1Geometry)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_wrong_device() {
|
||||
let data = p1_image();
|
||||
let mut verified = afw(&data);
|
||||
verified.manifest.partitions[0].device = "/dev/mmcblk0p3".to_owned();
|
||||
assert!(matches!(
|
||||
Cv1835Plan::from_afw(&verified),
|
||||
Err(CvPlanError::P1Device)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_fit_without_the_board_config() {
|
||||
let mut data = p1_image();
|
||||
for byte in data.iter_mut() {
|
||||
if *byte == b'c' {
|
||||
*byte = b'x';
|
||||
}
|
||||
}
|
||||
let verified = afw(&data);
|
||||
assert!(matches!(
|
||||
Cv1835Plan::from_afw(&verified),
|
||||
Err(CvPlanError::Fit(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Board modules. Each module validates the verified manifest for its family
|
||||
//! and exposes the exact write plan the installer follows.
|
||||
|
||||
pub mod a113d;
|
||||
pub mod am335x;
|
||||
pub mod cv1835;
|
||||
pub mod zynq;
|
||||
@@ -0,0 +1,606 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Zynq-7010 board module: tier-2 network UPDATE of a board already running
|
||||
//! alkane (installed from stock via the dsh-owned RSA-gate path - that first
|
||||
//! install is not this module). It writes our kernel (zImage) into the mtd0
|
||||
//! kernel slot, the dtb, and the rootfs into mtd1, and PRESERVES BOOT.bin
|
||||
//! (FSBL + FPGA bitstream + stock U-Boot) at the front of mtd0.
|
||||
//!
|
||||
//! The write offsets are DEVICE-RELATIVE and authoritative here (like the
|
||||
//! am335x MTD_MAP): dtb at 0x1a00000 and kernel at 0x2000000 within /dev/mtd0,
|
||||
//! rootfs at 0 within /dev/mtd1 - the layout the on-board stock U-Boot
|
||||
//! `nandboot` reads, confirmed live on an S17 (alkane-sdk install plan
|
||||
//! install/plans/zynq-7010.yaml, 2026-11-10). The module REFUSES to erase or
|
||||
//! write /dev/mtd0 below BOOTBIN_PRESERVE, so a bad offset can never clobber
|
||||
//! BOOT.bin.
|
||||
|
||||
use crate::md5::md5_hex;
|
||||
use crate::preflight::{classify, parse_digest};
|
||||
use crate::transport::{Remote, RemoteError};
|
||||
use alkane_artifacts::afw::{AfwImage, BootloaderPolicy, VerifiedAfw};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const BOARD: &str = "zynq-7010";
|
||||
pub const ARCH: &str = "armv7";
|
||||
/// mtd0 0x0..0x1a00000 is BOOT.bin (FSBL + FPGA bitstream + stock U-Boot) + the
|
||||
/// U-Boot env, and is NEVER erased or written by this module. (Was 0x2200000
|
||||
/// under the superseded stage-2 map; the live S17 layout places the dtb at
|
||||
/// 0x1a00000, so BOOT.bin ends there.)
|
||||
pub const BOOTBIN_PRESERVE: u64 = 0x1A00000;
|
||||
|
||||
/// Authoritative write targets: (image, device, device-relative offset, ceiling, format).
|
||||
/// Written rootfs -> dtb -> kernel so a mid-write interruption never leaves a new
|
||||
/// rootfs under an old kernel. Offsets and ceilings match the alkane-sdk install
|
||||
/// plan (install/plans/zynq-7010.yaml): dtb slot 0x1a00000 (0x600000), kernel
|
||||
/// slot 0x2000000 (0x800000), rootfs mtd1 (0x2000000).
|
||||
const TARGETS: [(&str, &str, u64, u64, &str); 3] = [
|
||||
("rootfs", "/dev/mtd1", 0x0, 0x2000000, "cpio-gzip"),
|
||||
("dtb", "/dev/mtd0", 0x1A00000, 0x20000, "fdt"),
|
||||
("kernel", "/dev/mtd0", 0x2000000, 0x800000, "zimage"),
|
||||
];
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ZynqPlanError {
|
||||
#[error("bundle is for {0}, not zynq-7010")]
|
||||
WrongBoard(String),
|
||||
#[error("bundle arch is {0}, zynq-7010 needs armv7")]
|
||||
WrongArch(String),
|
||||
#[error("zynq-7010 requires bootloader_policy preserve")]
|
||||
BootloaderPolicy,
|
||||
#[error("zynq-7010 bundle carries a bootloader/spl/BOOT.bin member: {0}")]
|
||||
BootloaderMember(String),
|
||||
#[error("manifest is not an OS payload")]
|
||||
PayloadType,
|
||||
#[error("manifest marker is empty")]
|
||||
Marker,
|
||||
#[error("zynq-7010 must install exactly kernel, dtb and rootfs")]
|
||||
InstallCount,
|
||||
#[error("zynq-7010 is missing the {0} image")]
|
||||
MissingImage(String),
|
||||
#[error("zynq-7010 {image} format is {actual}, expected {expected}")]
|
||||
ImageFormat { image: String, actual: String, expected: &'static str },
|
||||
#[error("zynq-7010 {image} is {size} bytes, over the 0x{ceiling:x}-byte ceiling")]
|
||||
ImageTooLarge { image: String, size: u64, ceiling: u64 },
|
||||
#[error("zynq-7010 {image} is not an ARM zImage")]
|
||||
NotZImage { image: String },
|
||||
#[error("zynq-7010 refuses to place {image} at 0x{offset:x} on {device}: below BOOT.bin (0x{bootbin:x})")]
|
||||
WouldClobberBootbin { image: String, device: String, offset: u64, bootbin: u64 },
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqTarget {
|
||||
pub image_name: String,
|
||||
pub device: String,
|
||||
pub offset: u64,
|
||||
pub size: u64,
|
||||
pub data: Vec<u8>,
|
||||
pub expected_md5: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqPlan {
|
||||
pub targets: Vec<ZynqTarget>,
|
||||
pub marker: String,
|
||||
pub kernel_version: String,
|
||||
pub sdk_revision: String,
|
||||
pub os_revision: String,
|
||||
pub afw_sha256: String,
|
||||
pub min_free_bytes: u64,
|
||||
}
|
||||
|
||||
fn is_bootloaderish(image: &AfwImage) -> bool {
|
||||
let lowered = format!("{} {} {}", image.name, image.file, image.role).to_lowercase();
|
||||
image.role == "bootloader"
|
||||
|| lowered.contains("spl")
|
||||
|| lowered.contains("u-boot")
|
||||
|| lowered.contains("uboot")
|
||||
|| lowered.contains("boot.bin")
|
||||
}
|
||||
|
||||
impl ZynqPlan {
|
||||
pub fn from_afw(afw: &VerifiedAfw) -> Result<Self, ZynqPlanError> {
|
||||
let manifest = &afw.manifest;
|
||||
if manifest.board != BOARD {
|
||||
return Err(ZynqPlanError::WrongBoard(manifest.board.clone()));
|
||||
}
|
||||
if manifest.arch != ARCH {
|
||||
return Err(ZynqPlanError::WrongArch(manifest.arch.clone()));
|
||||
}
|
||||
if manifest.payload_type != "os" {
|
||||
return Err(ZynqPlanError::PayloadType);
|
||||
}
|
||||
if manifest.bootloader_policy != BootloaderPolicy::Preserve {
|
||||
return Err(ZynqPlanError::BootloaderPolicy);
|
||||
}
|
||||
if manifest.marker.is_empty() {
|
||||
return Err(ZynqPlanError::Marker);
|
||||
}
|
||||
// BOOT.bin / bootloader members are never allowed - we reuse the board's.
|
||||
for image in &manifest.images {
|
||||
if is_bootloaderish(image) {
|
||||
return Err(ZynqPlanError::BootloaderMember(image.file.clone()));
|
||||
}
|
||||
}
|
||||
let installs: Vec<&AfwImage> = manifest.images.iter().filter(|i| i.install).collect();
|
||||
if installs.len() != TARGETS.len() {
|
||||
return Err(ZynqPlanError::InstallCount);
|
||||
}
|
||||
|
||||
let mut targets = Vec::with_capacity(TARGETS.len());
|
||||
for (image_name, device, offset, ceiling, expected_format) in TARGETS {
|
||||
let image = manifest
|
||||
.images
|
||||
.iter()
|
||||
.find(|i| i.name == image_name && i.install)
|
||||
.ok_or_else(|| ZynqPlanError::MissingImage(image_name.to_owned()))?;
|
||||
if image.format != expected_format {
|
||||
return Err(ZynqPlanError::ImageFormat {
|
||||
image: image_name.to_owned(),
|
||||
actual: image.format.clone(),
|
||||
expected: expected_format,
|
||||
});
|
||||
}
|
||||
if image.size > ceiling {
|
||||
return Err(ZynqPlanError::ImageTooLarge {
|
||||
image: image_name.to_owned(),
|
||||
size: image.size,
|
||||
ceiling,
|
||||
});
|
||||
}
|
||||
// The one hard brick guard: a write on /dev/mtd0 must sit entirely
|
||||
// above BOOT.bin.
|
||||
if device == "/dev/mtd0" && offset < BOOTBIN_PRESERVE {
|
||||
return Err(ZynqPlanError::WouldClobberBootbin {
|
||||
image: image_name.to_owned(),
|
||||
device: device.to_owned(),
|
||||
offset,
|
||||
bootbin: BOOTBIN_PRESERVE,
|
||||
});
|
||||
}
|
||||
let data = afw
|
||||
.image(image_name)
|
||||
.map(|(_, data)| data)
|
||||
.ok_or_else(|| ZynqPlanError::MissingImage(image_name.to_owned()))?;
|
||||
if expected_format == "zimage"
|
||||
&& !(data.len() >= 0x28 && data[0x24..0x28] == [0x18, 0x28, 0x6f, 0x01])
|
||||
{
|
||||
return Err(ZynqPlanError::NotZImage { image: image_name.to_owned() });
|
||||
}
|
||||
targets.push(ZynqTarget {
|
||||
image_name: image_name.to_owned(),
|
||||
device: device.to_owned(),
|
||||
offset,
|
||||
size: image.size,
|
||||
expected_md5: md5_hex(data),
|
||||
data: data.to_vec(),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
targets,
|
||||
marker: manifest.marker.clone(),
|
||||
kernel_version: manifest.kernel_version.clone(),
|
||||
sdk_revision: manifest.sdk_revision.clone(),
|
||||
os_revision: manifest.os_revision.clone(),
|
||||
afw_sha256: afw.archive_sha256.clone(),
|
||||
min_free_bytes: manifest
|
||||
.preflight
|
||||
.get("min_free_bytes")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(16 * 1024 * 1024),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = format!("board {BOARD} arch {ARCH}\n");
|
||||
out.push_str(&format!(
|
||||
"tier 2 update: write the kernel slot + mtd1; BOOT.bin (mtd0 0..0x{:x}) preserved, never written\n",
|
||||
BOOTBIN_PRESERVE
|
||||
));
|
||||
out.push_str("image format kernel=zImage, dtb=fdt, rootfs=cpio-gzip\n");
|
||||
for target in &self.targets {
|
||||
out.push_str(&format!(
|
||||
"write {} {} offset 0x{:x} size {} B md5 {}\n",
|
||||
target.image_name, target.device, target.offset, target.size, target.expected_md5
|
||||
));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"marker {} kernel {} sdk {} os {}",
|
||||
self.marker,
|
||||
self.kernel_version,
|
||||
short(&self.sdk_revision),
|
||||
short(&self.os_revision),
|
||||
));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn short(rev: &str) -> &str {
|
||||
rev.get(..12).unwrap_or(rev)
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ZynqError {
|
||||
#[error("preflight failed:\n{0}")]
|
||||
Preflight(String),
|
||||
#[error("--confirm FLASH is required to write")]
|
||||
Confirm,
|
||||
#[error("refusing to write {device} at 0x{offset:x}: below BOOT.bin (0x{bootbin:x})")]
|
||||
BootbinGuard { device: String, offset: u64, bootbin: u64 },
|
||||
#[error("{0} staged md5 differs from the verified bundle")]
|
||||
StageMismatch(String),
|
||||
#[error("{0} read-back md5 mismatch; do not reboot")]
|
||||
Readback(String),
|
||||
#[error(transparent)]
|
||||
Remote(#[from] RemoteError),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqCheck {
|
||||
pub name: String,
|
||||
pub ok: bool,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqPreflight {
|
||||
pub host: String,
|
||||
pub checks: Vec<ZynqCheck>,
|
||||
}
|
||||
|
||||
impl ZynqPreflight {
|
||||
pub fn ok(&self) -> bool {
|
||||
self.checks.iter().all(|c| c.ok)
|
||||
}
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = format!("preflight {}\n", self.host);
|
||||
for c in &self.checks {
|
||||
out.push_str(&format!("check {} {}: {}\n", c.name, if c.ok { "ok" } else { "FAIL" }, c.detail));
|
||||
}
|
||||
out.push_str(&format!("result {}", if self.ok() { "PASS" } else { "FAIL (do not write)" }));
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
pub fn preflight(
|
||||
plan: &ZynqPlan,
|
||||
remote: &mut dyn Remote,
|
||||
host: &str,
|
||||
) -> Result<ZynqPreflight, ZynqError> {
|
||||
let mut checks = Vec::new();
|
||||
|
||||
let fingerprint = remote.user_command(
|
||||
"uname -r; echo __MODEL__; cat /proc/device-tree/model 2>/dev/null; echo; \
|
||||
echo __RELEASE__; cat /etc/os-release 2>/dev/null; cat /etc/alkane-release 2>/dev/null \
|
||||
|| true",
|
||||
Duration::from_secs(20),
|
||||
)?;
|
||||
let text = String::from_utf8_lossy(&fingerprint).into_owned();
|
||||
let mut it = text.split("__MODEL__");
|
||||
let kernel = it.next().unwrap_or("").trim().to_owned();
|
||||
let rest = it.next().unwrap_or("");
|
||||
let mut it2 = rest.split("__RELEASE__");
|
||||
let _model = it2.next().unwrap_or("");
|
||||
let release = it2.next().unwrap_or("");
|
||||
let source = classify(&kernel, release, &text);
|
||||
checks.push(ZynqCheck {
|
||||
name: "source-os".to_owned(),
|
||||
ok: source == "alkane",
|
||||
detail: format!("{source} (update path requires alkane)"),
|
||||
});
|
||||
|
||||
let uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
|
||||
.trim()
|
||||
.to_owned();
|
||||
checks.push(ZynqCheck { name: "root".to_owned(), ok: uid == "0", detail: format!("uid {uid}") });
|
||||
|
||||
let tools = remote.user_command(
|
||||
"for c in /usr/sbin/flash_erase /usr/sbin/nandwrite /usr/sbin/nanddump md5sum sync; do \
|
||||
command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done",
|
||||
Duration::from_secs(15),
|
||||
)?;
|
||||
let missing: Vec<String> = String::from_utf8_lossy(&tools)
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("missing:").map(str::to_owned))
|
||||
.collect();
|
||||
checks.push(ZynqCheck {
|
||||
name: "commands".to_owned(),
|
||||
ok: missing.is_empty(),
|
||||
detail: if missing.is_empty() { "flash tools present".to_owned() } else { format!("missing {}", missing.join(", ")) },
|
||||
});
|
||||
|
||||
let mtd = String::from_utf8_lossy(&remote.user_command("cat /proc/mtd 2>/dev/null", Duration::from_secs(20))?).into_owned();
|
||||
let have_mtd01 = mtd.contains("mtd0:") && mtd.contains("mtd1:");
|
||||
checks.push(ZynqCheck {
|
||||
name: "mtd".to_owned(),
|
||||
ok: have_mtd01,
|
||||
detail: if have_mtd01 { "mtd0 (BOOT.bin+kernel) and mtd1 present".to_owned() } else { format!("mtd0/mtd1 not found: {mtd}") },
|
||||
});
|
||||
|
||||
// The guard, asserted again at preflight: no target writes mtd0 below BOOT.bin.
|
||||
let guard_ok = plan
|
||||
.targets
|
||||
.iter()
|
||||
.all(|t| !(t.device == "/dev/mtd0" && t.offset < BOOTBIN_PRESERVE));
|
||||
checks.push(ZynqCheck {
|
||||
name: "preserve-bootbin".to_owned(),
|
||||
ok: guard_ok,
|
||||
detail: format!("no write on /dev/mtd0 below 0x{BOOTBIN_PRESERVE:x}"),
|
||||
});
|
||||
|
||||
Ok(ZynqPreflight { host: host.to_owned(), checks })
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqInstallOptions {
|
||||
pub dry_run: bool,
|
||||
pub confirm: Option<String>,
|
||||
pub no_reboot: bool,
|
||||
pub backup_dir: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqBackup {
|
||||
pub image_name: String,
|
||||
pub device: String,
|
||||
pub offset: u64,
|
||||
pub path: PathBuf,
|
||||
pub md5: String,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ZynqReceipt {
|
||||
pub backups: Vec<ZynqBackup>,
|
||||
pub rebooted: bool,
|
||||
}
|
||||
|
||||
pub enum ZynqOutcome {
|
||||
DryRun(Box<ZynqPreflight>),
|
||||
Installed(ZynqReceipt),
|
||||
}
|
||||
|
||||
/// flash_erase/nandwrite erase-block count that covers `size` bytes at a 128 KiB
|
||||
/// erase block (the Zynq pl35x-nand block size).
|
||||
fn erase_blocks(size: u64) -> u64 {
|
||||
const BLOCK: u64 = 0x20000;
|
||||
size.div_ceil(BLOCK)
|
||||
}
|
||||
|
||||
pub fn install(
|
||||
plan: &ZynqPlan,
|
||||
remote: &mut dyn Remote,
|
||||
options: &ZynqInstallOptions,
|
||||
host: &str,
|
||||
) -> Result<ZynqOutcome, ZynqError> {
|
||||
let report = preflight(plan, remote, host)?;
|
||||
if !report.ok() {
|
||||
return Err(ZynqError::Preflight(report.render()));
|
||||
}
|
||||
if options.dry_run {
|
||||
return Ok(ZynqOutcome::DryRun(Box::new(report)));
|
||||
}
|
||||
if options.confirm.as_deref() != Some("FLASH") {
|
||||
return Err(ZynqError::Confirm);
|
||||
}
|
||||
fs::create_dir_all(&options.backup_dir)?;
|
||||
let epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
|
||||
let mut backups = Vec::new();
|
||||
|
||||
for target in &plan.targets {
|
||||
// Hard guard, right before touching NAND: never below BOOT.bin on mtd0.
|
||||
if target.device == "/dev/mtd0" && target.offset < BOOTBIN_PRESERVE {
|
||||
return Err(ZynqError::BootbinGuard {
|
||||
device: target.device.clone(),
|
||||
offset: target.offset,
|
||||
bootbin: BOOTBIN_PRESERVE,
|
||||
});
|
||||
}
|
||||
let name = &target.image_name;
|
||||
let device = &target.device;
|
||||
let offset = target.offset;
|
||||
|
||||
// Back up the region we are about to overwrite, offset-aware.
|
||||
let remote_backup = format!("/tmp/.alkane-z-{name}-backup.img");
|
||||
remote.root_command(
|
||||
&format!(
|
||||
"/usr/sbin/nanddump --omitoob --bb=skipbad --start=0x{offset:x} --length={} -f {remote_backup} {device}",
|
||||
target.size
|
||||
),
|
||||
Duration::from_secs(300),
|
||||
)?;
|
||||
let local = options.backup_dir.join(format!("{name}-{epoch}.img"));
|
||||
remote.pull(&remote_backup, &local, Duration::from_secs(300))?;
|
||||
let _ = remote.root_command(&format!("rm -f {remote_backup}"), Duration::from_secs(15));
|
||||
let data = fs::read(&local)?;
|
||||
let md5 = md5_hex(&data);
|
||||
backups.push(ZynqBackup {
|
||||
image_name: name.clone(),
|
||||
device: device.clone(),
|
||||
offset,
|
||||
path: local,
|
||||
md5,
|
||||
size: target.size,
|
||||
});
|
||||
|
||||
// Stage the verified payload and prove its remote md5 before writing.
|
||||
let mut staged = tempfile::NamedTempFile::new()?;
|
||||
staged.write_all(&target.data)?;
|
||||
staged.flush()?;
|
||||
let remote_stage = format!("/tmp/.alkane-z-{name}-stage.img");
|
||||
remote.push(staged.path(), &remote_stage, Duration::from_secs(300))?;
|
||||
let staged_md5 = parse_digest(
|
||||
&remote.root_command(&format!("md5sum {remote_stage}"), Duration::from_secs(60))?,
|
||||
32,
|
||||
)
|
||||
.unwrap_or_default();
|
||||
if staged_md5 != target.expected_md5 {
|
||||
let _ = remote.root_command(&format!("rm -f {remote_stage}"), Duration::from_secs(15));
|
||||
return Err(ZynqError::StageMismatch(name.clone()));
|
||||
}
|
||||
|
||||
// Erase and write exactly the region at its offset. flash_erase takes an
|
||||
// offset + block count, so BOOT.bin (below the offset) is never touched.
|
||||
let blocks = erase_blocks(target.size);
|
||||
remote.root_command(
|
||||
&format!("/usr/sbin/flash_erase {device} 0x{offset:x} {blocks}"),
|
||||
Duration::from_secs(300),
|
||||
)?;
|
||||
remote.root_command(
|
||||
&format!("/usr/sbin/nandwrite -p --start=0x{offset:x} {device} {remote_stage} && sync"),
|
||||
Duration::from_secs(300),
|
||||
)?;
|
||||
|
||||
// Read back exactly what we wrote and compare.
|
||||
let remote_readback = format!("/tmp/.alkane-z-{name}-readback.img");
|
||||
remote.root_command(
|
||||
&format!(
|
||||
"/usr/sbin/nanddump --omitoob --bb=skipbad --start=0x{offset:x} --length={} -f {remote_readback} {device}",
|
||||
target.size
|
||||
),
|
||||
Duration::from_secs(300),
|
||||
)?;
|
||||
let readback = parse_digest(
|
||||
&remote.root_command(&format!("md5sum {remote_readback}"), Duration::from_secs(60))?,
|
||||
32,
|
||||
)
|
||||
.unwrap_or_default();
|
||||
let _ = remote.root_command(
|
||||
&format!("rm -f {remote_stage} {remote_readback}"),
|
||||
Duration::from_secs(15),
|
||||
);
|
||||
if readback != target.expected_md5 {
|
||||
return Err(ZynqError::Readback(name.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
let rebooted = if options.no_reboot {
|
||||
false
|
||||
} else {
|
||||
remote.reboot()?;
|
||||
true
|
||||
};
|
||||
Ok(ZynqOutcome::Installed(ZynqReceipt { backups, rebooted }))
|
||||
}
|
||||
|
||||
pub fn owns_board(board: &str) -> bool {
|
||||
board == BOARD
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use alkane_artifacts::afw::{AfwManifest, AfwMember};
|
||||
use sha2::{Digest, Sha256};
|
||||
use serde_json::json;
|
||||
|
||||
const REV: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||
|
||||
fn zimage(payload: &[u8]) -> Vec<u8> {
|
||||
let mut b = vec![0u8; 64];
|
||||
b[0x24..0x28].copy_from_slice(&[0x18, 0x28, 0x6f, 0x01]);
|
||||
b.extend_from_slice(payload);
|
||||
b
|
||||
}
|
||||
|
||||
fn afw(kernel: Vec<u8>, dtb: Vec<u8>, rootfs: Vec<u8>) -> VerifiedAfw {
|
||||
let image = |name: &str, file: &str, role: &str, fmt: &str, data: &[u8]| {
|
||||
let sha: String = Sha256::digest(data).iter().map(|b| format!("{b:02x}")).collect();
|
||||
json!({"name": name, "file": file, "role": role, "format": fmt,
|
||||
"size": data.len(), "sha256": sha, "partition": "x", "install": true})
|
||||
};
|
||||
let value = json!({
|
||||
"schema": 2, "format": "afw", "board": "zynq-7010", "arch": "armv7",
|
||||
"version": "0.1.0", "build_date": "2026-11-06T00:00:00Z",
|
||||
"sdk_revision": REV, "os_revision": REV, "payload_type": "os",
|
||||
"bootloader_policy": "preserve",
|
||||
"signature": {"type": "unsigned", "member": null, "public_key_hex": null},
|
||||
"partitions": [],
|
||||
"images": [
|
||||
image("kernel", "payload/zImage", "kernel", "zimage", &kernel),
|
||||
image("dtb", "payload/zynq-alkane.dtb", "dtb", "fdt", &dtb),
|
||||
image("rootfs", "payload/rootfs.cpio.gz", "rootfs", "cpio-gzip", &rootfs),
|
||||
],
|
||||
"boot_switch": {}, "preflight": {"min_free_bytes": 16777216},
|
||||
"recovery": {}, "marker": "Alkane", "kernel_version": "6.18.48"
|
||||
});
|
||||
let manifest: AfwManifest = serde_json::from_value(value).unwrap();
|
||||
VerifiedAfw {
|
||||
manifest,
|
||||
members: vec![
|
||||
AfwMember { name: "payload/zImage".to_owned(), data: kernel },
|
||||
AfwMember { name: "payload/zynq-alkane.dtb".to_owned(), data: dtb },
|
||||
AfwMember { name: "payload/rootfs.cpio.gz".to_owned(), data: rootfs },
|
||||
],
|
||||
manifest_sha256: "0".repeat(64),
|
||||
archive_sha256: "0".repeat(64),
|
||||
}
|
||||
}
|
||||
|
||||
fn dtb() -> Vec<u8> {
|
||||
let mut b = vec![0u8; 1024];
|
||||
b[0..4].copy_from_slice(&[0xd0, 0x0d, 0xfe, 0xed]);
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_a_good_plan_and_places_above_bootbin() {
|
||||
let plan = ZynqPlan::from_afw(&afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec())).unwrap();
|
||||
assert_eq!(plan.targets.len(), 3);
|
||||
// write order rootfs, dtb, kernel
|
||||
assert_eq!(plan.targets[0].image_name, "rootfs");
|
||||
assert_eq!(plan.targets[2].image_name, "kernel");
|
||||
for t in &plan.targets {
|
||||
if t.device == "/dev/mtd0" {
|
||||
assert!(t.offset >= BOOTBIN_PRESERVE, "{} below BOOT.bin", t.image_name);
|
||||
}
|
||||
}
|
||||
assert!(plan.render().contains("BOOT.bin"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_non_zimage_kernel() {
|
||||
let result = ZynqPlan::from_afw(&afw(vec![0u8; 64], dtb(), b"\x1f\x8brf".to_vec()));
|
||||
assert!(matches!(result, Err(ZynqPlanError::NotZImage { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_an_oversize_kernel() {
|
||||
// Over the kernel-slot ceiling (0x800000).
|
||||
let big = zimage(&vec![0u8; 0x800001]);
|
||||
let result = ZynqPlan::from_afw(&afw(big, dtb(), b"\x1f\x8brf".to_vec()));
|
||||
assert!(matches!(result, Err(ZynqPlanError::ImageTooLarge { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_bootloader_member() {
|
||||
let mut verified = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
|
||||
verified.manifest.images[0].role = "bootloader".to_owned();
|
||||
assert!(matches!(ZynqPlan::from_afw(&verified), Err(ZynqPlanError::BootloaderMember(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_board_and_arch_are_refused() {
|
||||
let mut v = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
|
||||
v.manifest.board = "am335x".to_owned();
|
||||
assert!(matches!(ZynqPlan::from_afw(&v), Err(ZynqPlanError::WrongBoard(_))));
|
||||
let mut v = afw(zimage(b"k"), dtb(), b"\x1f\x8brf".to_vec());
|
||||
v.manifest.arch = "arm".to_owned();
|
||||
assert!(matches!(ZynqPlan::from_afw(&v), Err(ZynqPlanError::WrongArch(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_mtd0_target_is_above_bootbin() {
|
||||
// Compile-time-ish guarantee from the TARGETS table.
|
||||
for (image, device, offset, _ceiling, _fmt) in TARGETS {
|
||||
if device == "/dev/mtd0" {
|
||||
assert!(offset >= BOOTBIN_PRESERVE, "{image} target below BOOT.bin");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,920 @@
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Guarded write sequence for a verified artifact and an SDK partition plan.
|
||||
//! Board transport adapters must supply serial, recovery and readback evidence.
|
||||
//! Guarded writes plus the network-only CV1835 installer.
|
||||
//!
|
||||
//! The original guarded-write helpers remain for boards that need an attached
|
||||
//! recovery channel. CV1835 uses the network modules below: a verified `.afw`,
|
||||
//! a board plan, an SSH transport with a stock-root stage, a read-only
|
||||
//! preflight, a whole-partition read-back and a network restore.
|
||||
|
||||
pub mod boards;
|
||||
pub mod install;
|
||||
pub mod md5;
|
||||
pub mod preflight;
|
||||
pub mod stock;
|
||||
// DSH-authored, network-only method bodies compiled into the toolkit; the
|
||||
// interface lives in `stock`. Not read or edited by Claude. See stock_method.rs.
|
||||
mod stock_method;
|
||||
pub mod transport;
|
||||
|
||||
use alkane_artifacts::VerifiedArtifact;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! MD5 for the CV1835 whole-partition read-back.
|
||||
//!
|
||||
//! The stock busybox on this board ships `md5sum` but not `sha256sum`, and the
|
||||
//! proven installer gates the write on a whole-partition md5. This module is a
|
||||
//! small RFC 1321 implementation so the host can compare the same digest
|
||||
//! without shelling out to a tool that may not exist.
|
||||
|
||||
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] = [
|
||||
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
|
||||
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
|
||||
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
|
||||
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
|
||||
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
|
||||
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
|
||||
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
|
||||
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
|
||||
];
|
||||
|
||||
pub fn md5(data: &[u8]) -> [u8; 16] {
|
||||
let mut state = [0x67452301_u32, 0xefcdab89, 0x98badcfe, 0x10325476];
|
||||
let bit_length = (data.len() as u64).wrapping_mul(8);
|
||||
let mut message = data.to_vec();
|
||||
message.push(0x80);
|
||||
while message.len() % 64 != 56 {
|
||||
message.push(0);
|
||||
}
|
||||
message.extend_from_slice(&bit_length.to_le_bytes());
|
||||
|
||||
for chunk in message.chunks_exact(64) {
|
||||
let mut words = [0_u32; 16];
|
||||
for (index, word) in words.iter_mut().enumerate() {
|
||||
let start = index * 4;
|
||||
*word = u32::from_le_bytes([
|
||||
chunk[start],
|
||||
chunk[start + 1],
|
||||
chunk[start + 2],
|
||||
chunk[start + 3],
|
||||
]);
|
||||
}
|
||||
let [mut a, mut b, mut c, mut d] = state;
|
||||
for index in 0..64 {
|
||||
let (f, g) = match index {
|
||||
0..=15 => ((b & c) | (!b & d), index),
|
||||
16..=31 => ((d & b) | (!d & c), (5 * index + 1) % 16),
|
||||
32..=47 => (b ^ c ^ d, (3 * index + 5) % 16),
|
||||
_ => (c ^ (b | !d), (7 * index) % 16),
|
||||
};
|
||||
let rotated = a
|
||||
.wrapping_add(f)
|
||||
.wrapping_add(K[index])
|
||||
.wrapping_add(words[g])
|
||||
.rotate_left(S[index]);
|
||||
a = d;
|
||||
d = c;
|
||||
c = b;
|
||||
b = b.wrapping_add(rotated);
|
||||
}
|
||||
state[0] = state[0].wrapping_add(a);
|
||||
state[1] = state[1].wrapping_add(b);
|
||||
state[2] = state[2].wrapping_add(c);
|
||||
state[3] = state[3].wrapping_add(d);
|
||||
}
|
||||
|
||||
let mut digest = [0_u8; 16];
|
||||
for (index, word) in state.iter().enumerate() {
|
||||
digest[index * 4..index * 4 + 4].copy_from_slice(&word.to_le_bytes());
|
||||
}
|
||||
digest
|
||||
}
|
||||
|
||||
pub fn md5_hex(data: &[u8]) -> String {
|
||||
md5(data).iter().map(|byte| format!("{byte:02x}")).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rfc1321_vectors() {
|
||||
assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e");
|
||||
assert_eq!(md5_hex(b"a"), "0cc175b9c0f1b6a831c399e269772661");
|
||||
assert_eq!(md5_hex(b"abc"), "900150983cd24fb0d6963f7d28e17f72");
|
||||
assert_eq!(
|
||||
md5_hex(b"message digest"),
|
||||
"f96b697d7cb7938d525a2f31aaf161d0"
|
||||
);
|
||||
assert_eq!(
|
||||
md5_hex(b"abcdefghijklmnopqrstuvwxyz"),
|
||||
"c3fcd3d76192e4007dfb496cca67e13b"
|
||||
);
|
||||
assert_eq!(
|
||||
md5_hex(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"),
|
||||
"d174ab98d277d9f5a5611c2c9f419d9f"
|
||||
);
|
||||
assert_eq!(
|
||||
md5_hex(
|
||||
b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"
|
||||
),
|
||||
"57edf4a22be3c955ac49da2e2107b67a"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_a_block_boundary() {
|
||||
let data = vec![0x42_u8; 64];
|
||||
assert_eq!(md5_hex(&data), "8e558437ffca99de04c18a63b55a4fad");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Read-only CV1835 preflight: source-OS fingerprint, root channel, partition
|
||||
//! identity, held/golden backup hashes, free space and secure-region refusal.
|
||||
//!
|
||||
//! Every check runs over the network. A failure is reported, never repaired.
|
||||
|
||||
use crate::boards::cv1835::{Cv1835Plan, CvPlanError};
|
||||
use crate::md5::md5_hex;
|
||||
use crate::transport::{Remote, RemoteError};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
use thiserror::Error;
|
||||
|
||||
const P1_NAME: &str = "mmcblk0p1";
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum PreflightError {
|
||||
#[error("preflight transport: {0}")]
|
||||
Remote(#[from] RemoteError),
|
||||
#[error("preflight I/O: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("preflight plan: {0}")]
|
||||
Plan(#[from] CvPlanError),
|
||||
#[error("held backup {path} is {size} bytes, not 16 MiB")]
|
||||
BackupSize { path: PathBuf, size: u64 },
|
||||
#[error("held backup {0} has no readable md5")]
|
||||
BackupUnreadable(PathBuf),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Check {
|
||||
pub name: &'static str,
|
||||
pub ok: bool,
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BackupCheck {
|
||||
pub path: PathBuf,
|
||||
pub md5: String,
|
||||
pub sha256: String,
|
||||
pub matches_live: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PreflightReport {
|
||||
pub host: String,
|
||||
pub source_os: String,
|
||||
pub kernel: String,
|
||||
pub model: String,
|
||||
pub root_method: String,
|
||||
pub root_uid: String,
|
||||
pub partition_device: String,
|
||||
pub partition_size: u64,
|
||||
pub live_md5: String,
|
||||
pub held_backup: Option<BackupCheck>,
|
||||
pub golden_md5: Option<String>,
|
||||
pub free_bytes: u64,
|
||||
pub boot0_present: bool,
|
||||
pub checks: Vec<Check>,
|
||||
}
|
||||
|
||||
impl PreflightReport {
|
||||
pub fn ok(&self) -> bool {
|
||||
self.checks.iter().all(|check| check.ok)
|
||||
}
|
||||
|
||||
pub fn failures(&self) -> Vec<&Check> {
|
||||
self.checks.iter().filter(|check| !check.ok).collect()
|
||||
}
|
||||
|
||||
pub fn render(&self) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str(&format!("preflight {}\n", self.host));
|
||||
out.push_str(&format!(
|
||||
"source-os {} (kernel {})\n",
|
||||
self.source_os, self.kernel
|
||||
));
|
||||
if !self.model.is_empty() {
|
||||
out.push_str(&format!("model {}\n", self.model));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"root {} (uid {})\n",
|
||||
self.root_method, self.root_uid
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"partition {} {} B\n",
|
||||
self.partition_device, self.partition_size
|
||||
));
|
||||
out.push_str(&format!("live p1 md5 {}\n", self.live_md5));
|
||||
match &self.held_backup {
|
||||
Some(backup) => out.push_str(&format!(
|
||||
"held backup {} md5 {} ({})\n",
|
||||
backup.path.display(),
|
||||
backup.md5,
|
||||
if backup.matches_live {
|
||||
"matches live p1"
|
||||
} else {
|
||||
"differs from live p1"
|
||||
}
|
||||
)),
|
||||
None => out.push_str("held backup none (install will create one before writing)\n"),
|
||||
}
|
||||
if let Some(golden) = &self.golden_md5 {
|
||||
out.push_str(&format!("golden raw p1 md5 {golden}\n"));
|
||||
}
|
||||
out.push_str(&format!(
|
||||
"free tmp {} MiB\n",
|
||||
self.free_bytes / (1024 * 1024)
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"boot0 {} (never written)\n",
|
||||
if self.boot0_present {
|
||||
"present"
|
||||
} else {
|
||||
"not present"
|
||||
}
|
||||
));
|
||||
for check in &self.checks {
|
||||
out.push_str(&format!(
|
||||
"check {} {}: {}\n",
|
||||
check.name,
|
||||
if check.ok { "ok" } else { "FAIL" },
|
||||
check.detail
|
||||
));
|
||||
}
|
||||
out.push_str(if self.ok() {
|
||||
"result PASS\n"
|
||||
} else {
|
||||
"result FAIL (do not write)\n"
|
||||
});
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PreflightOptions<'a> {
|
||||
pub host: &'a str,
|
||||
pub held_backup: Option<&'a Path>,
|
||||
pub check_golden: bool,
|
||||
pub allow_unknown_source: bool,
|
||||
}
|
||||
|
||||
pub fn preflight(
|
||||
plan: &Cv1835Plan,
|
||||
remote: &mut dyn Remote,
|
||||
options: &PreflightOptions<'_>,
|
||||
) -> Result<PreflightReport, PreflightError> {
|
||||
let mut checks = Vec::new();
|
||||
let fingerprint = remote.user_command(
|
||||
"uname -r; echo __MODEL__; cat /proc/device-tree/model 2>/dev/null; echo; \
|
||||
echo __RELEASE__; cat /etc/os-release 2>/dev/null; \
|
||||
ls /etc/bos_version /etc/fw-info /etc/alkane-release /etc/ouros-release 2>/dev/null; \
|
||||
test -x /nvdata/rroot && echo rroot; \
|
||||
test -x /usr/sbin/update-daemon && echo update-daemon",
|
||||
Duration::from_secs(20),
|
||||
)?;
|
||||
let text = String::from_utf8_lossy(&fingerprint).into_owned();
|
||||
let mut sections = text.split("__MODEL__");
|
||||
let kernel = sections.next().unwrap_or("").trim().to_owned();
|
||||
let rest = sections.next().unwrap_or("");
|
||||
let mut sections = rest.split("__RELEASE__");
|
||||
let model = sections.next().unwrap_or("").trim().to_owned();
|
||||
let release = sections.next().unwrap_or("");
|
||||
let source_os = classify(&kernel, release, &text);
|
||||
let source_ok = plan.source_os.is_empty()
|
||||
|| plan.source_os.iter().any(|item| item == &source_os)
|
||||
|| options.allow_unknown_source;
|
||||
checks.push(Check {
|
||||
name: "source-os",
|
||||
ok: source_ok,
|
||||
detail: format!(
|
||||
"{source_os} (allowed: {})",
|
||||
if plan.source_os.is_empty() {
|
||||
"any".to_owned()
|
||||
} else {
|
||||
plan.source_os.join(", ")
|
||||
}
|
||||
),
|
||||
});
|
||||
|
||||
let root_uid = String::from_utf8_lossy(&remote.root_command("id -u", Duration::from_secs(20))?)
|
||||
.trim()
|
||||
.to_owned();
|
||||
checks.push(Check {
|
||||
name: "root",
|
||||
ok: root_uid == "0",
|
||||
detail: format!("uid {root_uid}"),
|
||||
});
|
||||
|
||||
let partition_device = plan.partition.device.clone();
|
||||
let block = String::from_utf8_lossy(&remote.user_command(
|
||||
&format!("test -b {partition_device} && echo block || echo missing"),
|
||||
Duration::from_secs(15),
|
||||
)?)
|
||||
.trim()
|
||||
.to_owned();
|
||||
let size_out = remote.user_command(
|
||||
&format!("cat /sys/class/block/{P1_NAME}/size 2>/dev/null || true"),
|
||||
Duration::from_secs(15),
|
||||
)?;
|
||||
let sectors: u64 = String::from_utf8_lossy(&size_out)
|
||||
.trim()
|
||||
.parse()
|
||||
.unwrap_or(0);
|
||||
let partition_size = sectors.saturating_mul(512);
|
||||
checks.push(Check {
|
||||
name: "partition",
|
||||
ok: block == "block" && partition_size == plan.partition.size,
|
||||
detail: format!(
|
||||
"{partition_device} {partition_size} B (plan {} B)",
|
||||
plan.partition.size
|
||||
),
|
||||
});
|
||||
|
||||
let live = remote.root_command(
|
||||
&format!("md5sum {partition_device}"),
|
||||
Duration::from_secs(60),
|
||||
)?;
|
||||
let live_md5 = parse_digest(&live, 32).unwrap_or_else(|| "unreadable".to_owned());
|
||||
checks.push(Check {
|
||||
name: "live-p1-md5",
|
||||
ok: live_md5.len() == 32,
|
||||
detail: live_md5.clone(),
|
||||
});
|
||||
|
||||
let commands = remote.user_command(
|
||||
"for c in dd md5sum sync; do command -v $c >/dev/null 2>&1 && echo $c || echo missing:$c; done",
|
||||
Duration::from_secs(15),
|
||||
)?;
|
||||
let commands_text = String::from_utf8_lossy(&commands).into_owned();
|
||||
let missing: Vec<&str> = commands_text
|
||||
.lines()
|
||||
.filter_map(|line| line.strip_prefix("missing:"))
|
||||
.collect();
|
||||
checks.push(Check {
|
||||
name: "commands",
|
||||
ok: missing.is_empty(),
|
||||
detail: if missing.is_empty() {
|
||||
"dd, md5sum, sync present".to_owned()
|
||||
} else {
|
||||
format!("missing {}", missing.join(", "))
|
||||
},
|
||||
});
|
||||
|
||||
let free_bytes = free_bytes(remote)?;
|
||||
checks.push(Check {
|
||||
name: "free-space",
|
||||
ok: free_bytes >= plan.min_free_bytes,
|
||||
detail: format!(
|
||||
"{} MiB at /tmp (plan {} MiB)",
|
||||
free_bytes / (1024 * 1024),
|
||||
plan.min_free_bytes / (1024 * 1024)
|
||||
),
|
||||
});
|
||||
|
||||
let boot0 = String::from_utf8_lossy(&remote.user_command(
|
||||
"test -e /dev/mmcblk0boot0 && echo yes || echo no",
|
||||
Duration::from_secs(15),
|
||||
)?)
|
||||
.trim()
|
||||
.to_owned();
|
||||
let boot0_present = boot0 == "yes";
|
||||
checks.push(Check {
|
||||
name: "secure-regions",
|
||||
ok: !plan.partition.device.contains("boot0"),
|
||||
detail: format!(
|
||||
"boot0 {}; the write plan targets only {}",
|
||||
if boot0_present { "present" } else { "absent" },
|
||||
plan.partition.device
|
||||
),
|
||||
});
|
||||
|
||||
let mut held_backup = None;
|
||||
if let Some(path) = options.held_backup {
|
||||
let size = fs::metadata(path)?.len();
|
||||
if size != plan.partition.size {
|
||||
return Err(PreflightError::BackupSize {
|
||||
path: path.to_path_buf(),
|
||||
size,
|
||||
});
|
||||
}
|
||||
let data = fs::read(path)?;
|
||||
let md5 = md5_hex(&data);
|
||||
let sha256: String = Sha256::digest(&data)
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect();
|
||||
let matches_live = md5 == live_md5;
|
||||
checks.push(Check {
|
||||
name: "held-backup",
|
||||
ok: true,
|
||||
detail: format!(
|
||||
"{} md5 {md5} ({})",
|
||||
path.display(),
|
||||
if matches_live {
|
||||
"matches live p1"
|
||||
} else {
|
||||
"differs from live p1; restore will still write it"
|
||||
}
|
||||
),
|
||||
});
|
||||
held_backup = Some(BackupCheck {
|
||||
path: path.to_path_buf(),
|
||||
md5,
|
||||
sha256,
|
||||
matches_live,
|
||||
});
|
||||
}
|
||||
|
||||
let mut golden_md5 = None;
|
||||
if options.check_golden {
|
||||
let out = remote.root_command(
|
||||
&format!(
|
||||
"dd if=/dev/mmcblk0 skip={} count=32768 bs=512 2>/dev/null | md5sum",
|
||||
plan.golden_lba_bytes / 512
|
||||
),
|
||||
Duration::from_secs(90),
|
||||
)?;
|
||||
if let Some(digest) = parse_digest(&out, 32) {
|
||||
golden_md5 = Some(digest);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(PreflightReport {
|
||||
host: options.host.to_owned(),
|
||||
source_os,
|
||||
kernel,
|
||||
model,
|
||||
root_method: remote.root_method().to_owned(),
|
||||
root_uid,
|
||||
partition_device,
|
||||
partition_size,
|
||||
live_md5,
|
||||
held_backup,
|
||||
golden_md5,
|
||||
free_bytes,
|
||||
boot0_present,
|
||||
checks,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn classify(kernel: &str, release: &str, all: &str) -> String {
|
||||
if all.contains("/etc/bos_version") || release.contains("Braiins") {
|
||||
return "braiins".to_owned();
|
||||
}
|
||||
if all.contains("/etc/alkane-release") || kernel.starts_with("6.18") {
|
||||
return "alkane".to_owned();
|
||||
}
|
||||
if all.contains("/etc/ouros-release") || kernel.contains("6.6.147") {
|
||||
return "ouros".to_owned();
|
||||
}
|
||||
if all.contains("/etc/fw-info") || release.contains("Vnish") || release.contains("AnthillOS") {
|
||||
return "vnish".to_owned();
|
||||
}
|
||||
// Stock Bitmain control boards: Amlogic stock is kernel 4.9.38; the AM335x
|
||||
// (BeagleBone-class) stock is kernel 3.8.13+ with an "Antminer" model line.
|
||||
if kernel.contains("4.9.38")
|
||||
|| kernel.starts_with("3.8.13")
|
||||
|| all.contains("update-daemon")
|
||||
|| all.contains("rroot")
|
||||
|| all.to_lowercase().contains("antminer")
|
||||
{
|
||||
return "stock-bitmain".to_owned();
|
||||
}
|
||||
"unknown".to_owned()
|
||||
}
|
||||
|
||||
pub fn parse_digest(output: &[u8], length: usize) -> Option<String> {
|
||||
let text = String::from_utf8_lossy(output);
|
||||
text.split_whitespace()
|
||||
.map(|token| token.trim().to_ascii_lowercase())
|
||||
.find(|token| token.len() == length && token.bytes().all(|byte| byte.is_ascii_hexdigit()))
|
||||
}
|
||||
|
||||
fn free_bytes(remote: &mut dyn Remote) -> Result<u64, RemoteError> {
|
||||
let out = remote.user_command("df -k /tmp 2>/dev/null || df -k /", Duration::from_secs(15))?;
|
||||
let text = String::from_utf8_lossy(&out);
|
||||
for line in text.lines().rev() {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
if fields.len() >= 4 {
|
||||
if let Ok(kib) = fields[3].parse::<u64>() {
|
||||
return Ok(kib.saturating_mul(1024));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn classifies_the_source_os() {
|
||||
assert_eq!(
|
||||
classify("4.9.38-tag-", "", "update-daemon\n"),
|
||||
"stock-bitmain"
|
||||
);
|
||||
assert_eq!(
|
||||
classify("4.9.38-tag-", "/etc/fw-info\n", "/etc/fw-info\n"),
|
||||
"vnish"
|
||||
);
|
||||
assert_eq!(classify("6.6.147", "/etc/ouros-release\n", ""), "ouros");
|
||||
assert_eq!(classify("6.18.48", "", ""), "alkane");
|
||||
assert_eq!(classify("4.9.38", "", "/etc/bos_version\n"), "braiins");
|
||||
assert_eq!(classify("5.10.0", "", ""), "unknown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_md5_from_md5sum_output() {
|
||||
let output = b"3f43804f10ce256200bfc71e7fbdd9ee /dev/mmcblk0p1\n";
|
||||
assert_eq!(
|
||||
parse_digest(output, 32).as_deref(),
|
||||
Some("3f43804f10ce256200bfc71e7fbdd9ee")
|
||||
);
|
||||
assert_eq!(parse_digest(b"not a digest\n", 32), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Stock <-> alkane crossing, compiled into the toolkit.
|
||||
//!
|
||||
//! The toolkit is self-contained: it installs alkane onto a board on stock and
|
||||
//! returns a board to stock entirely on its own, with NO external helper and NO
|
||||
//! runtime dependency on any other tool. A user's machine needs only this
|
||||
//! binary.
|
||||
//!
|
||||
//! Two steps trip a stock miner's safeguards (getting our first image on past
|
||||
//! stock's gates with root, and the reverse). Those method bodies are authored
|
||||
//! by DeepSeek Harness in the sibling module `stock_method` and are NOT read,
|
||||
//! reviewed, or edited by Claude. THIS file is the Claude-owned boundary: the
|
||||
//! interface (`StockMethod`, `StockError`) and the toolkit-side orchestration
|
||||
//! and verification around the method. The method is plain Rust - there is no AI
|
||||
//! tooling in the toolkit - and must be network-only.
|
||||
|
||||
use alkane_artifacts::afw::VerifiedAfw;
|
||||
use std::path::Path;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum StockError {
|
||||
#[error("the stock method is not implemented in this build")]
|
||||
NotImplemented,
|
||||
#[error("could not reach the board: {0}")]
|
||||
Network(String),
|
||||
#[error("authentication failed: {0}")]
|
||||
Auth(String),
|
||||
#[error("the stock method failed: {0}")]
|
||||
Method(String),
|
||||
#[error("io: {0}")]
|
||||
Io(String),
|
||||
}
|
||||
|
||||
/// The stock-side methods, implemented by `stock_method` (DSH-authored). All
|
||||
/// implementations must be NETWORK-ONLY (no serial-console dependency).
|
||||
pub trait StockMethod {
|
||||
/// Put our first image (the `.afw`) onto a board currently on stock, past
|
||||
/// stock's gates and with root, over the network only. On Ok the board is
|
||||
/// installed with alkane; the caller verifies liveness.
|
||||
fn install_from_stock(
|
||||
&self,
|
||||
host: &str,
|
||||
afw_path: &Path,
|
||||
afw: &VerifiedAfw,
|
||||
password: Option<&str>,
|
||||
) -> Result<(), StockError>;
|
||||
|
||||
/// Return an aftermarket (alkane) board to genuine stock, over the network
|
||||
/// only. `password` is the board's alkane root credential. On Ok the board
|
||||
/// is on stock; the caller verifies.
|
||||
fn restore_to_stock(&self, host: &str, password: Option<&str>) -> Result<(), StockError>;
|
||||
}
|
||||
|
||||
/// The compiled-in method implementation.
|
||||
pub fn method() -> &'static dyn StockMethod {
|
||||
crate::stock_method::method()
|
||||
}
|
||||
|
||||
/// Install alkane onto a board on stock (network-only), via the compiled-in method.
|
||||
pub fn install_from_stock(
|
||||
host: &str,
|
||||
afw_path: &Path,
|
||||
afw: &VerifiedAfw,
|
||||
password: Option<&str>,
|
||||
) -> Result<(), StockError> {
|
||||
method().install_from_stock(host, afw_path, afw, password)
|
||||
}
|
||||
|
||||
/// Return an alkane board to stock (network-only), via the compiled-in method.
|
||||
pub fn restore_to_stock(host: &str, password: Option<&str>) -> Result<(), StockError> {
|
||||
method().restore_to_stock(host, password)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// The interface is exercised against whatever `stock_method` provides. We
|
||||
// only assert the toolkit wires a method object in; its behaviour is the
|
||||
// method module's own tests.
|
||||
#[test]
|
||||
fn a_method_is_compiled_in() {
|
||||
let _m: &dyn StockMethod = method();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,699 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
//! Network transport for the CV1835 installer.
|
||||
//!
|
||||
//! Two root channels are implemented, both over the network:
|
||||
//!
|
||||
//! * `direct`: the SSH login is already uid 0 (Braiins OS, ourOS/alkane with a
|
||||
//! root key, or an operator-supplied root login).
|
||||
//! * `update-daemon`: stock Bitmain (and Vnish, which runs on the stock
|
||||
//! kernel) exposes an SSH login as `miner` (uid 1001). `/usr/sbin/update-daemon`
|
||||
//! listens on 127.0.0.1:12887 and pipes its socket into `system()` as root.
|
||||
//! We reach it through an SSH local forward, exactly as documented in the RE
|
||||
//! notes (`cv-kvm-host` / `cvbuild/cvroot.py`,
|
||||
//! `alkane-sdk-wiki/40-boot-os-and-build/cross-install-matrix.md`). The
|
||||
//! channel is blind, so root output is redirected to a world-readable file
|
||||
//! and read back over the unprivileged SSH session.
|
||||
//! * `rroot`: an existing `/nvdata/rroot` setuid helper on CV stock/Vnish,
|
||||
//! documented in `60-reverse-engineering-methods/rroot-setuid-escalation.md`.
|
||||
//! It is a fallback because the helper is not durable across a p7 reformat.
|
||||
//!
|
||||
//! Credentials are never read here: a password is used only through
|
||||
//! `sshpass -f <path>`, and that path comes from the operator (environment
|
||||
//! variable materialized by the CLI, or a file named on the command line).
|
||||
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, ExitStatus, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
use thiserror::Error;
|
||||
|
||||
const MAX_CAPTURE: usize = 64 * 1024 * 1024;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum RemoteError {
|
||||
#[error("remote I/O: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("cannot start {0}")]
|
||||
MissingTool(&'static str),
|
||||
#[error("invalid target: {0}")]
|
||||
InvalidTarget(String),
|
||||
#[error("SSH transport: {0}")]
|
||||
Ssh(String),
|
||||
#[error("SSH command timed out after {0:?}")]
|
||||
Timeout(Duration),
|
||||
#[error("remote command failed ({status}): {stderr}")]
|
||||
Command { status: String, stderr: String },
|
||||
#[error("root access was not obtained: {0}")]
|
||||
NotRoot(String),
|
||||
#[error("no network root channel is available on this board")]
|
||||
NoRootMethod,
|
||||
#[error("update-daemon: {0}")]
|
||||
Daemon(String),
|
||||
#[error("remote output is over the {0}-byte cap")]
|
||||
OutputTooLarge(usize),
|
||||
}
|
||||
|
||||
impl RemoteError {
|
||||
fn sanitize(text: &str) -> String {
|
||||
let text = text.trim();
|
||||
let mut shortened: String = text.chars().take(300).collect();
|
||||
if shortened.len() < text.len() {
|
||||
shortened.push_str("...");
|
||||
}
|
||||
shortened
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum RootMethod {
|
||||
Auto,
|
||||
Direct,
|
||||
UpdateDaemon,
|
||||
Rroot,
|
||||
}
|
||||
|
||||
impl RootMethod {
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"auto" => Some(Self::Auto),
|
||||
"direct" => Some(Self::Direct),
|
||||
"update-daemon" => Some(Self::UpdateDaemon),
|
||||
"rroot" => Some(Self::Rroot),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SshOptions {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub user: String,
|
||||
pub identity_file: Option<PathBuf>,
|
||||
pub password_file: Option<PathBuf>,
|
||||
pub known_hosts: Option<PathBuf>,
|
||||
pub root_method: RootMethod,
|
||||
pub update_daemon_port: Option<u16>,
|
||||
}
|
||||
|
||||
impl Default for SshOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
host: String::new(),
|
||||
port: 22,
|
||||
user: "miner".to_owned(),
|
||||
identity_file: None,
|
||||
password_file: None,
|
||||
known_hosts: None,
|
||||
root_method: RootMethod::Auto,
|
||||
update_daemon_port: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SshOptions {
|
||||
fn validate(&self) -> Result<(), RemoteError> {
|
||||
if self.host.is_empty()
|
||||
|| self.host.len() > 253
|
||||
|| self.host.starts_with('-')
|
||||
|| !self.host.bytes().all(|byte| {
|
||||
byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b':' | b'_')
|
||||
})
|
||||
{
|
||||
return Err(RemoteError::InvalidTarget("host".to_owned()));
|
||||
}
|
||||
if self.user.is_empty()
|
||||
|| !self
|
||||
.user
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
|
||||
{
|
||||
return Err(RemoteError::InvalidTarget("user".to_owned()));
|
||||
}
|
||||
if self.port == 0 {
|
||||
return Err(RemoteError::InvalidTarget("port".to_owned()));
|
||||
}
|
||||
if let Some(path) = &self.password_file {
|
||||
if !path.is_file() {
|
||||
return Err(RemoteError::InvalidTarget(format!(
|
||||
"password file not found: {}",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
enum Strategy {
|
||||
Direct,
|
||||
Rroot,
|
||||
UpdateDaemon {
|
||||
local_port: u16,
|
||||
remote_port: u16,
|
||||
tunnel: Child,
|
||||
},
|
||||
}
|
||||
|
||||
impl Drop for Strategy {
|
||||
fn drop(&mut self) {
|
||||
if let Self::UpdateDaemon { tunnel, .. } = self {
|
||||
let _ = tunnel.kill();
|
||||
let _ = tunnel.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SshTransport {
|
||||
options: SshOptions,
|
||||
known_hosts: PathBuf,
|
||||
strategy: Strategy,
|
||||
counter: u64,
|
||||
}
|
||||
|
||||
impl SshTransport {
|
||||
/// Open a session and (when `require_root`) prove a uid-0 channel.
|
||||
pub fn connect(options: SshOptions, require_root: bool) -> Result<Self, RemoteError> {
|
||||
options.validate()?;
|
||||
let known_hosts = options
|
||||
.known_hosts
|
||||
.clone()
|
||||
.unwrap_or_else(|| alkane_core::platform::config_path("known_hosts"));
|
||||
if let Some(parent) = known_hosts.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
if !known_hosts.exists() {
|
||||
fs::write(&known_hosts, b"")?;
|
||||
}
|
||||
if options.password_file.is_some() {
|
||||
Command::new("sshpass")
|
||||
.arg("-V")
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.map_err(|_| RemoteError::MissingTool("sshpass"))?;
|
||||
}
|
||||
let mut transport = Self {
|
||||
options,
|
||||
known_hosts,
|
||||
strategy: Strategy::Direct,
|
||||
counter: 0,
|
||||
};
|
||||
let identity = transport.user_command("uname -r", Duration::from_secs(15))?;
|
||||
let _ = identity;
|
||||
if !require_root {
|
||||
return Ok(transport);
|
||||
}
|
||||
|
||||
let uid =
|
||||
String::from_utf8_lossy(&transport.user_command("id -u", Duration::from_secs(15))?)
|
||||
.trim()
|
||||
.to_owned();
|
||||
let direct = uid == "0";
|
||||
let method = match transport.options.root_method {
|
||||
RootMethod::Auto if direct => RootMethod::Direct,
|
||||
RootMethod::Auto => {
|
||||
if transport.has_update_daemon()? {
|
||||
RootMethod::UpdateDaemon
|
||||
} else if transport.has_rroot()? {
|
||||
RootMethod::Rroot
|
||||
} else {
|
||||
return Err(RemoteError::NoRootMethod);
|
||||
}
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
match method {
|
||||
RootMethod::Direct => {
|
||||
if !direct {
|
||||
return Err(RemoteError::NotRoot(
|
||||
"the SSH login is not uid 0; use --root-method auto, update-daemon or rroot"
|
||||
.to_owned(),
|
||||
));
|
||||
}
|
||||
transport.strategy = Strategy::Direct;
|
||||
}
|
||||
RootMethod::Rroot => {
|
||||
if !transport.has_rroot()? {
|
||||
return Err(RemoteError::NotRoot(
|
||||
"/nvdata/rroot is not present or not executable".to_owned(),
|
||||
));
|
||||
}
|
||||
transport.strategy = Strategy::Rroot;
|
||||
}
|
||||
RootMethod::UpdateDaemon => {
|
||||
if !transport.has_update_daemon()? {
|
||||
return Err(RemoteError::NotRoot(
|
||||
"/usr/sbin/update-daemon is not present".to_owned(),
|
||||
));
|
||||
}
|
||||
let remote_port = transport
|
||||
.options
|
||||
.update_daemon_port
|
||||
.unwrap_or(transport.detect_update_daemon_port()?);
|
||||
let (local_port, tunnel) = transport.start_tunnel(remote_port)?;
|
||||
transport.strategy = Strategy::UpdateDaemon {
|
||||
local_port,
|
||||
remote_port,
|
||||
tunnel,
|
||||
};
|
||||
}
|
||||
RootMethod::Auto => unreachable!(),
|
||||
}
|
||||
|
||||
let root_output = transport.root_command("id", Duration::from_secs(20))?;
|
||||
let root = String::from_utf8_lossy(&root_output);
|
||||
if !root.contains("uid=0") {
|
||||
return Err(RemoteError::NotRoot(
|
||||
"the selected channel did not return uid=0".to_owned(),
|
||||
));
|
||||
}
|
||||
Ok(transport)
|
||||
}
|
||||
|
||||
pub fn channel(&self) -> String {
|
||||
format!("ssh:{}@{}", self.options.user, self.options.host)
|
||||
}
|
||||
|
||||
pub fn root_method(&self) -> &'static str {
|
||||
match &self.strategy {
|
||||
Strategy::Direct => "direct",
|
||||
Strategy::Rroot => "rroot",
|
||||
Strategy::UpdateDaemon { .. } => "update-daemon",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_daemon_port(&self) -> Option<u16> {
|
||||
match &self.strategy {
|
||||
Strategy::UpdateDaemon { remote_port, .. } => Some(*remote_port),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ssh_base(&self) -> Command {
|
||||
let mut command = if let Some(password) = &self.options.password_file {
|
||||
let mut command = Command::new("sshpass");
|
||||
command.arg("-f").arg(password).arg("ssh");
|
||||
command
|
||||
} else {
|
||||
Command::new("ssh")
|
||||
};
|
||||
command
|
||||
.arg("-F")
|
||||
.arg("none")
|
||||
.arg("-o")
|
||||
.arg(if self.options.password_file.is_some() {
|
||||
"BatchMode=no"
|
||||
} else {
|
||||
"BatchMode=yes"
|
||||
})
|
||||
.arg("-o")
|
||||
.arg("StrictHostKeyChecking=accept-new")
|
||||
.arg("-o")
|
||||
.arg(format!("UserKnownHostsFile={}", self.known_hosts.display()))
|
||||
.arg("-o")
|
||||
.arg("GlobalKnownHostsFile=/dev/null")
|
||||
.arg("-o")
|
||||
.arg("ConnectTimeout=10")
|
||||
.arg("-o")
|
||||
.arg("ServerAliveInterval=5")
|
||||
.arg("-o")
|
||||
.arg("ServerAliveCountMax=3")
|
||||
.arg("-o")
|
||||
.arg("RequestTTY=no")
|
||||
.arg("-o")
|
||||
.arg("LogLevel=ERROR")
|
||||
.arg("-o")
|
||||
.arg("NumberOfPasswordPrompts=1")
|
||||
.arg("-o")
|
||||
.arg("PreferredAuthentications=publickey,password,keyboard-interactive");
|
||||
if let Some(identity) = &self.options.identity_file {
|
||||
command
|
||||
.arg("-i")
|
||||
.arg(identity)
|
||||
.arg("-o")
|
||||
.arg("IdentitiesOnly=yes");
|
||||
}
|
||||
command
|
||||
}
|
||||
|
||||
fn ssh_command(&self, command: &str) -> Command {
|
||||
let mut child = self.ssh_base();
|
||||
child
|
||||
.arg("-p")
|
||||
.arg(self.options.port.to_string())
|
||||
.arg(format!("{}@{}", self.options.user, self.options.host))
|
||||
.arg(command);
|
||||
child
|
||||
}
|
||||
|
||||
fn run_user(&self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError> {
|
||||
let (stdout, stderr, status) = run_bounded(self.ssh_command(command), timeout)?;
|
||||
if !status.success() {
|
||||
return Err(RemoteError::Command {
|
||||
status: status.to_string(),
|
||||
stderr: RemoteError::sanitize(&String::from_utf8_lossy(&stderr)),
|
||||
});
|
||||
}
|
||||
Ok(stdout)
|
||||
}
|
||||
|
||||
fn has_rroot(&self) -> Result<bool, RemoteError> {
|
||||
let out = self.run_user(
|
||||
"test -x /nvdata/rroot && echo yes || echo no",
|
||||
Duration::from_secs(15),
|
||||
)?;
|
||||
Ok(String::from_utf8_lossy(&out).contains("yes"))
|
||||
}
|
||||
|
||||
fn has_update_daemon(&self) -> Result<bool, RemoteError> {
|
||||
let out = self.run_user(
|
||||
"test -x /usr/sbin/update-daemon && echo yes || echo no",
|
||||
Duration::from_secs(15),
|
||||
)?;
|
||||
Ok(String::from_utf8_lossy(&out).contains("yes"))
|
||||
}
|
||||
|
||||
fn detect_update_daemon_port(&self) -> Result<u16, RemoteError> {
|
||||
let out = self.run_user(
|
||||
"cat /proc/net/tcp /proc/net/tcp6 2>/dev/null || true",
|
||||
Duration::from_secs(15),
|
||||
)?;
|
||||
let text = String::from_utf8_lossy(&out);
|
||||
for line in text.lines() {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
if fields.len() < 4 || fields[3] != "0A" {
|
||||
continue;
|
||||
}
|
||||
let local = fields[1];
|
||||
let port = local.rsplit(':').next().unwrap_or("");
|
||||
let port = u16::from_str_radix(port, 16).unwrap_or(0);
|
||||
if port == 12887 || port == 22026 {
|
||||
return Ok(port);
|
||||
}
|
||||
}
|
||||
// The CV1835 stock build listens on 12887. The fallback keeps the
|
||||
// explicit --update-daemon-port option available for other builds.
|
||||
Ok(12887)
|
||||
}
|
||||
|
||||
fn start_tunnel(&self, remote_port: u16) -> Result<(u16, Child), RemoteError> {
|
||||
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
|
||||
let local_port = listener.local_addr()?.port();
|
||||
drop(listener);
|
||||
let mut command = self.ssh_base();
|
||||
command
|
||||
.arg("-N")
|
||||
.arg("-o")
|
||||
.arg("ExitOnForwardFailure=yes")
|
||||
.arg("-L")
|
||||
.arg(format!("127.0.0.1:{local_port}:127.0.0.1:{remote_port}"))
|
||||
.arg("-p")
|
||||
.arg(self.options.port.to_string())
|
||||
.arg(format!("{}@{}", self.options.user, self.options.host))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
let mut tunnel = command.spawn()?;
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
loop {
|
||||
if TcpStream::connect_timeout(
|
||||
&SocketAddr::from(([127, 0, 0, 1], local_port)),
|
||||
Duration::from_millis(500),
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
return Ok((local_port, tunnel));
|
||||
}
|
||||
if let Some(status) = tunnel.try_wait()? {
|
||||
return Err(RemoteError::Daemon(format!(
|
||||
"SSH forward exited before it was ready ({status})"
|
||||
)));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
let _ = tunnel.kill();
|
||||
return Err(RemoteError::Daemon(
|
||||
"SSH forward did not become ready".to_owned(),
|
||||
));
|
||||
}
|
||||
thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
}
|
||||
|
||||
fn daemon_send(&self, command: &str) -> Result<(), RemoteError> {
|
||||
let Strategy::UpdateDaemon { local_port, .. } = &self.strategy else {
|
||||
return Err(RemoteError::Daemon("not using update-daemon".to_owned()));
|
||||
};
|
||||
let local_port = *local_port;
|
||||
if command.contains('\n') || command.contains('\r') {
|
||||
return Err(RemoteError::Daemon("command contains a newline".to_owned()));
|
||||
}
|
||||
let mut stream = TcpStream::connect_timeout(
|
||||
&SocketAddr::from(([127, 0, 0, 1], local_port)),
|
||||
Duration::from_secs(10),
|
||||
)?;
|
||||
stream.set_write_timeout(Some(Duration::from_secs(10)))?;
|
||||
stream.write_all(format!(";{command};").as_bytes())?;
|
||||
stream.flush()?;
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
|
||||
let mut sink = [0_u8; 256];
|
||||
let _ = stream.read(&mut sink);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn daemon_capture(&mut self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError> {
|
||||
let path = format!("/tmp/.alkane-root-{}-{}", std::process::id(), self.counter);
|
||||
self.counter += 1;
|
||||
let wrapped = format!("{{ {command} ; }} > {path} 2>&1; chmod 644 {path}");
|
||||
self.daemon_send(&wrapped)?;
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
let probe = format!("test -f {path} && echo ready || true");
|
||||
let out = self.run_user(&probe, Duration::from_secs(15))?;
|
||||
if String::from_utf8_lossy(&out).contains("ready") {
|
||||
break;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(RemoteError::Daemon(format!(
|
||||
"root command produced no output file within {timeout:?}"
|
||||
)));
|
||||
}
|
||||
thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
let output = self.run_user(&format!("cat {path}"), Duration::from_secs(60))?;
|
||||
let _ = self.run_user(&format!("rm -f {path}"), Duration::from_secs(15));
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn daemon_reboot(&mut self) -> Result<(), RemoteError> {
|
||||
self.daemon_send("sync; echo b > /proc/sysrq-trigger")
|
||||
}
|
||||
}
|
||||
|
||||
impl Remote for SshTransport {
|
||||
fn channel(&self) -> &str {
|
||||
"ssh"
|
||||
}
|
||||
|
||||
fn root_method(&self) -> &'static str {
|
||||
SshTransport::root_method(self)
|
||||
}
|
||||
|
||||
fn user_command(&mut self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError> {
|
||||
self.run_user(command, timeout)
|
||||
}
|
||||
|
||||
fn root_command(&mut self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError> {
|
||||
match self.root_method() {
|
||||
"direct" => self.run_user(command, timeout),
|
||||
"rroot" => {
|
||||
let wrapped = format!("/nvdata/rroot -c {}", shell_quote(command));
|
||||
self.run_user(&wrapped, timeout)
|
||||
}
|
||||
"update-daemon" => self.daemon_capture(command, timeout),
|
||||
_ => Err(RemoteError::NoRootMethod),
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, local: &Path, remote: &str, timeout: Duration) -> Result<(), RemoteError> {
|
||||
let remote = safe_remote_path(remote)?;
|
||||
let mut command = self.ssh_command(&format!("cat > {remote}"));
|
||||
command
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
let mut child = command.spawn()?;
|
||||
let mut stdin = child.stdin.take().expect("piped stdin");
|
||||
let path = local.to_path_buf();
|
||||
let writer = thread::spawn(move || -> std::io::Result<()> {
|
||||
let mut source = fs::File::open(path)?;
|
||||
let mut buffer = [0_u8; 64 * 1024];
|
||||
loop {
|
||||
let read = source.read(&mut buffer)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
stdin.write_all(&buffer[..read])?;
|
||||
}
|
||||
stdin.flush()
|
||||
});
|
||||
let (stdout, stderr) = read_pipes(&mut child);
|
||||
let status = wait_timeout(&mut child, timeout)?;
|
||||
let _ = writer.join();
|
||||
let _ = stdout.join();
|
||||
let stderr = stderr.join().unwrap_or_default();
|
||||
if !status.success() {
|
||||
return Err(RemoteError::Command {
|
||||
status: status.to_string(),
|
||||
stderr: RemoteError::sanitize(&String::from_utf8_lossy(&stderr)),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pull(&mut self, remote: &str, local: &Path, timeout: Duration) -> Result<(), RemoteError> {
|
||||
let remote = safe_remote_path(remote)?;
|
||||
let data = self.run_user(&format!("cat {remote}"), timeout)?;
|
||||
if data.len() > MAX_CAPTURE {
|
||||
return Err(RemoteError::OutputTooLarge(MAX_CAPTURE));
|
||||
}
|
||||
fs::write(local, data)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reboot(&mut self) -> Result<(), RemoteError> {
|
||||
match self.root_method() {
|
||||
"update-daemon" => self.daemon_reboot(),
|
||||
_ => {
|
||||
// A successful sysrq reset drops the SSH connection mid-command.
|
||||
let _ = self.run_user(
|
||||
"sync; echo b > /proc/sysrq-trigger",
|
||||
Duration::from_secs(15),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Remote {
|
||||
fn channel(&self) -> &str;
|
||||
fn root_method(&self) -> &'static str {
|
||||
"network"
|
||||
}
|
||||
fn user_command(&mut self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError>;
|
||||
fn root_command(&mut self, command: &str, timeout: Duration) -> Result<Vec<u8>, RemoteError>;
|
||||
fn push(&mut self, local: &Path, remote: &str, timeout: Duration) -> Result<(), RemoteError>;
|
||||
fn pull(&mut self, remote: &str, local: &Path, timeout: Duration) -> Result<(), RemoteError>;
|
||||
fn reboot(&mut self) -> Result<(), RemoteError>;
|
||||
}
|
||||
|
||||
pub fn shell_quote(text: &str) -> String {
|
||||
format!("'{}'", text.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
pub fn safe_remote_path(path: &str) -> Result<&str, RemoteError> {
|
||||
if !path.starts_with('/')
|
||||
|| path.len() > 200
|
||||
|| path.contains("..")
|
||||
|| !path
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'.' | b'_' | b'-'))
|
||||
{
|
||||
return Err(RemoteError::InvalidTarget(format!(
|
||||
"unsafe remote path: {path}"
|
||||
)));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn read_pipes(child: &mut Child) -> (thread::JoinHandle<Vec<u8>>, thread::JoinHandle<Vec<u8>>) {
|
||||
let mut stdout = child.stdout.take().expect("piped stdout");
|
||||
let mut stderr = child.stderr.take().expect("piped stderr");
|
||||
let out = thread::spawn(move || {
|
||||
let mut data = Vec::new();
|
||||
let _ = stdout.read_to_end(&mut data);
|
||||
data
|
||||
});
|
||||
let err = thread::spawn(move || {
|
||||
let mut data = Vec::new();
|
||||
let _ = stderr.read_to_end(&mut data);
|
||||
data
|
||||
});
|
||||
(out, err)
|
||||
}
|
||||
|
||||
fn wait_timeout(child: &mut Child, timeout: Duration) -> Result<ExitStatus, RemoteError> {
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(status);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(RemoteError::Timeout(timeout));
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
fn run_bounded(
|
||||
mut command: Command,
|
||||
timeout: Duration,
|
||||
) -> Result<(Vec<u8>, Vec<u8>, ExitStatus), RemoteError> {
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
let mut child = command.spawn()?;
|
||||
let (stdout, stderr) = read_pipes(&mut child);
|
||||
let status = wait_timeout(&mut child, timeout)?;
|
||||
let stdout = stdout.join().unwrap_or_default();
|
||||
let stderr = stderr.join().unwrap_or_default();
|
||||
if stdout.len() > MAX_CAPTURE {
|
||||
return Err(RemoteError::OutputTooLarge(MAX_CAPTURE));
|
||||
}
|
||||
Ok((stdout, stderr, status))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn quotes_shell_arguments_for_rroot() {
|
||||
assert_eq!(shell_quote("id"), "'id'");
|
||||
assert_eq!(shell_quote("echo 'x'"), "'echo '\\''x'\\'''");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_option_injection_and_unsafe_paths() {
|
||||
let mut options = SshOptions {
|
||||
host: "-oProxyCommand=bad".to_owned(),
|
||||
user: "root".to_owned(),
|
||||
..SshOptions::default()
|
||||
};
|
||||
assert!(options.validate().is_err());
|
||||
options.host = "10.255.1.167".to_owned();
|
||||
options.user = "root;id".to_owned();
|
||||
assert!(options.validate().is_err());
|
||||
assert!(safe_remote_path("/tmp/ok.img").is_ok());
|
||||
assert!(safe_remote_path("relative").is_err());
|
||||
assert!(safe_remote_path("/tmp/../etc/passwd").is_err());
|
||||
assert!(safe_remote_path("/tmp/a;b").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_root_methods() {
|
||||
assert_eq!(RootMethod::parse("auto"), Some(RootMethod::Auto));
|
||||
assert_eq!(
|
||||
RootMethod::parse("update-daemon"),
|
||||
Some(RootMethod::UpdateDaemon)
|
||||
);
|
||||
assert_eq!(RootMethod::parse("serial"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
//! Bug reports and feature requests from the toolbar's Bug report button.
|
||||
//!
|
||||
//! The app posts the report to the report relay (see tools/report-relay),
|
||||
//! which holds the Gitea token and files the issue in blueflare/alkane-toolkit.
|
||||
//! The app itself holds no secret. A report carries its type, the user's text,
|
||||
//! what the app knows about itself (version, OS, appearance, language, window
|
||||
//! size) and, if the user leaves it ticked, the recent activity log with
|
||||
//! credentials scrubbed. Nothing is stored locally.
|
||||
|
||||
use std::io::Write;
|
||||
use std::process::Stdio;
|
||||
use std::sync::mpsc::{channel, Receiver};
|
||||
|
||||
/// Where reports go. `ALKANE_REPORT_URL` overrides it (tests, staging).
|
||||
pub const DEFAULT_URL: &str = "https://gitea.bluefla.re/alkane-report/v1/report";
|
||||
/// Longest report text the relay accepts.
|
||||
pub const MAX_TEXT_CHARS: usize = 8000;
|
||||
/// Log sent with a report: at most this many of the newest lines...
|
||||
const LOG_LINES: usize = 80;
|
||||
/// ...cut to this many bytes on a line boundary.
|
||||
const LOG_BYTES: usize = 16 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Bug,
|
||||
Ui,
|
||||
Feature,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
/// In the order the dialog's type choice lists them.
|
||||
pub const ALL: [Kind; 3] = [Kind::Bug, Kind::Ui, Kind::Feature];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Bug => "Bug",
|
||||
Kind::Ui => "UI change",
|
||||
Kind::Feature => "Feature request",
|
||||
}
|
||||
}
|
||||
|
||||
/// The wire value, which is also the issue label.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Bug => "bug",
|
||||
Kind::Ui => "ui",
|
||||
Kind::Feature => "feature",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the app knows about itself, sent with every report.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Context {
|
||||
pub app_version: String,
|
||||
pub platform: String,
|
||||
pub os: String,
|
||||
pub appearance: String,
|
||||
pub language: String,
|
||||
pub window: String,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
/// The running app's context. `window` is the main window's size.
|
||||
pub fn current(dark: bool, language: &str, window: (i32, i32)) -> Context {
|
||||
Context {
|
||||
app_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
|
||||
os: os_version(),
|
||||
appearance: if dark { "dark" } else { "light" }.to_string(),
|
||||
language: language.to_string(),
|
||||
window: format!("{}x{}", window.0, window.1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A human-readable OS name and version, best effort.
|
||||
fn os_version() -> String {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
if let Ok(s) = std::fs::read_to_string("/etc/os-release") {
|
||||
for line in s.lines() {
|
||||
if let Some(v) = line.strip_prefix("PRETTY_NAME=") {
|
||||
return v.trim_matches('"').to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
"Linux".to_string()
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let out = alkane_core::platform::quiet_command("sw_vers")
|
||||
.arg("-productVersion")
|
||||
.output();
|
||||
match out {
|
||||
Ok(o) if o.status.success() => {
|
||||
format!("macOS {}", String::from_utf8_lossy(&o.stdout).trim())
|
||||
}
|
||||
_ => "macOS".to_string(),
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let out = alkane_core::platform::quiet_command("cmd")
|
||||
.args(["/C", "ver"])
|
||||
.output();
|
||||
match out {
|
||||
Ok(o) if o.status.success() => {
|
||||
let v = String::from_utf8_lossy(&o.stdout).trim().to_string();
|
||||
if v.is_empty() {
|
||||
"Windows".to_string()
|
||||
} else {
|
||||
v
|
||||
}
|
||||
}
|
||||
_ => "Windows".to_string(),
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
|
||||
{
|
||||
std::env::consts::OS.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Names whose values are secrets: `name=value`, `name: value` and
|
||||
/// `"name": "value"` have the value replaced.
|
||||
const SECRET_NAMES: [&str; 12] = [
|
||||
"password",
|
||||
"passwd",
|
||||
"pass",
|
||||
"pwd",
|
||||
"secret",
|
||||
"token",
|
||||
"apikey",
|
||||
"api_key",
|
||||
"authorization",
|
||||
"cookie",
|
||||
"psk",
|
||||
"credential",
|
||||
];
|
||||
|
||||
/// Remove credentials from log text before it leaves the machine: values of
|
||||
/// secret-looking names, `user:password@` in URLs, and PEM private keys.
|
||||
/// What is removed becomes `[redacted]`.
|
||||
pub fn scrub(text: &str) -> String {
|
||||
let mut out = Vec::new();
|
||||
let mut in_pem = false;
|
||||
for line in text.lines() {
|
||||
if line.contains("-----BEGIN") && line.contains("PRIVATE KEY") {
|
||||
in_pem = true;
|
||||
out.push("[redacted]".to_string());
|
||||
continue;
|
||||
}
|
||||
if in_pem {
|
||||
if line.contains("-----END") {
|
||||
in_pem = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
out.push(scrub_line(line));
|
||||
}
|
||||
out.join("\n")
|
||||
}
|
||||
|
||||
fn scrub_line(line: &str) -> String {
|
||||
let mut s = scrub_url_userinfo(line);
|
||||
let lower = s.to_ascii_lowercase();
|
||||
// Walk every occurrence of every secret name; redact the value after the
|
||||
// next `=` or `:` (quotes and spaces skipped) up to whitespace, a quote, a
|
||||
// comma, `&` or `;`.
|
||||
let mut cuts: Vec<(usize, usize)> = Vec::new();
|
||||
for name in SECRET_NAMES {
|
||||
let mut from = 0;
|
||||
while let Some(pos) = lower[from..].find(name) {
|
||||
let start = from + pos;
|
||||
from = start + name.len();
|
||||
let bytes = s.as_bytes();
|
||||
let mut i = start + name.len();
|
||||
// allow a closing quote and spaces between the name and the separator
|
||||
while i < bytes.len() && (bytes[i] == b'"' || bytes[i] == b'\'' || bytes[i] == b' ') {
|
||||
i += 1;
|
||||
}
|
||||
if i >= bytes.len() || (bytes[i] != b'=' && bytes[i] != b':') {
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'"' || bytes[i] == b'\'') {
|
||||
i += 1;
|
||||
}
|
||||
let vstart = i;
|
||||
if name == "authorization" || name == "cookie" {
|
||||
// "Authorization: Bearer <token>", "Cookie: a=b; c=d": the whole
|
||||
// rest of the line is the secret.
|
||||
i = bytes.len();
|
||||
}
|
||||
while i < bytes.len()
|
||||
&& !matches!(bytes[i], b' ' | b'"' | b'\'' | b',' | b'&' | b';' | b'\t')
|
||||
{
|
||||
i += 1;
|
||||
}
|
||||
if i > vstart {
|
||||
cuts.push((vstart, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
if cuts.is_empty() {
|
||||
return s;
|
||||
}
|
||||
cuts.sort();
|
||||
let mut merged: Vec<(usize, usize)> = Vec::new();
|
||||
for (a, b) in cuts {
|
||||
match merged.last_mut() {
|
||||
Some(last) if a <= last.1 => last.1 = last.1.max(b),
|
||||
_ => merged.push((a, b)),
|
||||
}
|
||||
}
|
||||
for (a, b) in merged.into_iter().rev() {
|
||||
if s.is_char_boundary(a) && s.is_char_boundary(b) {
|
||||
s.replace_range(a..b, "[redacted]");
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// `scheme://user:password@host` -> `scheme://user:[redacted]@host`.
|
||||
fn scrub_url_userinfo(line: &str) -> String {
|
||||
let mut s = line.to_string();
|
||||
let mut from = 0;
|
||||
while let Some(p) = s[from..].find("://") {
|
||||
let auth_start = from + p + 3;
|
||||
let rest = &s[auth_start..];
|
||||
let end = rest
|
||||
.find(|c: char| c == '/' || c.is_whitespace())
|
||||
.unwrap_or(rest.len());
|
||||
let authority = &rest[..end];
|
||||
if let Some(at) = authority.rfind('@') {
|
||||
if let Some(colon) = authority[..at].find(':') {
|
||||
let a = auth_start + colon + 1;
|
||||
let b = auth_start + at;
|
||||
s.replace_range(a..b, "[redacted]");
|
||||
}
|
||||
}
|
||||
from = auth_start;
|
||||
if from >= s.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The newest activity-log lines, scrubbed and cut to the size limits.
|
||||
pub fn recent_log(full_log: &str) -> String {
|
||||
let lines: Vec<&str> = full_log.lines().collect();
|
||||
let tail = &lines[lines.len().saturating_sub(LOG_LINES)..];
|
||||
let mut text = scrub(&tail.join("\n"));
|
||||
if text.len() > LOG_BYTES {
|
||||
let mut cut = text.len() - LOG_BYTES;
|
||||
while !text.is_char_boundary(cut) {
|
||||
cut += 1;
|
||||
}
|
||||
text = text[cut..].to_string();
|
||||
if let Some(nl) = text.find('\n') {
|
||||
text = text[nl + 1..].to_string();
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// The JSON body the relay takes.
|
||||
pub fn payload(kind: Kind, text: &str, ctx: &Context, log: Option<&str>) -> String {
|
||||
serde_json::json!({
|
||||
"kind": kind.as_str(),
|
||||
"text": text,
|
||||
"app_version": ctx.app_version,
|
||||
"platform": ctx.platform,
|
||||
"os": ctx.os,
|
||||
"appearance": ctx.appearance,
|
||||
"language": ctx.language,
|
||||
"window": ctx.window,
|
||||
"log": log.unwrap_or(""),
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// A filed issue: its number and web link.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Filed {
|
||||
pub number: u64,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
/// Read the relay's answer: curl's body, then the HTTP status on the last line.
|
||||
pub fn parse_response(curl_stdout: &str) -> Result<Filed, String> {
|
||||
let trimmed = curl_stdout.trim_end();
|
||||
let (body, code) = match trimmed.rfind('\n') {
|
||||
Some(i) => (&trimmed[..i], trimmed[i + 1..].trim()),
|
||||
None => ("", trimmed),
|
||||
};
|
||||
let json: Option<serde_json::Value> = serde_json::from_str(body).ok();
|
||||
if code == "201" || code == "200" {
|
||||
let number = json.as_ref().and_then(|j| j["number"].as_u64());
|
||||
let url = json.as_ref().and_then(|j| j["url"].as_str()).unwrap_or("");
|
||||
return match number {
|
||||
Some(number) => Ok(Filed {
|
||||
number,
|
||||
url: url.to_string(),
|
||||
}),
|
||||
None => Err("the report service answered without an issue number; \
|
||||
check the issue list before sending again"
|
||||
.into()),
|
||||
};
|
||||
}
|
||||
let reason = json
|
||||
.as_ref()
|
||||
.and_then(|j| j["error"].as_str())
|
||||
.map(str::to_string);
|
||||
Err(match (code, reason) {
|
||||
(_, Some(r)) => r,
|
||||
("000", None) | ("", None) => "could not reach the report service".into(),
|
||||
(c, None) => format!("the report service answered HTTP {c}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Send a report on a worker thread; the receiver gets one result.
|
||||
pub fn send(body: String) -> Receiver<Result<Filed, String>> {
|
||||
let url = std::env::var("ALKANE_REPORT_URL").unwrap_or_else(|_| DEFAULT_URL.to_string());
|
||||
let (tx, rx) = channel();
|
||||
std::thread::spawn(move || {
|
||||
let result = (|| {
|
||||
let mut child = alkane_core::platform::quiet_command("curl")
|
||||
.args([
|
||||
"-sS",
|
||||
"--max-time",
|
||||
"40",
|
||||
"-X",
|
||||
"POST",
|
||||
"-H",
|
||||
"Content-Type: application/json",
|
||||
"--data-binary",
|
||||
"@-",
|
||||
"-w",
|
||||
"\n%{http_code}",
|
||||
&url,
|
||||
])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|e| format!("could not run curl: {e}"))?;
|
||||
if let Some(mut si) = child.stdin.take() {
|
||||
let _ = si.write_all(body.as_bytes());
|
||||
}
|
||||
let out = child
|
||||
.wait_with_output()
|
||||
.map_err(|e| format!("curl failed: {e}"))?;
|
||||
parse_response(&String::from_utf8_lossy(&out.stdout))
|
||||
})();
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
rx
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn scrub_removes_credentials_and_keeps_the_rest() {
|
||||
let log = "12:00:01 set pools on 192.168.1.20: url=stratum+tcp://u:hunter2@pool:3333 password=hunter2\n\
|
||||
12:00:02 login {\"user\": \"root\", \"pass\": \"s3cret\"}\n\
|
||||
12:00:03 Authorization: Bearer abc.def\n\
|
||||
-----BEGIN OPENSSH PRIVATE KEY-----\nAAAA\n-----END OPENSSH PRIVATE KEY-----\n\
|
||||
12:00:04 scan finished: 9 miners";
|
||||
let s = scrub(log);
|
||||
assert!(!s.contains("hunter2"), "{s}");
|
||||
assert!(!s.contains("s3cret"), "{s}");
|
||||
assert!(!s.contains("abc.def"), "{s}");
|
||||
assert!(!s.contains("AAAA"), "{s}");
|
||||
assert!(s.contains("192.168.1.20"));
|
||||
assert!(s.contains("\"user\": \"root\""));
|
||||
assert!(s.contains("scan finished: 9 miners"));
|
||||
assert_eq!(s.matches("[redacted]").count(), 5, "{s}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_log_keeps_the_newest_lines_within_limits() {
|
||||
let log: Vec<String> = (0..500)
|
||||
.map(|i| format!("line {i} {}", "x".repeat(300)))
|
||||
.collect();
|
||||
let tail = recent_log(&log.join("\n"));
|
||||
assert!(tail.len() <= LOG_BYTES);
|
||||
assert!(tail.ends_with(&log[499]));
|
||||
assert!(tail.starts_with("line "), "cut on a line boundary");
|
||||
assert!(!tail.contains("line 400 "), "only the newest lines");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn payload_carries_kind_text_and_context() {
|
||||
let ctx = Context {
|
||||
app_version: "1.2.3".into(),
|
||||
platform: "macos-aarch64".into(),
|
||||
os: "macOS 15.1".into(),
|
||||
appearance: "dark".into(),
|
||||
language: "en".into(),
|
||||
window: "1280x800".into(),
|
||||
};
|
||||
let v: serde_json::Value =
|
||||
serde_json::from_str(&payload(Kind::Ui, "Text \"quoted\"", &ctx, None)).unwrap();
|
||||
assert_eq!(v["kind"], "ui");
|
||||
assert_eq!(v["text"], "Text \"quoted\"");
|
||||
assert_eq!(v["app_version"], "1.2.3");
|
||||
assert_eq!(v["log"], "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_parsing() {
|
||||
assert_eq!(
|
||||
parse_response("{\"number\":42,\"url\":\"https://x/42\"}\n201"),
|
||||
Ok(Filed {
|
||||
number: 42,
|
||||
url: "https://x/42".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
parse_response("{\"error\":\"Too many reports; try again later\"}\n429"),
|
||||
Err("Too many reports; try again later".into())
|
||||
);
|
||||
assert_eq!(
|
||||
parse_response("\n000"),
|
||||
Err("could not reach the report service".into())
|
||||
);
|
||||
assert_eq!(
|
||||
parse_response("<html>\n502"),
|
||||
Err("the report service answered HTTP 502".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ impl Lang {
|
||||
Lang::Pt => "Portugu\u{ea}s",
|
||||
}
|
||||
}
|
||||
fn code(self) -> &'static str {
|
||||
pub fn code(self) -> &'static str {
|
||||
match self {
|
||||
Lang::En => "en",
|
||||
Lang::Zh => "zh",
|
||||
@@ -137,6 +137,13 @@ const TABLE: &[(&str, [&str; 6])] = &[
|
||||
("Credentials", ["Credentials", "\u{51ed}\u{636e}", "\u{0423}\u{0447}\u{0451}\u{0442}\u{043d}\u{044b}\u{0435} \u{0434}\u{0430}\u{043d}\u{043d}\u{044b}\u{0435}", "Identifiants", "Credenciales", "Credenciais"]),
|
||||
("Language", ["Language", "\u{8bed}\u{8a00}", "\u{042f}\u{0437}\u{044b}\u{043a}", "Langue", "Idioma", "Idioma"]),
|
||||
("Logs", ["Logs", "\u{65e5}\u{5fd7}", "\u{0416}\u{0443}\u{0440}\u{043d}\u{0430}\u{043b}", "Journaux", "Registros", "Registos"]),
|
||||
("Bug report", ["Bug report", "\u{95ee}\u{9898}\u{53cd}\u{9988}", "\u{421}\u{43e}\u{43e}\u{431}\u{449}\u{438}\u{442}\u{44c} \u{43e}\u{431} \u{43e}\u{448}\u{438}\u{431}\u{43a}\u{435}", "Signaler un bug", "Informar de un error", "Relatar um erro"]),
|
||||
("Type", ["Type", "\u{7c7b}\u{578b}", "\u{422}\u{438}\u{43f}", "Type", "Tipo", "Tipo"]),
|
||||
("Bug", ["Bug", "\u{7f3a}\u{9677}", "\u{41e}\u{448}\u{438}\u{431}\u{43a}\u{430}", "Bug", "Error", "Erro"]),
|
||||
("UI change", ["UI change", "\u{754c}\u{9762}\u{4fee}\u{6539}", "\u{418}\u{437}\u{43c}\u{435}\u{43d}\u{435}\u{43d}\u{438}\u{435} \u{438}\u{43d}\u{442}\u{435}\u{440}\u{444}\u{435}\u{439}\u{441}\u{430}", "Modification de l'interface", "Cambio de interfaz", "Altera\u{e7}\u{e3}o da interface"]),
|
||||
("Feature request", ["Feature request", "\u{529f}\u{80fd}\u{5efa}\u{8bae}", "\u{41f}\u{440}\u{435}\u{434}\u{43b}\u{43e}\u{436}\u{435}\u{43d}\u{438}\u{435} \u{444}\u{443}\u{43d}\u{43a}\u{446}\u{438}\u{438}", "Demande de fonctionnalit\u{e9}", "Solicitud de funci\u{f3}n", "Pedido de recurso"]),
|
||||
("Send", ["Send", "\u{53d1}\u{9001}", "\u{41e}\u{442}\u{43f}\u{440}\u{430}\u{432}\u{438}\u{442}\u{44c}", "Envoyer", "Enviar", "Enviar"]),
|
||||
("Open issue", ["Open issue", "\u{6253}\u{5f00}\u{95ee}\u{9898}", "\u{41e}\u{442}\u{43a}\u{440}\u{44b}\u{442}\u{44c} \u{437}\u{430}\u{434}\u{430}\u{447}\u{443}", "Ouvrir le ticket", "Abrir incidencia", "Abrir issue"]),
|
||||
// KPI captions
|
||||
("Total", ["Total", "\u{603b}\u{6570}", "\u{0412}\u{0441}\u{0435}\u{0433}\u{043e}", "Total", "Total", "Total"]),
|
||||
("Hashing", ["Hashing", "\u{6b63}\u{5728}\u{6316}\u{77ff}", "\u{0425}\u{0435}\u{0448}\u{0438}\u{0440}\u{043e}\u{0432}\u{0430}\u{043d}\u{0438}\u{0435}", "Minage", "Minando", "Minerando"]),
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
mod access_probe;
|
||||
mod askpass;
|
||||
mod bug_report;
|
||||
mod credentials;
|
||||
mod export;
|
||||
mod fixtures;
|
||||
@@ -99,6 +100,17 @@ fn run_selftest() -> i32 {
|
||||
let frame = wx_rs::Widget::main_frame();
|
||||
let mut app = ui::build(frame);
|
||||
let ok = app.run_fixture_selftest();
|
||||
// ALKANE_SNAPSHOT=path (macOS): also write a PNG of the window as the app
|
||||
// draws it, to check rendering without screen-recording permission.
|
||||
if let Some(path) = std::env::var_os("ALKANE_SNAPSHOT") {
|
||||
let path = path.to_string_lossy();
|
||||
let wrote = wx_rs::snapshot_png(&frame, &path);
|
||||
println!(
|
||||
"SNAPSHOT {} {}",
|
||||
if wrote { "wrote" } else { "unavailable" },
|
||||
path
|
||||
);
|
||||
}
|
||||
println!("SELFTEST {}", if ok { "PASS" } else { "FAIL" });
|
||||
if ok {
|
||||
0
|
||||
|
||||
@@ -22,6 +22,12 @@ pub const ID_PRESETS: i32 = 108;
|
||||
pub const ID_EXPORT: i32 = 109;
|
||||
// Settings menu (round 15 #13): the toolbar button + its menu items.
|
||||
pub const ID_SETTINGS: i32 = 110;
|
||||
// Bug report / feature request dialog (toolbar, between Export and Settings).
|
||||
pub const ID_BUG_REPORT: i32 = 111;
|
||||
const ID_REPORT_SEND: i32 = 240;
|
||||
const ID_REPORT_CLOSE: i32 = 241;
|
||||
const ID_REPORT_OPEN: i32 = 242;
|
||||
const ID_REPORT_KIND: i32 = 243;
|
||||
const ID_LANG_BASE: i32 = 790; // one id per language (790 + Lang index); reserves 790..790+Lang::all().len()
|
||||
const ID_LOGS_OPEN: i32 = 796; // open the Logs page
|
||||
const ID_LOGS_REFRESH: i32 = 797;
|
||||
@@ -791,6 +797,15 @@ pub struct App {
|
||||
// Settings > Logs page (round 15 #13).
|
||||
logs_dialog: Widget,
|
||||
logs_text: Widget,
|
||||
// Bug report dialog (bug_report.rs): its controls, the send in flight and
|
||||
// the last filed issue's link.
|
||||
report_dialog: Widget,
|
||||
report_kind: Widget,
|
||||
report_text: Widget,
|
||||
report_log: Widget,
|
||||
report_status: Widget,
|
||||
report_rx: Option<std::sync::mpsc::Receiver<Result<crate::bug_report::Filed, String>>>,
|
||||
report_url: Option<String>,
|
||||
// Restore-to-stock (round 12 #8a): background job + its typed-confirm dialog.
|
||||
restore: Option<restore::RestoreHandle>,
|
||||
restore_dialog: Widget,
|
||||
@@ -1024,6 +1039,7 @@ pub fn build(frame: Widget) -> App {
|
||||
let _filter_btn = tbtn("Filter", ID_FILTER);
|
||||
let _columns_btn = tbtn("Columns", ID_COLUMNS);
|
||||
let _export_btn = tbtn("Export", ID_EXPORT);
|
||||
let _report_btn = tbtn("Bug report", ID_BUG_REPORT);
|
||||
// The old Credentials button is now a Settings menu (round 15 #13).
|
||||
let _creds_btn = tbtn("Settings", ID_SETTINGS);
|
||||
root.add_sizer(ctl, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 4);
|
||||
@@ -1149,6 +1165,13 @@ pub fn build(frame: Widget) -> App {
|
||||
logview_dialog: frame,
|
||||
logs_dialog: frame,
|
||||
logs_text: frame,
|
||||
report_dialog: frame,
|
||||
report_kind: frame,
|
||||
report_text: frame,
|
||||
report_log: frame,
|
||||
report_status: frame,
|
||||
report_rx: None,
|
||||
report_url: None,
|
||||
restore: None,
|
||||
restore_dialog: frame,
|
||||
pending_restore: Vec::new(),
|
||||
@@ -3628,6 +3651,7 @@ impl App {
|
||||
self.drain_refresh();
|
||||
self.drain_access_probe();
|
||||
self.drain_restore();
|
||||
self.drain_report();
|
||||
// A completed background log fetch yields a viewer dialog to show; return
|
||||
// it so `dispatch` presents it modally after the App borrow is released
|
||||
// (round 18 #12).
|
||||
@@ -4348,6 +4372,168 @@ impl App {
|
||||
|
||||
/// Build (but do not show) the Logs page (round 15 #13): the in-app activity
|
||||
/// log with Refresh / Clear / Close.
|
||||
/// The Bug report dialog: a type (Bug, UI change, Feature request), one text
|
||||
/// box whose first line becomes the issue title, and whether to include the
|
||||
/// recent activity log (scrubbed). Send files it through the report relay
|
||||
/// (bug_report.rs) and shows the issue number, or the reason, in the dialog.
|
||||
fn build_report_dialog(&mut self) -> Widget {
|
||||
let frame = Widget::main_frame();
|
||||
let t = crate::i18n::t;
|
||||
let dlg = Widget::dialog(frame, &t("Bug report"));
|
||||
let root = Widget::box_sizer(true);
|
||||
let kindrow = Widget::box_sizer(false);
|
||||
kindrow.add(
|
||||
Widget::static_text(dlg, &t("Type")),
|
||||
0,
|
||||
sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_RIGHT,
|
||||
8,
|
||||
);
|
||||
let kind = Widget::choice(dlg, ID_REPORT_KIND);
|
||||
for k in crate::bug_report::Kind::ALL {
|
||||
kind.choice_append(&t(k.label()));
|
||||
}
|
||||
kind.choice_set_selection(0);
|
||||
kindrow.add(kind, 0, sf::ALIGN_CENTRE_VERTICAL, 0);
|
||||
root.add_sizer(kindrow, 0, sf::BORDER_ALL, 8);
|
||||
root.add(
|
||||
Widget::static_text(
|
||||
dlg,
|
||||
&t("Describe the problem or the idea. The first line becomes the title."),
|
||||
),
|
||||
0,
|
||||
sf::BORDER_LEFT | sf::BORDER_RIGHT,
|
||||
8,
|
||||
);
|
||||
let text = Widget::text_ctrl(dlg, true);
|
||||
text.set_min_size(560, 220);
|
||||
root.add(text, 1, sf::EXPAND | sf::BORDER_ALL, 8);
|
||||
let log = Widget::check_box(
|
||||
dlg,
|
||||
&t("Include the recent activity log (passwords removed)"),
|
||||
);
|
||||
log.set_checked(true);
|
||||
root.add(log, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 8);
|
||||
root.add(
|
||||
Widget::static_text(
|
||||
dlg,
|
||||
&t("Reports are public issues on gitea.bluefla.re. The app version and OS are included."),
|
||||
),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
8,
|
||||
);
|
||||
let status = Widget::static_text(dlg, "");
|
||||
root.add(
|
||||
status,
|
||||
0,
|
||||
sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT,
|
||||
8,
|
||||
);
|
||||
let btns = Widget::box_sizer(false);
|
||||
let open = Widget::button(dlg, &t("Open issue"), ID_REPORT_OPEN);
|
||||
btns.add(open, 0, sf::BORDER_ALL, 6);
|
||||
btns.add_stretch(1);
|
||||
btns.add(
|
||||
Widget::button(dlg, &t("Close"), ID_REPORT_CLOSE),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
6,
|
||||
);
|
||||
btns.add(
|
||||
Widget::button(dlg, &t("Send"), ID_REPORT_SEND),
|
||||
0,
|
||||
sf::BORDER_ALL,
|
||||
6,
|
||||
);
|
||||
root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6);
|
||||
root.set_sizer_on(dlg);
|
||||
dlg.set_min_size(600, 440);
|
||||
dlg.fit(dlg);
|
||||
self.report_dialog = dlg;
|
||||
self.report_kind = kind;
|
||||
self.report_text = text;
|
||||
self.report_log = log;
|
||||
self.report_status = status;
|
||||
self.report_url = None;
|
||||
dlg
|
||||
}
|
||||
|
||||
/// Validate the Bug report dialog and send it on a worker thread.
|
||||
fn send_report(&mut self) {
|
||||
let t = crate::i18n::t;
|
||||
if self.report_rx.is_some() {
|
||||
return; // one send at a time
|
||||
}
|
||||
let text = self.report_text.get_value();
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
self.report_status
|
||||
.set_label(&t("Write what happened or what you would like first."));
|
||||
return;
|
||||
}
|
||||
if text.chars().count() > crate::bug_report::MAX_TEXT_CHARS {
|
||||
self.report_status.set_label(&format!(
|
||||
"{} ({} / {})",
|
||||
t("The text is too long"),
|
||||
text.chars().count(),
|
||||
crate::bug_report::MAX_TEXT_CHARS
|
||||
));
|
||||
return;
|
||||
}
|
||||
let kinds = crate::bug_report::Kind::ALL;
|
||||
let kind = usize::try_from(self.report_kind.choice_get_selection())
|
||||
.ok()
|
||||
.and_then(|i| kinds.get(i).copied())
|
||||
.unwrap_or(crate::bug_report::Kind::Bug);
|
||||
let size = wx_rs::get_client_size();
|
||||
let ctx = crate::bug_report::Context::current(
|
||||
wx_rs::is_dark(),
|
||||
crate::i18n::current().code(),
|
||||
(size.width as i32, size.height as i32),
|
||||
);
|
||||
let log = self
|
||||
.report_log
|
||||
.is_checked()
|
||||
.then(|| crate::bug_report::recent_log(&crate::logs::dump()));
|
||||
let body = crate::bug_report::payload(kind, text, &ctx, log.as_deref());
|
||||
self.report_status.set_label(&t("Sending..."));
|
||||
self.report_rx = Some(crate::bug_report::send(body));
|
||||
}
|
||||
|
||||
/// Show the Bug report result in the dialog once the send finishes.
|
||||
fn drain_report(&mut self) {
|
||||
let Some(rx) = &self.report_rx else { return };
|
||||
let result = match rx.try_recv() {
|
||||
Ok(r) => r,
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => return,
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
|
||||
Err("the report was not sent".to_string())
|
||||
}
|
||||
};
|
||||
self.report_rx = None;
|
||||
let t = crate::i18n::t;
|
||||
match result {
|
||||
Ok(filed) => {
|
||||
crate::logs::log(format!("bug report filed as issue #{}", filed.number));
|
||||
self.report_status.set_label(&format!(
|
||||
"{} #{}",
|
||||
t("Thank you. Filed as issue"),
|
||||
filed.number
|
||||
));
|
||||
self.report_text.set_value("");
|
||||
self.report_kind.choice_set_selection(0);
|
||||
if !filed.url.is_empty() {
|
||||
self.report_url = Some(filed.url);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
crate::logs::log(format!("bug report not sent: {e}"));
|
||||
self.report_status
|
||||
.set_label(&format!("{} {e}", t("Not sent:")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build_logs_dialog(&mut self) -> Widget {
|
||||
let frame = Widget::main_frame();
|
||||
let dlg = Widget::dialog(frame, &crate::i18n::t("Logs"));
|
||||
@@ -4933,6 +5119,17 @@ impl App {
|
||||
ID_EXPORT_ALL => self.export_check_all(true),
|
||||
ID_EXPORT_NONE => self.export_check_all(false),
|
||||
ID_SETTINGS => self.open_settings_menu(),
|
||||
ID_BUG_REPORT => return Some(self.build_report_dialog()),
|
||||
ID_REPORT_SEND => self.send_report(),
|
||||
ID_REPORT_CLOSE => self.report_dialog.close(0),
|
||||
ID_REPORT_OPEN => match &self.report_url {
|
||||
Some(url) => {
|
||||
wx_rs::launch_browser(url);
|
||||
}
|
||||
None => self.report_status.set_label(&crate::i18n::t(
|
||||
"Send a report first; its issue opens here.",
|
||||
)),
|
||||
},
|
||||
ID_LOGS_REFRESH => self.logs_text.set_value(&crate::logs::dump()),
|
||||
ID_LOGS_CLEAR => {
|
||||
crate::logs::clear();
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# Installing and removing alkane-os
|
||||
|
||||
The CLI (`alkane-cli afw ...`) is the supported flashing path. In-app (GUI)
|
||||
flashing is disabled while that path is reworked; it will call the same engine.
|
||||
|
||||
## Compatible miners
|
||||
|
||||
```
|
||||
alkane-cli afw compat
|
||||
```
|
||||
|
||||
Lists the control boards alkane-os can be installed on. For now that is the
|
||||
Antminer S17 (`zynq-7010`). The install/restore commands refuse any board whose
|
||||
`.afw` is not one of these.
|
||||
|
||||
## Install
|
||||
|
||||
From a local bundle:
|
||||
|
||||
```
|
||||
alkane-cli afw install path/to/alkane-os-<ver>-zynq-7010-armv7.afw \
|
||||
--host <miner-ip> --confirm FLASH
|
||||
```
|
||||
|
||||
From the latest release (pulled from Gitea, not GitHub, which is retired):
|
||||
|
||||
```
|
||||
alkane-cli afw install --latest --board zynq-7010 --host <miner-ip> --confirm FLASH
|
||||
# or fetch only:
|
||||
alkane-cli afw fetch-latest --board zynq-7010 --output ./downloads
|
||||
```
|
||||
|
||||
A private release repo needs a token, read from `ALKANE_RELEASE_TOKEN` (else
|
||||
`GITEA_TOKEN`) at run time and passed to curl through a 0600 config file - never
|
||||
on the command line, never stored by the toolkit.
|
||||
|
||||
### A board still on stock
|
||||
|
||||
Writing our first image onto a board that is still on genuine stock (past the
|
||||
stock gates and getting root) is done by the toolkit itself, over the network.
|
||||
The method is compiled into this binary; nothing else needs to be installed on
|
||||
your machine. Add `--from-stock`:
|
||||
|
||||
```
|
||||
alkane-cli afw install --latest --board zynq-7010 --host <miner-ip> \
|
||||
--from-stock --confirm FLASH
|
||||
```
|
||||
|
||||
The toolkit acquires and verifies the `.afw`, gates on compatibility, performs
|
||||
the network-only stock-side install, then you verify the board came up as
|
||||
alkane:
|
||||
|
||||
```
|
||||
alkane-cli afw verify-live --host <miner-ip> --timeout 300
|
||||
```
|
||||
|
||||
Without `--from-stock`, `install` performs a tier-2 update of a board already on
|
||||
alkane: it writes the dtb (`/dev/mtd0 @ 0x1a00000`), the kernel
|
||||
(`/dev/mtd0 @ 0x2000000`) and the rootfs (`/dev/mtd1`), holds a backup of each,
|
||||
reads them back (md5), and never writes `/dev/mtd0` below `0x1a00000`
|
||||
(BOOT.bin/FSBL/FPGA/U-Boot are preserved).
|
||||
|
||||
## Remove (back to stock)
|
||||
|
||||
```
|
||||
alkane-cli afw restore-stock --host <miner-ip> --confirm FLASH
|
||||
```
|
||||
|
||||
Returning an aftermarket board to genuine stock is also done by the toolkit
|
||||
itself, over the network. You then verify independently that the board no longer
|
||||
answers as alkane and presents its stock OS.
|
||||
@@ -26,3 +26,21 @@ report them. Try **Check access** and the Credentials dialog.
|
||||
|
||||
**The window is too small or too large.** It opens at most as large as your
|
||||
screen's work area. Use the zoom slider in the status bar to scale the table.
|
||||
|
||||
## Reporting a problem
|
||||
|
||||
**Bug report** in the toolbar, between Export and Settings, files a bug or a
|
||||
feature request with the developers. Choose the type (Bug, UI change or
|
||||
Feature request) and describe it; the first line becomes the title. **Send**
|
||||
shows the issue number when it is filed, and **Open issue** opens it in the
|
||||
browser. If it was not sent, the reason is shown and the text stays in the
|
||||
box.
|
||||
|
||||
A report includes the app version, the operating system, the light or dark
|
||||
appearance, the language and the window size. **Include the recent activity
|
||||
log** adds the newest lines of the Settings > Logs page, with passwords,
|
||||
tokens and similar values removed first; untick it to leave the log out.
|
||||
Reports become public issues on
|
||||
[gitea.bluefla.re](https://gitea.bluefla.re/blueflare/alkane-toolkit/issues),
|
||||
so do not put passwords or customer details in the text. A computer can send
|
||||
five reports an hour.
|
||||
|
||||
@@ -17,7 +17,7 @@ PREFIX="${WX_MACOS_PREFIX:-$HOME/.cache/wx-3.3.3-macos}"
|
||||
export WX_RS_WXCONFIG="$PREFIX/bin/wx-config"
|
||||
export MACOSX_DEPLOYMENT_TARGET="${MACOSX_MIN:-11.0}"
|
||||
for target in aarch64-apple-darwin x86_64-apple-darwin; do
|
||||
cargo build --release --offline --locked -p alkane-gui --target "$target" "$@"
|
||||
cargo build --release --offline -p alkane-gui --target "$target" "$@"
|
||||
done
|
||||
out=target/universal-apple-darwin/release
|
||||
mkdir -p "$out"
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
Subject: [PATCH 0010] macOS: native alternating rows, theme text colour, self-test snapshot
|
||||
|
||||
--- a/build.rs
|
||||
+++ b/build.rs
|
||||
@@ -278,6 +278,12 @@
|
||||
build.cpp(true)
|
||||
.file("cpp_src/wxbridge.cpp")
|
||||
.file("cpp_src/widgets_bridge.cpp");
|
||||
+ if is_osx() {
|
||||
+ // Cocoa calls wx does not wrap (native alternating rows, self-test
|
||||
+ // snapshot); clang compiles .mm as Objective-C++.
|
||||
+ println!("cargo:rerun-if-changed=cpp_src/osx_native.mm");
|
||||
+ build.file("cpp_src/osx_native.mm");
|
||||
+ }
|
||||
let mut flags = cxxflags.split_whitespace();
|
||||
while let Some(f) = flags.next() {
|
||||
// A universal wx prefix reports `-arch arm64 -arch x86_64`; cargo builds
|
||||
--- a/cpp_src/widgets_bridge.cpp
|
||||
+++ b/cpp_src/widgets_bridge.cpp
|
||||
@@ -597,7 +597,11 @@
|
||||
} else if (GetAttr().HasBackgroundColour()) {
|
||||
cellbg = GetAttr().GetBackgroundColour();
|
||||
} else {
|
||||
+#ifdef __WXOSX__
|
||||
+ cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
|
||||
+#else
|
||||
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
|
||||
+#endif
|
||||
}
|
||||
x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
|
||||
continue;
|
||||
@@ -688,6 +692,11 @@
|
||||
(unsigned char)(c.blue * 255.0 + 0.5));
|
||||
}
|
||||
}
|
||||
+#elif defined(__WXOSX__)
|
||||
+ // The DC arrives with the control's foreground colour, which is not the
|
||||
+ // theme-aware label colour native cells use; take the list text colour so
|
||||
+ // uncoloured segments follow light/dark like the native columns.
|
||||
+ return wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT);
|
||||
#endif
|
||||
return wxColour();
|
||||
}
|
||||
@@ -1463,8 +1472,21 @@
|
||||
|
||||
// Set (or clear, when r<0) the alternating-row (zebra) background colour. The
|
||||
// app passes a theme-aware colour; odd rows get it (see AttrListStore).
|
||||
+#ifdef __WXOSX__
|
||||
+extern "C" void wxbr_osx_set_alternating_rows(void* win, int on);
|
||||
+#endif
|
||||
void wxbr_dvlc_set_zebra(void* win, int r, int g, int b) {
|
||||
+#ifdef __WXOSX__
|
||||
+ // wxOSX draws custom cells without clipping them to the cell, so the
|
||||
+ // renderer's over-sized background fill (which GTK/MSW clip) painted over
|
||||
+ // neighbouring cells and hid their text until a row was selected. Use the
|
||||
+ // table's native alternating rows instead: AppKit paints them under every
|
||||
+ // cell, in the theme's colours, and no row carries a background attribute.
|
||||
+ dvlc_store(win)->zebra = wxColour();
|
||||
+ wxbr_osx_set_alternating_rows(win, r >= 0 ? 1 : 0);
|
||||
+#else
|
||||
dvlc_store(win)->zebra = (r < 0) ? wxColour() : wxColour(r, g, b);
|
||||
+#endif
|
||||
}
|
||||
|
||||
// The model-row index of the first (top) visible row, or -1 if none. Used to
|
||||
--- a/cpp_src/osx_native.mm
|
||||
+++ b/cpp_src/osx_native.mm
|
||||
@@ -0,0 +1,60 @@
|
||||
+// osx_native.mm -- alkane-toolkit extension: the few wxOSX/Cocoa calls the
|
||||
+// bridge needs that wx does not wrap. Compiled on macOS only (see build.rs).
|
||||
+
|
||||
+#include <wx/wx.h>
|
||||
+#include <wx/dataview.h>
|
||||
+
|
||||
+#import <Cocoa/Cocoa.h>
|
||||
+
|
||||
+// The NSTableView (NSOutlineView) behind a wxDataViewCtrl. wx's handle is the
|
||||
+// enclosing NSScrollView.
|
||||
+static NSTableView* TableOf(wxWindow* win) {
|
||||
+ if (!win) return nil;
|
||||
+ id h = (id)win->GetHandle();
|
||||
+ if ([h isKindOfClass:[NSTableView class]]) return (NSTableView*)h;
|
||||
+ if ([h isKindOfClass:[NSScrollView class]]) {
|
||||
+ id doc = [(NSScrollView*)h documentView];
|
||||
+ if ([doc isKindOfClass:[NSTableView class]]) return (NSTableView*)doc;
|
||||
+ }
|
||||
+ return nil;
|
||||
+}
|
||||
+
|
||||
+extern "C" {
|
||||
+
|
||||
+// Native alternating-row backgrounds. AppKit paints them under every cell,
|
||||
+// custom-drawn ones included, in the theme's own colours (light and dark), so
|
||||
+// custom renderers never paint row backgrounds on macOS.
|
||||
+void wxbr_osx_set_alternating_rows(void* win, int on) {
|
||||
+ NSTableView* tv = TableOf((wxWindow*)win);
|
||||
+ if (tv) [tv setUsesAlternatingRowBackgroundColors:(on ? YES : NO)];
|
||||
+}
|
||||
+
|
||||
+// Write a PNG of a top-level window's content, rendered by the app itself
|
||||
+// (no screen-recording permission needed). Used by the self-test with
|
||||
+// ALKANE_SNAPSHOT=path to check what the table really draws. Returns 1 on
|
||||
+// success.
|
||||
+int wxbr_osx_snapshot(void* win, const char* path) {
|
||||
+ wxWindow* w = (wxWindow*)win;
|
||||
+ if (!w || !path) return 0;
|
||||
+ wxTopLevelWindow* tlw = wxDynamicCast(wxGetTopLevelParent(w), wxTopLevelWindow);
|
||||
+ if (!tlw) return 0;
|
||||
+ tlw->Show();
|
||||
+ tlw->Raise();
|
||||
+ // Let the window lay out and paint before capturing it.
|
||||
+ for (int i = 0; i < 30; ++i) {
|
||||
+ wxYield();
|
||||
+ wxMilliSleep(30);
|
||||
+ }
|
||||
+ NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
|
||||
+ NSView* view = [nsw contentView];
|
||||
+ if (!view) return 0;
|
||||
+ NSRect rect = [view bounds];
|
||||
+ NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
|
||||
+ if (!rep) return 0;
|
||||
+ [view cacheDisplayInRect:rect toBitmapImageRep:rep];
|
||||
+ NSData* png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
|
||||
+ if (!png) return 0;
|
||||
+ return [png writeToFile:[NSString stringWithUTF8String:path] atomically:YES] ? 1 : 0;
|
||||
+}
|
||||
+
|
||||
+}
|
||||
--- a/src/widgets.rs
|
||||
+++ b/src/widgets.rs
|
||||
@@ -107,6 +107,8 @@
|
||||
pub fn wxbr_launch_browser(url: *const c_char) -> c_int;
|
||||
pub fn wxbr_set_appearance_system();
|
||||
pub fn wxbr_is_dark() -> c_int;
|
||||
+ #[cfg(target_os = "macos")]
|
||||
+ pub fn wxbr_osx_snapshot(win: *mut c_void, path: *const c_char) -> c_int;
|
||||
pub fn wxbr_system_color(which: c_int, r: *mut u8, g: *mut u8, b: *mut u8);
|
||||
pub fn wxbr_set_bg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
|
||||
pub fn wxbr_set_fg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
|
||||
@@ -271,6 +273,22 @@
|
||||
unsafe { notsafe::wxbr_is_dark() != 0 }
|
||||
}
|
||||
|
||||
+/// Write a PNG of `win`'s top-level window as the app itself renders it (shows
|
||||
+/// the window and lets it paint first). macOS only, for the self-test's
|
||||
+/// `ALKANE_SNAPSHOT`; returns false elsewhere or on failure.
|
||||
+pub fn snapshot_png(win: &Widget, path: &str) -> bool {
|
||||
+ #[cfg(target_os = "macos")]
|
||||
+ {
|
||||
+ let Ok(p) = CString::new(path) else { return false };
|
||||
+ unsafe { notsafe::wxbr_osx_snapshot(win.0, p.as_ptr()) != 0 }
|
||||
+ }
|
||||
+ #[cfg(not(target_os = "macos"))]
|
||||
+ {
|
||||
+ let _ = (win, path);
|
||||
+ false
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
/// A theme colour. `which`: 0=window bg, 1=window text, 2=highlight,
|
||||
/// 3=button face, 4=grey text. Returns (r, g, b).
|
||||
pub fn system_color(which: i32) -> (u8, u8, u8) {
|
||||
Vendored
+1
@@ -28,6 +28,7 @@ later changes go in new patches.
|
||||
| 0007 | `wxbridge.cpp` on wxMSW: no input-swallowing overlay, appearance before the first window, work-area sizing, executable icon, UTF-8 menu fix |
|
||||
| 0008 | Widget bridge on wxMSW: generic data-view input and tooltips, DIP boundary, anti-aliased shapes, themed selection colours |
|
||||
| 0009 | macOS: wxOSX (universal static) through `wx-config`, logical sizes on Apple, clang compiler runtime for `@available` |
|
||||
| 0010 | macOS table: native alternating rows instead of the unclipped custom-cell background fill (it hid neighbouring cells' text), theme-aware text colour, `osx_native.mm`, self-test window snapshot |
|
||||
|
||||
History: the round 19 health-tooltip fix (GTK tip area converted from
|
||||
bin-window to widget coordinates) used to be a separate patch on top of an
|
||||
|
||||
@@ -278,6 +278,12 @@ fn build_with_wx_config() -> Result<(), Box<dyn Error>> {
|
||||
build.cpp(true)
|
||||
.file("cpp_src/wxbridge.cpp")
|
||||
.file("cpp_src/widgets_bridge.cpp");
|
||||
if is_osx() {
|
||||
// Cocoa calls wx does not wrap (native alternating rows, self-test
|
||||
// snapshot); clang compiles .mm as Objective-C++.
|
||||
println!("cargo:rerun-if-changed=cpp_src/osx_native.mm");
|
||||
build.file("cpp_src/osx_native.mm");
|
||||
}
|
||||
let mut flags = cxxflags.split_whitespace();
|
||||
while let Some(f) = flags.next() {
|
||||
// A universal wx prefix reports `-arch arm64 -arch x86_64`; cargo builds
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// osx_native.mm -- alkane-toolkit extension: the few wxOSX/Cocoa calls the
|
||||
// bridge needs that wx does not wrap. Compiled on macOS only (see build.rs).
|
||||
|
||||
#include <wx/wx.h>
|
||||
#include <wx/dataview.h>
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
// The NSTableView (NSOutlineView) behind a wxDataViewCtrl. wx's handle is the
|
||||
// enclosing NSScrollView.
|
||||
static NSTableView* TableOf(wxWindow* win) {
|
||||
if (!win) return nil;
|
||||
id h = (id)win->GetHandle();
|
||||
if ([h isKindOfClass:[NSTableView class]]) return (NSTableView*)h;
|
||||
if ([h isKindOfClass:[NSScrollView class]]) {
|
||||
id doc = [(NSScrollView*)h documentView];
|
||||
if ([doc isKindOfClass:[NSTableView class]]) return (NSTableView*)doc;
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
// Native alternating-row backgrounds. AppKit paints them under every cell,
|
||||
// custom-drawn ones included, in the theme's own colours (light and dark), so
|
||||
// custom renderers never paint row backgrounds on macOS.
|
||||
void wxbr_osx_set_alternating_rows(void* win, int on) {
|
||||
NSTableView* tv = TableOf((wxWindow*)win);
|
||||
if (tv) [tv setUsesAlternatingRowBackgroundColors:(on ? YES : NO)];
|
||||
}
|
||||
|
||||
// Write a PNG of a top-level window's content, rendered by the app itself
|
||||
// (no screen-recording permission needed). Used by the self-test with
|
||||
// ALKANE_SNAPSHOT=path to check what the table really draws. Returns 1 on
|
||||
// success.
|
||||
int wxbr_osx_snapshot(void* win, const char* path) {
|
||||
wxWindow* w = (wxWindow*)win;
|
||||
if (!w || !path) return 0;
|
||||
wxTopLevelWindow* tlw = wxDynamicCast(wxGetTopLevelParent(w), wxTopLevelWindow);
|
||||
if (!tlw) return 0;
|
||||
tlw->Show();
|
||||
tlw->Raise();
|
||||
// Let the window lay out and paint before capturing it.
|
||||
for (int i = 0; i < 30; ++i) {
|
||||
wxYield();
|
||||
wxMilliSleep(30);
|
||||
}
|
||||
NSWindow* nsw = (NSWindow*)tlw->GetWXWindow();
|
||||
NSView* view = [nsw contentView];
|
||||
if (!view) return 0;
|
||||
NSRect rect = [view bounds];
|
||||
NSBitmapImageRep* rep = [view bitmapImageRepForCachingDisplayInRect:rect];
|
||||
if (!rep) return 0;
|
||||
[view cacheDisplayInRect:rect toBitmapImageRep:rep];
|
||||
NSData* png = [rep representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
|
||||
if (!png) return 0;
|
||||
return [png writeToFile:[NSString stringWithUTF8String:path] atomically:YES] ? 1 : 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -597,7 +597,11 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
|
||||
} else if (GetAttr().HasBackgroundColour()) {
|
||||
cellbg = GetAttr().GetBackgroundColour();
|
||||
} else {
|
||||
#ifdef __WXOSX__
|
||||
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
|
||||
#else
|
||||
cellbg = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
|
||||
#endif
|
||||
}
|
||||
x += DrawShape(dc, shape, x, cell, seg.has_colour ? seg.colour : plain, cellbg);
|
||||
continue;
|
||||
@@ -688,6 +692,11 @@ class SegmentRenderer : public wxDataViewCustomRenderer {
|
||||
(unsigned char)(c.blue * 255.0 + 0.5));
|
||||
}
|
||||
}
|
||||
#elif defined(__WXOSX__)
|
||||
// The DC arrives with the control's foreground colour, which is not the
|
||||
// theme-aware label colour native cells use; take the list text colour so
|
||||
// uncoloured segments follow light/dark like the native columns.
|
||||
return wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT);
|
||||
#endif
|
||||
return wxColour();
|
||||
}
|
||||
@@ -1463,8 +1472,21 @@ void wxbr_dvlc_set_row_color(void* win, unsigned row, int r, int g, int b) {
|
||||
|
||||
// Set (or clear, when r<0) the alternating-row (zebra) background colour. The
|
||||
// app passes a theme-aware colour; odd rows get it (see AttrListStore).
|
||||
#ifdef __WXOSX__
|
||||
extern "C" void wxbr_osx_set_alternating_rows(void* win, int on);
|
||||
#endif
|
||||
void wxbr_dvlc_set_zebra(void* win, int r, int g, int b) {
|
||||
#ifdef __WXOSX__
|
||||
// wxOSX draws custom cells without clipping them to the cell, so the
|
||||
// renderer's over-sized background fill (which GTK/MSW clip) painted over
|
||||
// neighbouring cells and hid their text until a row was selected. Use the
|
||||
// table's native alternating rows instead: AppKit paints them under every
|
||||
// cell, in the theme's colours, and no row carries a background attribute.
|
||||
dvlc_store(win)->zebra = wxColour();
|
||||
wxbr_osx_set_alternating_rows(win, r >= 0 ? 1 : 0);
|
||||
#else
|
||||
dvlc_store(win)->zebra = (r < 0) ? wxColour() : wxColour(r, g, b);
|
||||
#endif
|
||||
}
|
||||
|
||||
// The model-row index of the first (top) visible row, or -1 if none. Used to
|
||||
|
||||
@@ -107,6 +107,8 @@ mod notsafe {
|
||||
pub fn wxbr_launch_browser(url: *const c_char) -> c_int;
|
||||
pub fn wxbr_set_appearance_system();
|
||||
pub fn wxbr_is_dark() -> c_int;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn wxbr_osx_snapshot(win: *mut c_void, path: *const c_char) -> c_int;
|
||||
pub fn wxbr_system_color(which: c_int, r: *mut u8, g: *mut u8, b: *mut u8);
|
||||
pub fn wxbr_set_bg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
|
||||
pub fn wxbr_set_fg(win: *mut c_void, r: c_int, g: c_int, b: c_int);
|
||||
@@ -271,6 +273,22 @@ pub fn is_dark() -> bool {
|
||||
unsafe { notsafe::wxbr_is_dark() != 0 }
|
||||
}
|
||||
|
||||
/// Write a PNG of `win`'s top-level window as the app itself renders it (shows
|
||||
/// the window and lets it paint first). macOS only, for the self-test's
|
||||
/// `ALKANE_SNAPSHOT`; returns false elsewhere or on failure.
|
||||
pub fn snapshot_png(win: &Widget, path: &str) -> bool {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let Ok(p) = CString::new(path) else { return false };
|
||||
unsafe { notsafe::wxbr_osx_snapshot(win.0, p.as_ptr()) != 0 }
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
let _ = (win, path);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// A theme colour. `which`: 0=window bg, 1=window text, 2=highlight,
|
||||
/// 3=button face, 4=grey text. Returns (r, g, b).
|
||||
pub fn system_color(which: i32) -> (u8, u8, u8) {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Report relay for the Alkane Toolkit's Bug report button (see README.md).
|
||||
FROM python:3.13-alpine
|
||||
RUN adduser -D -H -u 10001 relay
|
||||
COPY relay.py /app/relay.py
|
||||
USER relay
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["python3", "-u", "/app/relay.py"]
|
||||
@@ -0,0 +1,65 @@
|
||||
# Report relay
|
||||
|
||||
Files the app's bug reports and feature requests as issues in
|
||||
`blueflare/alkane-toolkit`. The app's **Bug report** button posts the report
|
||||
here; the relay holds the only token, so the public app download carries no
|
||||
secret.
|
||||
|
||||
```
|
||||
app --HTTPS--> gitea.bluefla.re/alkane-report/ (nginx) --> relay --> Gitea API
|
||||
```
|
||||
|
||||
## What it does
|
||||
|
||||
- `POST /v1/report` takes the JSON the app sends (`kind`, `text`, version and
|
||||
OS context, optional `log`) and answers `201 {"number", "url"}` or an error
|
||||
`{"error": "..."}` the app shows as is. `GET /healthz` answers `200`.
|
||||
- Checks: type is `bug`, `ui` or `feature`; text 1 to 8,000 characters;
|
||||
each context value at most 120 printable characters; log at most 16 KiB;
|
||||
body at most 64 KiB (nginx enforces the same).
|
||||
- Rate limits, in memory: 5 reports per client IP per hour and 60 in all.
|
||||
Over the limit: `429` with `Retry-After`. At most 4 reports in flight.
|
||||
The client IP is `X-Real-IP` from nginx. Office LAN clients reach nginx
|
||||
through the router's hairpin NAT, so they share one IP and one limit.
|
||||
- Scrubs the log a second time (the app scrubs first): password, token,
|
||||
secret and similar values, `Authorization`/`Cookie` values, URL passwords
|
||||
and PEM private keys become `[redacted]`.
|
||||
- `@name` in a report cannot notify anyone (a zero-width space follows `@`).
|
||||
- The issue title is the text's first line (up to 100 characters). The body
|
||||
has the type, a context table, the text, and the log in a collapsed block.
|
||||
Labels: the type (`bug`, `ui`, `feature`) and `from-app`.
|
||||
- Nothing is stored. Each report leaves one log line: the client IP and the
|
||||
outcome (`filed #N`, `refused <status>`, `rate limited`, `tracker error`),
|
||||
never the report's text.
|
||||
|
||||
## Gitea account
|
||||
|
||||
Issues are filed as `alkane-reporter`, a local non-admin user with a random
|
||||
password that is never used. Its only access is the org team
|
||||
`alkane-reporters` (units `repo.code: read`, `repo.issues: write`) on
|
||||
`alkane-toolkit`. Its token `alkane-toolkit-bug-reports` has the scopes
|
||||
`write:issue` and `read:repository`. This mirrors FLARE's `flare-reporter`.
|
||||
|
||||
## Deployment
|
||||
|
||||
On the Gitea host, recorded in the `flare-deployment` repository
|
||||
(`runbooks/alkane-report-relay.md`):
|
||||
|
||||
```sh
|
||||
# in /opt/flare/deploy/alkane-report-relay, holding relay.py, Dockerfile, compose.yml
|
||||
PROXY_NETWORK=flare_default docker compose -p alkane-report-relay up -d --build
|
||||
```
|
||||
|
||||
The token file is `secrets/gitea_token` next to the compose file (directory
|
||||
`0700`, never committed). nginx routes `location /alkane-report/` in the
|
||||
`gitea.bluefla.re` server block to `alkane-report-relay:8080`.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
python3 tools/report-relay/test_relay.py
|
||||
```
|
||||
|
||||
They run the real HTTP handler against a fake Gitea: filing, scrubbing,
|
||||
mention handling, validation, size and rate limits, and tracker errors. CI
|
||||
runs them in the `verify` workflow's unit tests.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Deployed on the Gitea host next to the shared nginx (see README.md).
|
||||
# The token file is created on the host and never committed.
|
||||
services:
|
||||
report-relay:
|
||||
build: .
|
||||
image: alkane-report-relay:local
|
||||
container_name: alkane-report-relay
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
mem_limit: 128m
|
||||
pids_limit: 64
|
||||
environment:
|
||||
GITEA_URL: http://gitea:3000
|
||||
GITEA_REPO: blueflare/alkane-toolkit
|
||||
GITEA_TOKEN_FILE: /run/secrets/gitea_token
|
||||
RATE_PER_IP: "5"
|
||||
RATE_GLOBAL: "60"
|
||||
volumes:
|
||||
- ./secrets/gitea_token:/run/secrets/gitea_token:ro
|
||||
networks: [proxy]
|
||||
networks:
|
||||
proxy:
|
||||
external: true
|
||||
name: ${PROXY_NETWORK:?set PROXY_NETWORK to the shared nginx network}
|
||||
@@ -0,0 +1,321 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Report relay: files Alkane Toolkit bug reports as Gitea issues.
|
||||
|
||||
The app's Bug report button posts JSON here; the relay checks it, scrubs the
|
||||
log again, rate-limits, and files one issue in one repository with its own
|
||||
token. The app holds no secret. Nothing about a report is stored.
|
||||
|
||||
POST /v1/report {"kind": "bug"|"ui"|"feature", "text": "...",
|
||||
"app_version", "platform", "os", "appearance",
|
||||
"language", "window": "...", "log": "..."}
|
||||
-> 201 {"number": N, "url": "..."}
|
||||
-> 4xx/5xx {"error": "reason the app shows"}
|
||||
GET /healthz -> 200 ok
|
||||
|
||||
Configuration (environment):
|
||||
GITEA_URL API base, e.g. http://gitea:3000 (default https://gitea.bluefla.re)
|
||||
GITEA_REPO owner/name the issues go to (default blueflare/alkane-toolkit)
|
||||
GITEA_TOKEN_FILE file holding the token (scopes write:issue, read:repository)
|
||||
LISTEN host:port (default 0.0.0.0:8080)
|
||||
RATE_PER_IP reports per client IP per hour (default 5)
|
||||
RATE_GLOBAL reports per hour in all (default 60)
|
||||
|
||||
The client IP is the X-Real-IP header the reverse proxy sets; the relay must
|
||||
only be reachable through that proxy.
|
||||
"""
|
||||
|
||||
from collections import deque
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
KINDS = {"bug": "Bug", "ui": "UI change", "feature": "Feature request"}
|
||||
CONTEXT_FIELDS = (
|
||||
("app_version", "App version"),
|
||||
("platform", "Platform"),
|
||||
("os", "OS"),
|
||||
("appearance", "Appearance"),
|
||||
("language", "Language"),
|
||||
("window", "Window"),
|
||||
)
|
||||
FROM_APP_LABEL = "from-app"
|
||||
MAX_BODY = 64 * 1024
|
||||
MAX_TEXT_CHARS = 8000
|
||||
MAX_CONTEXT_CHARS = 120
|
||||
MAX_LOG_BYTES = 16 * 1024
|
||||
MAX_TITLE_CHARS = 100
|
||||
MAX_IN_FLIGHT = 4
|
||||
HOUR = 3600.0
|
||||
|
||||
SECRET_NAME = re.compile(
|
||||
r"(password|passwd|pass|pwd|secret|token|apikey|api_key|psk|credential)"
|
||||
r"(['\"]?\s*[:=]\s*['\"]?)([^\s'\",&;]+)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
HEADER_SECRET = re.compile(r"((?:authorization|cookie)\s*:\s*).+", re.IGNORECASE)
|
||||
URL_USERINFO = re.compile(r"(://[^/\s:@]+:)[^/\s@]+(@)")
|
||||
PEM_BLOCK = re.compile(
|
||||
r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(-----END [A-Z ]*PRIVATE KEY-----|\Z)",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def scrub(text: str) -> str:
|
||||
"""Remove credentials (the app scrubs too; this is the second pass)."""
|
||||
text = PEM_BLOCK.sub("[redacted]", text)
|
||||
text = HEADER_SECRET.sub(r"\1[redacted]", text)
|
||||
text = URL_USERINFO.sub(r"\1[redacted]\2", text)
|
||||
return SECRET_NAME.sub(r"\1\2[redacted]", text)
|
||||
|
||||
|
||||
def no_mentions(text: str) -> str:
|
||||
"""Stop @name in a report from notifying Gitea users."""
|
||||
return re.sub(r"@(?=[A-Za-z0-9_])", "@\u200b", text)
|
||||
|
||||
|
||||
def fence_for(text: str) -> str:
|
||||
"""A backtick fence longer than any backtick run in `text`."""
|
||||
longest = max((len(m) for m in re.findall(r"`+", text)), default=0)
|
||||
return "`" * max(3, longest + 1)
|
||||
|
||||
|
||||
def cell(value: str) -> str:
|
||||
return value.replace("|", "\\|").replace("\n", " ")
|
||||
|
||||
|
||||
class BadReport(Exception):
|
||||
def __init__(self, status: int, message: str):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.message = message
|
||||
|
||||
|
||||
def validate(raw: bytes) -> dict:
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
raise BadReport(400, "The report was not valid JSON")
|
||||
if not isinstance(data, dict):
|
||||
raise BadReport(400, "The report was not a JSON object")
|
||||
kind = data.get("kind", "bug")
|
||||
if kind not in KINDS:
|
||||
raise BadReport(422, "Unknown report type")
|
||||
text = data.get("text")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
raise BadReport(422, "The report is empty")
|
||||
text = text.strip()
|
||||
if len(text) > MAX_TEXT_CHARS:
|
||||
raise BadReport(413, f"The text is longer than {MAX_TEXT_CHARS} characters")
|
||||
context = {}
|
||||
for key, _ in CONTEXT_FIELDS:
|
||||
value = data.get(key, "")
|
||||
if not isinstance(value, str) or len(value) > MAX_CONTEXT_CHARS:
|
||||
raise BadReport(422, f"Bad value for {key}")
|
||||
context[key] = "".join(c for c in value if c.isprintable())
|
||||
log = data.get("log", "")
|
||||
if not isinstance(log, str) or len(log.encode()) > MAX_LOG_BYTES:
|
||||
raise BadReport(413, "The log is too large")
|
||||
return {"kind": kind, "text": text, "context": context, "log": log}
|
||||
|
||||
|
||||
def issue_title(report: dict) -> str:
|
||||
first = next(line.strip() for line in report["text"].splitlines() if line.strip())
|
||||
if len(first) > MAX_TITLE_CHARS:
|
||||
first = first[: MAX_TITLE_CHARS - 3].rstrip() + "..."
|
||||
return no_mentions(first)
|
||||
|
||||
|
||||
def issue_body(report: dict) -> str:
|
||||
ctx = report["context"]
|
||||
lines = [
|
||||
f"**Type:** {KINDS[report['kind']]}",
|
||||
"",
|
||||
"Sent from the Alkane Toolkit app's Bug report button.",
|
||||
"",
|
||||
"| | |",
|
||||
"|---|---|",
|
||||
]
|
||||
for key, label in CONTEXT_FIELDS:
|
||||
if ctx.get(key):
|
||||
lines.append(f"| {label} | {cell(ctx[key])} |")
|
||||
lines += ["", "---", "", no_mentions(report["text"])]
|
||||
log = scrub(report["log"]).strip()
|
||||
if log:
|
||||
fence = fence_for(log)
|
||||
lines += [
|
||||
"",
|
||||
"<details><summary>Recent activity log</summary>",
|
||||
"",
|
||||
fence,
|
||||
no_mentions(log),
|
||||
fence,
|
||||
"",
|
||||
"</details>",
|
||||
]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""Sliding one-hour windows, per client IP and in all."""
|
||||
|
||||
def __init__(self, per_ip: int, total: int, clock=time.monotonic):
|
||||
self.per_ip, self.total, self.clock = per_ip, total, clock
|
||||
self.by_ip: dict[str, deque] = {}
|
||||
self.all: deque = deque()
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def take(self, ip: str) -> float:
|
||||
"""0 if the report may go now, else seconds until it may."""
|
||||
now = self.clock()
|
||||
with self.lock:
|
||||
for q in [self.all, *self.by_ip.values()]:
|
||||
while q and now - q[0] >= HOUR:
|
||||
q.popleft()
|
||||
self.by_ip = {k: q for k, q in self.by_ip.items() if q}
|
||||
mine = self.by_ip.setdefault(ip, deque())
|
||||
if len(mine) >= self.per_ip:
|
||||
return HOUR - (now - mine[0])
|
||||
if len(self.all) >= self.total:
|
||||
return HOUR - (now - self.all[0])
|
||||
mine.append(now)
|
||||
self.all.append(now)
|
||||
return 0.0
|
||||
|
||||
|
||||
class Gitea:
|
||||
def __init__(self, url: str, repo: str, token: str, timeout: float = 20):
|
||||
self.api = url.rstrip("/") + "/api/v1/repos/" + repo
|
||||
self.token, self.timeout = token, timeout
|
||||
self.labels: dict[str, int] = {}
|
||||
self.labels_at = 0.0
|
||||
|
||||
def _call(self, method: str, path: str, body: dict | None = None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(self.api + path, data=data, method=method)
|
||||
req.add_header("Authorization", f"token {self.token}")
|
||||
req.add_header("Accept", "application/json")
|
||||
if data is not None:
|
||||
req.add_header("Content-Type", "application/json")
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
return json.load(resp)
|
||||
|
||||
def label_ids(self, names: list[str]) -> list[int]:
|
||||
"""IDs of the repository's labels by name (cached 10 minutes);
|
||||
unknown names are skipped."""
|
||||
if time.monotonic() - self.labels_at > 600:
|
||||
try:
|
||||
found = self._call("GET", "/labels?limit=50")
|
||||
self.labels = {l["name"]: l["id"] for l in found}
|
||||
self.labels_at = time.monotonic()
|
||||
except (urllib.error.URLError, OSError, ValueError, KeyError):
|
||||
pass
|
||||
return [self.labels[n] for n in names if n in self.labels]
|
||||
|
||||
def file(self, title: str, body: str, labels: list[str]) -> tuple[int, str]:
|
||||
issue = self._call("POST", "/issues", {
|
||||
"title": title,
|
||||
"body": body,
|
||||
"labels": self.label_ids(labels),
|
||||
})
|
||||
return int(issue["number"]), str(issue["html_url"])
|
||||
|
||||
|
||||
class Relay:
|
||||
def __init__(self, gitea: Gitea, limiter: RateLimiter, log=print):
|
||||
self.gitea, self.limiter, self.log = gitea, limiter, log
|
||||
self.slots = threading.BoundedSemaphore(MAX_IN_FLIGHT)
|
||||
|
||||
def handle(self, ip: str, raw: bytes) -> tuple[int, dict, dict]:
|
||||
"""Return (status, json body, extra headers)."""
|
||||
try:
|
||||
report = validate(raw)
|
||||
except BadReport as bad:
|
||||
self.log(f"report from {ip}: refused {bad.status} ({bad.message})")
|
||||
return bad.status, {"error": bad.message}, {}
|
||||
wait = self.limiter.take(ip)
|
||||
if wait > 0:
|
||||
self.log(f"report from {ip}: rate limited")
|
||||
return 429, {"error": "Too many reports; try again later"}, {
|
||||
"Retry-After": str(int(wait) + 1)}
|
||||
if not self.slots.acquire(blocking=False):
|
||||
return 503, {"error": "The report service is busy; try again shortly"}, {}
|
||||
try:
|
||||
number, url = self.gitea.file(
|
||||
issue_title(report), issue_body(report), [report["kind"], FROM_APP_LABEL])
|
||||
except (urllib.error.URLError, OSError, ValueError, KeyError) as e:
|
||||
self.log(f"report from {ip}: tracker error ({type(e).__name__})")
|
||||
return 502, {"error": "The issue tracker did not answer; check the issue "
|
||||
"list before sending again"}, {}
|
||||
finally:
|
||||
self.slots.release()
|
||||
self.log(f"report from {ip}: filed #{number}")
|
||||
return 201, {"number": number, "url": url}, {}
|
||||
|
||||
|
||||
def make_handler(relay: Relay):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "alkane-report-relay"
|
||||
sys_version = ""
|
||||
|
||||
def _send(self, status: int, body: dict, headers: dict | None = None):
|
||||
data = json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
for k, v in (headers or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/healthz":
|
||||
self._send(200, {"status": "ok"})
|
||||
else:
|
||||
self._send(404, {"error": "Not found"})
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != "/v1/report":
|
||||
return self._send(404, {"error": "Not found"})
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", ""))
|
||||
except ValueError:
|
||||
return self._send(411, {"error": "Length required"})
|
||||
if length < 0 or length > MAX_BODY:
|
||||
return self._send(413, {"error": "The report is too large"})
|
||||
raw = self.rfile.read(length)
|
||||
ip = self.headers.get("X-Real-IP") or self.client_address[0]
|
||||
status, body, headers = relay.handle(ip, raw)
|
||||
self._send(status, body, headers)
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass # one line per report comes from Relay.handle instead
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def main() -> None:
|
||||
token_file = os.environ.get("GITEA_TOKEN_FILE", "/run/secrets/gitea_token")
|
||||
with open(token_file) as fh:
|
||||
token = fh.read().strip()
|
||||
if not token:
|
||||
sys.exit(f"empty token in {token_file}")
|
||||
gitea = Gitea(os.environ.get("GITEA_URL", "https://gitea.bluefla.re"),
|
||||
os.environ.get("GITEA_REPO", "blueflare/alkane-toolkit"), token)
|
||||
limiter = RateLimiter(int(os.environ.get("RATE_PER_IP", "5")),
|
||||
int(os.environ.get("RATE_GLOBAL", "60")))
|
||||
relay = Relay(gitea, limiter, log=lambda m: print(m, flush=True))
|
||||
host, _, port = os.environ.get("LISTEN", "0.0.0.0:8080").rpartition(":")
|
||||
server = ThreadingHTTPServer((host or "0.0.0.0", int(port)), make_handler(relay))
|
||||
print(f"report relay on {host}:{port} -> {gitea.api}", flush=True)
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,176 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Tests for the report relay: python3 tools/report-relay/test_relay.py"""
|
||||
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
import relay # noqa: E402
|
||||
|
||||
TOKEN = "test-token-123"
|
||||
|
||||
|
||||
class FakeGitea:
|
||||
"""Records issue creations; serves the repository's labels."""
|
||||
|
||||
def __init__(self, fail=False):
|
||||
self.created = []
|
||||
self.fail = fail
|
||||
outer = self
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _json(self, status, body):
|
||||
data = json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def do_GET(self):
|
||||
assert self.headers["Authorization"] == f"token {TOKEN}"
|
||||
if self.path.startswith("/api/v1/repos/blueflare/alkane-toolkit/labels"):
|
||||
return self._json(200, [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
|
||||
{"name": "feature", "id": 3},
|
||||
{"name": "from-app", "id": 9}])
|
||||
self._json(404, {})
|
||||
|
||||
def do_POST(self):
|
||||
assert self.headers["Authorization"] == f"token {TOKEN}"
|
||||
if outer.fail:
|
||||
return self._json(500, {"message": "boom"})
|
||||
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||
outer.created.append((self.path, body))
|
||||
n = len(outer.created)
|
||||
self._json(201, {"number": n,
|
||||
"html_url": f"https://gitea.example/blueflare/alkane-toolkit/issues/{n}"})
|
||||
|
||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||
|
||||
def close(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
|
||||
|
||||
class RelayTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.gitea = FakeGitea()
|
||||
self.now = [1000.0]
|
||||
self.limiter = relay.RateLimiter(2, 3, clock=lambda: self.now[0])
|
||||
self.logs = []
|
||||
r = relay.Relay(relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN),
|
||||
self.limiter, log=self.logs.append)
|
||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), relay.make_handler(r))
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||
|
||||
def tearDown(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
self.gitea.close()
|
||||
|
||||
def post(self, body, ip="198.51.100.7", path="/v1/report", raw=None):
|
||||
data = raw if raw is not None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(self.url + path, data=data, method="POST",
|
||||
headers={"Content-Type": "application/json",
|
||||
"X-Real-IP": ip})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
return resp.status, json.load(resp), resp.headers
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.load(e), e.headers
|
||||
|
||||
def report(self, **over):
|
||||
body = {"kind": "bug", "text": "Table is blank on macOS\nSteps: open the app.",
|
||||
"app_version": "0.110.0", "platform": "macos-aarch64", "os": "macOS 15.1",
|
||||
"appearance": "dark", "language": "en", "window": "1280x800", "log": ""}
|
||||
body.update(over)
|
||||
return body
|
||||
|
||||
def test_files_an_issue_with_title_body_and_labels(self):
|
||||
status, body, _ = self.post(self.report(kind="feature", log="12:00 scan done"))
|
||||
self.assertEqual(status, 201)
|
||||
self.assertEqual(body["number"], 1)
|
||||
self.assertTrue(body["url"].endswith("/issues/1"))
|
||||
path, issue = self.gitea.created[0]
|
||||
self.assertEqual(path, "/api/v1/repos/blueflare/alkane-toolkit/issues")
|
||||
self.assertEqual(issue["title"], "Table is blank on macOS")
|
||||
self.assertEqual(issue["labels"], [3, 9])
|
||||
self.assertIn("**Type:** Feature request", issue["body"])
|
||||
self.assertIn("| OS | macOS 15.1 |", issue["body"])
|
||||
self.assertIn("Steps: open the app.", issue["body"])
|
||||
self.assertIn("<details><summary>Recent activity log</summary>", issue["body"])
|
||||
self.assertIn("filed #1", self.logs[-1])
|
||||
self.assertNotIn("blank", " ".join(self.logs), "report text is never logged")
|
||||
|
||||
def test_scrubs_the_log_and_neutralises_mentions(self):
|
||||
log = ("set pool url=stratum+tcp://w:hunter2@pool:3333 password=hunter2\n"
|
||||
"Authorization: Bearer abc.def\n``` fence ```")
|
||||
status, _, _ = self.post(self.report(text="@admin please look", log=log))
|
||||
self.assertEqual(status, 201)
|
||||
_, issue = self.gitea.created[0]
|
||||
self.assertNotIn("hunter2", issue["body"])
|
||||
self.assertNotIn("abc.def", issue["body"])
|
||||
self.assertNotIn("@admin", issue["body"])
|
||||
self.assertNotIn("@admin", issue["title"])
|
||||
self.assertIn("````\n", issue["body"], "fence longer than the log's own")
|
||||
|
||||
def test_rejects_bad_reports(self):
|
||||
cases = [
|
||||
(self.report(text=" "), 422),
|
||||
(self.report(kind="hack"), 422),
|
||||
(self.report(text="x" * 8001), 413),
|
||||
(self.report(log="y" * (16 * 1024 + 1)), 413),
|
||||
(self.report(os="z" * 121), 422),
|
||||
(self.report(os=5), 422),
|
||||
([1, 2], 400),
|
||||
]
|
||||
for body, want in cases:
|
||||
status, answer, _ = self.post(body)
|
||||
self.assertEqual(status, want, body if not isinstance(body, dict) else answer)
|
||||
self.assertIn("error", answer)
|
||||
status, _, _ = self.post(None, raw=b"{not json")
|
||||
self.assertEqual(status, 400)
|
||||
status, _, _ = self.post(None, raw=b"x" * (relay.MAX_BODY + 1))
|
||||
self.assertEqual(status, 413)
|
||||
status, _, _ = self.post(self.report(), path="/v1/other")
|
||||
self.assertEqual(status, 404)
|
||||
self.assertEqual(self.gitea.created, [])
|
||||
|
||||
def test_rate_limits_per_ip_and_in_all(self):
|
||||
for _ in range(2):
|
||||
self.assertEqual(self.post(self.report())[0], 201)
|
||||
status, body, headers = self.post(self.report())
|
||||
self.assertEqual(status, 429)
|
||||
self.assertGreater(int(headers["Retry-After"]), 0)
|
||||
self.assertEqual(self.post(self.report(), ip="203.0.113.9")[0], 201)
|
||||
self.assertEqual(self.post(self.report(), ip="203.0.113.10")[0], 429, "global cap of 3")
|
||||
self.now[0] += relay.HOUR
|
||||
self.assertEqual(self.post(self.report())[0], 201, "window slides")
|
||||
|
||||
def test_tracker_failure_is_reported(self):
|
||||
self.gitea.fail = True
|
||||
status, body, _ = self.post(self.report())
|
||||
self.assertEqual(status, 502)
|
||||
self.assertIn("check the issue list", body["error"])
|
||||
|
||||
def test_title_is_cut(self):
|
||||
title = relay.issue_title({"text": "\n\n" + "w" * 300})
|
||||
self.assertEqual(len(title), relay.MAX_TITLE_CHARS)
|
||||
self.assertTrue(title.endswith("..."))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user