Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b624c1910 | ||
|
|
16951b6c92 | ||
|
|
ea753c1756 | ||
|
|
080bebe050 | ||
|
|
8cb6989000 | ||
|
|
99cddbdf93 | ||
|
|
3742f28e7d | ||
|
|
dabe3ce846 | ||
|
|
3931dbb0f0 | ||
|
|
41303fcbad | ||
|
|
b10bf04142 | ||
|
|
0d9c0fb7c1 | ||
|
|
d574118314 | ||
|
|
0873d2c79d | ||
|
|
12a11edfd7 | ||
|
|
71ab5a957c | ||
|
|
f6c740bc24 | ||
|
|
968173095e | ||
|
|
63c603d919 | ||
|
|
fdb9bedb03 | ||
|
|
4be4750aae | ||
|
|
165b11bda3 | ||
|
|
e83bb8d2f1 | ||
|
|
c0a647237a | ||
|
|
9c49fa91af | ||
|
|
fbeb6dc328 | ||
|
|
8180f4ff80 | ||
|
|
9155c55d4c | ||
|
|
be2eab6262 | ||
|
|
15df9086c1 | ||
|
|
d2d4c085ae | ||
|
|
6e785275da | ||
|
|
9d49c4b070 | ||
|
|
dd3cff19cb | ||
|
|
25047a603a | ||
|
|
69dcedbd9c | ||
|
|
bccfaae2fa | ||
|
|
7cd26aff56 | ||
|
|
4f59233064 | ||
|
|
7e0174fda1 | ||
|
|
7d5f250254 | ||
|
|
fbf44889ea | ||
|
|
f9cd12b374 | ||
|
|
aab9b63350 | ||
|
|
224b3b37e8 |
@@ -11,7 +11,7 @@ concurrency:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish:
|
publish:
|
||||||
runs-on: alkane-verify
|
runs-on: alkane-ci
|
||||||
container:
|
container:
|
||||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||||
permissions:
|
permissions:
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish:
|
publish:
|
||||||
runs-on: alkane-verify
|
runs-on: alkane-ci
|
||||||
container:
|
container:
|
||||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||||
permissions:
|
permissions:
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ concurrency:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
check:
|
check:
|
||||||
runs-on: alkane-fast
|
runs-on: alkane-ci
|
||||||
container:
|
container:
|
||||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ concurrency:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
verify:
|
verify:
|
||||||
runs-on: alkane-verify
|
runs-on: alkane-ci
|
||||||
container:
|
container:
|
||||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||||
outputs:
|
outputs:
|
||||||
@@ -202,7 +202,7 @@ jobs:
|
|||||||
verify-windows:
|
verify-windows:
|
||||||
needs: verify
|
needs: verify
|
||||||
if: needs.verify.outputs.surface == 'full'
|
if: needs.verify.outputs.surface == 'full'
|
||||||
runs-on: alkane-verify
|
runs-on: alkane-ci
|
||||||
container:
|
container:
|
||||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||||
env:
|
env:
|
||||||
|
|||||||
@@ -155,6 +155,54 @@ pub struct AfwManifest {
|
|||||||
pub notes: Option<String>,
|
pub notes: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What an `.afw` bundle overwrites on the target, derived from its manifest.
|
||||||
|
///
|
||||||
|
/// Tiers mirror the flash tiers: 1 = update (userspace / HAL only, no kernel or
|
||||||
|
/// bootloader write), 2 = kernel (kernel, dtb and boot images; bootloader
|
||||||
|
/// preserved), 3 = bootloader (U-Boot/SPL is rewritten as well).
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
|
pub struct FlashPlan {
|
||||||
|
pub tier: u8,
|
||||||
|
pub writes_uboot: bool,
|
||||||
|
pub writes_kernel: bool,
|
||||||
|
pub writes_userspace: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AfwManifest {
|
||||||
|
/// Compute the flash tier and the regions this bundle overwrites. Pure
|
||||||
|
/// computation over the parsed manifest; no device or file access.
|
||||||
|
///
|
||||||
|
/// - `writes_uboot`: `bootloader_policy` is [`BootloaderPolicy::Include`]
|
||||||
|
/// (anything but `Preserve`), or an image with role `bootloader` exists.
|
||||||
|
/// - `writes_kernel`: an image with role `kernel`, `dtb` or `boot` exists.
|
||||||
|
/// - `writes_userspace`: an image with role `rootfs` exists.
|
||||||
|
/// - `tier`: 3 if `writes_uboot`, else 2 if `writes_kernel`, else 1.
|
||||||
|
pub fn flash_plan(&self) -> FlashPlan {
|
||||||
|
let has_role = |roles: &[&str]| {
|
||||||
|
self.images
|
||||||
|
.iter()
|
||||||
|
.any(|image| roles.contains(&image.role.as_str()))
|
||||||
|
};
|
||||||
|
let writes_uboot =
|
||||||
|
self.bootloader_policy != BootloaderPolicy::Preserve || has_role(&["bootloader"]);
|
||||||
|
let writes_kernel = has_role(&["kernel", "dtb", "boot"]);
|
||||||
|
let writes_userspace = has_role(&["rootfs"]);
|
||||||
|
let tier = if writes_uboot {
|
||||||
|
3
|
||||||
|
} else if writes_kernel {
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
};
|
||||||
|
FlashPlan {
|
||||||
|
tier,
|
||||||
|
writes_uboot,
|
||||||
|
writes_kernel,
|
||||||
|
writes_userspace,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||||
pub struct AfwMember {
|
pub struct AfwMember {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
@@ -1080,6 +1128,106 @@ mod tests {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Build a parsed manifest with the given bootloader policy and one image
|
||||||
|
/// per listed role (payload bytes are irrelevant to `flash_plan`).
|
||||||
|
fn plan_manifest(policy: &str, roles: &[&str]) -> AfwManifest {
|
||||||
|
let mut value = manifest(&[0_u8; 4]);
|
||||||
|
value["bootloader_policy"] = json!(policy);
|
||||||
|
value["images"] = json!(roles
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, role)| json!({
|
||||||
|
"name": format!("img{i}"), "file": format!("payload/img{i}"),
|
||||||
|
"role": role, "format": "raw", "size": 4, "sha256": "0".repeat(64),
|
||||||
|
"partition": null, "install": false
|
||||||
|
}))
|
||||||
|
.collect::<Vec<_>>());
|
||||||
|
serde_json::from_value(value).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flash_plan_tier2_preserve_kernel_and_rootfs() {
|
||||||
|
let plan = plan_manifest("preserve", &["kernel", "dtb", "rootfs"]).flash_plan();
|
||||||
|
assert_eq!(plan.tier, 2);
|
||||||
|
assert!(plan.writes_kernel);
|
||||||
|
assert!(plan.writes_userspace);
|
||||||
|
assert!(!plan.writes_uboot);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flash_plan_tier3_include_with_bootloader_image() {
|
||||||
|
let plan =
|
||||||
|
plan_manifest("include", &["bootloader", "kernel", "dtb", "rootfs"]).flash_plan();
|
||||||
|
assert_eq!(plan.tier, 3);
|
||||||
|
assert!(plan.writes_uboot);
|
||||||
|
assert!(plan.writes_kernel);
|
||||||
|
assert!(plan.writes_userspace);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flash_plan_tier3_from_bootloader_image_alone() {
|
||||||
|
// A bootloader image forces tier 3 even if the policy says preserve
|
||||||
|
// (verification rejects that combination, but the plan stays safe).
|
||||||
|
let plan = plan_manifest("preserve", &["bootloader"]).flash_plan();
|
||||||
|
assert_eq!(plan.tier, 3);
|
||||||
|
assert!(plan.writes_uboot);
|
||||||
|
assert!(!plan.writes_kernel);
|
||||||
|
assert!(!plan.writes_userspace);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flash_plan_tier3_from_include_policy_alone() {
|
||||||
|
let plan = plan_manifest("include", &["rootfs"]).flash_plan();
|
||||||
|
assert_eq!(plan.tier, 3);
|
||||||
|
assert!(plan.writes_uboot);
|
||||||
|
assert!(!plan.writes_kernel);
|
||||||
|
assert!(plan.writes_userspace);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flash_plan_tier1_rootfs_only() {
|
||||||
|
let plan = plan_manifest("preserve", &["rootfs"]).flash_plan();
|
||||||
|
assert_eq!(plan.tier, 1);
|
||||||
|
assert!(plan.writes_userspace);
|
||||||
|
assert!(!plan.writes_kernel);
|
||||||
|
assert!(!plan.writes_uboot);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flash_plan_boot_role_counts_as_kernel() {
|
||||||
|
let plan = plan_manifest("preserve", &["boot"]).flash_plan();
|
||||||
|
assert_eq!(plan.tier, 2);
|
||||||
|
assert!(plan.writes_kernel);
|
||||||
|
assert!(!plan.writes_userspace);
|
||||||
|
assert!(!plan.writes_uboot);
|
||||||
|
// The shared cv1835 fixture is a single "boot" FIT under preserve.
|
||||||
|
let fixture: AfwManifest = serde_json::from_value(manifest(&[0_u8; 4])).unwrap();
|
||||||
|
assert_eq!(fixture.flash_plan().tier, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flash_plan_component_only_is_tier1_with_no_regions() {
|
||||||
|
let plan = plan_manifest("preserve", &["component"]).flash_plan();
|
||||||
|
assert_eq!(plan.tier, 1);
|
||||||
|
assert!(!plan.writes_uboot);
|
||||||
|
assert!(!plan.writes_kernel);
|
||||||
|
assert!(!plan.writes_userspace);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flash_plan_empty_images_preserve_is_tier1() {
|
||||||
|
let plan = plan_manifest("preserve", &[]).flash_plan();
|
||||||
|
assert_eq!(plan.tier, 1);
|
||||||
|
assert!(!plan.writes_uboot && !plan.writes_kernel && !plan.writes_userspace);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flash_plan_tier3_dominates_kernel() {
|
||||||
|
let plan = plan_manifest("include", &["bootloader", "kernel"]).flash_plan();
|
||||||
|
assert_eq!(plan.tier, 3);
|
||||||
|
assert!(plan.writes_uboot && plan.writes_kernel);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn refuses_a_hash_mismatch() {
|
fn refuses_a_hash_mismatch() {
|
||||||
let p1 = p1_image(P1);
|
let p1 = p1_image(P1);
|
||||||
|
|||||||
@@ -48,44 +48,162 @@ pub enum FetchError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Where releases come from. Defaults to the alkane-os repo on the self-hosted
|
/// 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.
|
/// Gitea; a full repo URL on any Gitea or GitHub host is also accepted so an
|
||||||
|
/// operator can flash from their own fork.
|
||||||
pub struct ReleaseSource {
|
pub struct ReleaseSource {
|
||||||
pub base_url: String,
|
pub base_url: String,
|
||||||
pub owner: String,
|
pub owner: String,
|
||||||
pub repo: String,
|
pub repo: String,
|
||||||
pub token: Option<String>,
|
pub token: Option<String>,
|
||||||
|
/// GitHub uses `api.github.com/repos/...` instead of a Gitea
|
||||||
|
/// `.../api/v1/repos/...` path.
|
||||||
|
pub github: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The default self-hosted Gitea base (honoring `ALKANE_RELEASE_BASE`).
|
||||||
|
fn default_gitea_base() -> String {
|
||||||
|
std::env::var("ALKANE_RELEASE_BASE")
|
||||||
|
.ok()
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.unwrap_or_else(|| "https://gitea.bluefla.re".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve the token for the default self-hosted Gitea (never sent elsewhere).
|
||||||
|
fn gitea_token() -> Option<String> {
|
||||||
|
std::env::var("ALKANE_RELEASE_TOKEN")
|
||||||
|
.ok()
|
||||||
|
.or_else(|| std::env::var("GITEA_TOKEN").ok())
|
||||||
|
.filter(|t| !t.is_empty())
|
||||||
|
.or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty()))
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ReleaseSource {
|
impl ReleaseSource {
|
||||||
/// The alkane-os release source, honoring `ALKANE_RELEASE_BASE` and a token
|
/// The alkane-os release source, honoring `ALKANE_RELEASE_BASE` and a token
|
||||||
/// from `ALKANE_RELEASE_TOKEN` or `GITEA_TOKEN`.
|
/// from `ALKANE_RELEASE_TOKEN` or `GITEA_TOKEN`.
|
||||||
pub fn alkane_os() -> Self {
|
pub fn alkane_os() -> Self {
|
||||||
let base_url = std::env::var("ALKANE_RELEASE_BASE")
|
Self::for_repo("blueflare", "alkane-os")
|
||||||
.ok()
|
}
|
||||||
.filter(|s| !s.is_empty())
|
|
||||||
.unwrap_or_else(|| "https://gitea.bluefla.re".to_string());
|
/// A release source for an arbitrary Gitea `owner`/`repo` on the default
|
||||||
let token = std::env::var("ALKANE_RELEASE_TOKEN")
|
/// self-hosted Gitea base, with the resolved Gitea token.
|
||||||
.ok()
|
pub fn for_repo(owner: &str, repo: &str) -> Self {
|
||||||
.or_else(|| std::env::var("GITEA_TOKEN").ok())
|
|
||||||
.filter(|t| !t.is_empty())
|
|
||||||
.or_else(|| EMBEDDED_TOKEN.map(str::to_string).filter(|t| !t.is_empty()));
|
|
||||||
Self {
|
Self {
|
||||||
base_url,
|
base_url: default_gitea_base(),
|
||||||
owner: "blueflare".to_string(),
|
owner: owner.to_string(),
|
||||||
repo: "alkane-os".to_string(),
|
repo: repo.to_string(),
|
||||||
|
token: gitea_token(),
|
||||||
|
github: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse a full repo URL (or a bare `owner/repo`) into a release source.
|
||||||
|
/// Supports any Gitea host and GitHub (`github.com`); a bare `owner/repo`
|
||||||
|
/// uses the default self-hosted Gitea. Accepts optional scheme, a trailing
|
||||||
|
/// `.git`, and trailing path noise (e.g. `/releases`).
|
||||||
|
///
|
||||||
|
/// The resolved Gitea token is attached ONLY when the host is the default
|
||||||
|
/// self-hosted Gitea, so the embedded admin token is never sent to GitHub or
|
||||||
|
/// any other host (those use anonymous access to public releases).
|
||||||
|
pub fn from_url(input: &str) -> Option<ReleaseSource> {
|
||||||
|
let s = input.trim().trim_end_matches('/');
|
||||||
|
if s.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let no_scheme = s
|
||||||
|
.strip_prefix("https://")
|
||||||
|
.or_else(|| s.strip_prefix("http://"))
|
||||||
|
.unwrap_or(s);
|
||||||
|
let parts: Vec<&str> = no_scheme.split('/').filter(|p| !p.is_empty()).collect();
|
||||||
|
// host present when the first segment looks like a hostname (has a dot).
|
||||||
|
let (host, owner, repo) = if parts.len() >= 3 && parts[0].contains('.') {
|
||||||
|
(Some(parts[0]), parts[1], parts[2])
|
||||||
|
} else if parts.len() == 2 && !parts[0].contains('.') {
|
||||||
|
(None, parts[0], parts[1])
|
||||||
|
} else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let repo = repo.trim_end_matches(".git");
|
||||||
|
if owner.is_empty() || repo.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let default_host = default_gitea_base()
|
||||||
|
.trim_start_matches("https://")
|
||||||
|
.trim_start_matches("http://")
|
||||||
|
.trim_end_matches('/')
|
||||||
|
.to_string();
|
||||||
|
let src = match host {
|
||||||
|
Some("github.com") | Some("www.github.com") => ReleaseSource {
|
||||||
|
base_url: "https://api.github.com".to_string(),
|
||||||
|
owner: owner.to_string(),
|
||||||
|
repo: repo.to_string(),
|
||||||
|
token: None, // never send the gitea token to github
|
||||||
|
github: true,
|
||||||
|
},
|
||||||
|
Some(h) if h == default_host => ReleaseSource {
|
||||||
|
base_url: default_gitea_base(),
|
||||||
|
owner: owner.to_string(),
|
||||||
|
repo: repo.to_string(),
|
||||||
|
token: gitea_token(),
|
||||||
|
github: false,
|
||||||
|
},
|
||||||
|
Some(h) => ReleaseSource {
|
||||||
|
base_url: format!("https://{h}"),
|
||||||
|
owner: owner.to_string(),
|
||||||
|
repo: repo.to_string(),
|
||||||
|
token: None, // a different Gitea host: anonymous public access
|
||||||
|
github: false,
|
||||||
|
},
|
||||||
|
None => Self::for_repo(owner, repo),
|
||||||
|
};
|
||||||
|
Some(src)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A minimal source for downloading a release asset by its direct URL. The
|
||||||
|
/// gitea token is attached ONLY when the asset URL is on the trusted
|
||||||
|
/// self-hosted Gitea host; GitHub and other hosts get anonymous access, so
|
||||||
|
/// the embedded admin token is never sent off-host.
|
||||||
|
pub fn for_asset_url(url: &str) -> ReleaseSource {
|
||||||
|
let host = url
|
||||||
|
.trim_start_matches("https://")
|
||||||
|
.trim_start_matches("http://")
|
||||||
|
.split('/')
|
||||||
|
.next()
|
||||||
|
.unwrap_or("");
|
||||||
|
let default_host = default_gitea_base()
|
||||||
|
.trim_start_matches("https://")
|
||||||
|
.trim_start_matches("http://")
|
||||||
|
.trim_end_matches('/')
|
||||||
|
.to_string();
|
||||||
|
let token = if host == default_host {
|
||||||
|
gitea_token()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
ReleaseSource {
|
||||||
|
base_url: format!("https://{host}"),
|
||||||
|
owner: String::new(),
|
||||||
|
repo: String::new(),
|
||||||
token,
|
token,
|
||||||
|
github: host.eq_ignore_ascii_case("api.github.com")
|
||||||
|
|| host.eq_ignore_ascii_case("github.com"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The releases list (newest first). Unlike `releases/latest`, this includes
|
/// The releases list (newest first). Unlike `releases/latest`, this includes
|
||||||
/// pre-releases, so an early/bench channel is still found by `--latest`.
|
/// pre-releases, so an early/bench channel is still found by `--latest`.
|
||||||
fn api_list(&self) -> String {
|
fn api_list(&self) -> String {
|
||||||
format!(
|
let base = self.base_url.trim_end_matches('/');
|
||||||
"{}/api/v1/repos/{}/{}/releases?limit=50",
|
if self.github {
|
||||||
self.base_url.trim_end_matches('/'),
|
format!(
|
||||||
self.owner,
|
"{}/repos/{}/{}/releases?per_page=50",
|
||||||
self.repo
|
base, self.owner, self.repo
|
||||||
)
|
)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"{}/api/v1/repos/{}/{}/releases?limit=50",
|
||||||
|
base, self.owner, self.repo
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,7 +284,10 @@ fn write_private(path: &Path, contents: &str) -> Result<(), FetchError> {
|
|||||||
fn curl_bytes(src: &ReleaseSource, url: &str) -> Result<Vec<u8>, FetchError> {
|
fn curl_bytes(src: &ReleaseSource, url: &str) -> Result<Vec<u8>, FetchError> {
|
||||||
let config = TokenConfig::new(&src.token)?;
|
let config = TokenConfig::new(&src.token)?;
|
||||||
let mut cmd = Command::new("curl");
|
let mut cmd = Command::new("curl");
|
||||||
cmd.arg("-fsSL").arg("--max-time").arg("120");
|
// A generic User-Agent (GitHub's API rejects requests without one); never
|
||||||
|
// carries any operator/host detail.
|
||||||
|
cmd.arg("-fsSL").arg("-A").arg("alkane-toolkit");
|
||||||
|
cmd.arg("--max-time").arg("120");
|
||||||
config.apply(&mut cmd);
|
config.apply(&mut cmd);
|
||||||
cmd.arg(url);
|
cmd.arg(url);
|
||||||
let out = cmd.output().map_err(|e| FetchError::Curl(e.to_string()))?;
|
let out = cmd.output().map_err(|e| FetchError::Curl(e.to_string()))?;
|
||||||
@@ -184,6 +305,8 @@ fn curl_download(src: &ReleaseSource, url: &str, dest: &Path) -> Result<(), Fetc
|
|||||||
let config = TokenConfig::new(&src.token)?;
|
let config = TokenConfig::new(&src.token)?;
|
||||||
let mut cmd = Command::new("curl");
|
let mut cmd = Command::new("curl");
|
||||||
cmd.arg("-fsSL")
|
cmd.arg("-fsSL")
|
||||||
|
.arg("-A")
|
||||||
|
.arg("alkane-toolkit")
|
||||||
.arg("--max-time")
|
.arg("--max-time")
|
||||||
.arg("600")
|
.arg("600")
|
||||||
.arg("-o")
|
.arg("-o")
|
||||||
@@ -223,6 +346,18 @@ pub fn fetch_latest_afw(
|
|||||||
Ok(dest)
|
Ok(dest)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Board tokens recognised in `.afw` asset names (the `-<board>-` filename
|
||||||
|
/// segment). Used by `ReleaseInfo::compatible_boards`.
|
||||||
|
pub const KNOWN_BOARDS: &[&str] = &[
|
||||||
|
"zynq-7010",
|
||||||
|
"am335x",
|
||||||
|
"cv1835",
|
||||||
|
"a113d",
|
||||||
|
"allwinner-h3",
|
||||||
|
"allwinner-h6",
|
||||||
|
"allwinner-h616",
|
||||||
|
];
|
||||||
|
|
||||||
/// One `.afw` asset in a release.
|
/// One `.afw` asset in a release.
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct AfwAsset {
|
pub struct AfwAsset {
|
||||||
@@ -249,6 +384,30 @@ impl ReleaseInfo {
|
|||||||
let needle = format!("-{board}-");
|
let needle = format!("-{board}-");
|
||||||
self.afw_assets.iter().find(|a| a.name.contains(&needle))
|
self.afw_assets.iter().find(|a| a.name.contains(&needle))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The distinct board tokens (from `KNOWN_BOARDS`) this release carries an
|
||||||
|
/// `.afw` for, detected from the asset filenames (`-<board>-` segment, e.g.
|
||||||
|
/// `alkane-os-0.1.2-zynq-7010-armv7.afw` -> `zynq-7010`). Ordered by first
|
||||||
|
/// appearance across the assets; a release with no recognised board yields an
|
||||||
|
/// empty list.
|
||||||
|
pub fn compatible_boards(&self) -> Vec<String> {
|
||||||
|
let mut boards: Vec<String> = Vec::new();
|
||||||
|
for asset in &self.afw_assets {
|
||||||
|
for board in KNOWN_BOARDS {
|
||||||
|
let needle = format!("-{board}-");
|
||||||
|
if asset.name.contains(&needle) && !boards.iter().any(|b| b == board) {
|
||||||
|
boards.push((*board).to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
boards
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this release has an `.afw` for `board` (same match as
|
||||||
|
/// `asset_for_board`).
|
||||||
|
pub fn is_compatible_with(&self, board: &str) -> bool {
|
||||||
|
self.asset_for_board(board).is_some()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parse a Gitea releases array (newest first) into `ReleaseInfo`s, keeping only
|
/// Parse a Gitea releases array (newest first) into `ReleaseInfo`s, keeping only
|
||||||
@@ -336,6 +495,54 @@ pub fn fetch_afw_url(
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn from_url_parses_gitea_github_and_bare() {
|
||||||
|
std::env::remove_var("ALKANE_RELEASE_BASE");
|
||||||
|
// Bare owner/repo -> default gitea.
|
||||||
|
let g = ReleaseSource::from_url("someone/alkane-os").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(g.owner.as_str(), g.repo.as_str()),
|
||||||
|
("someone", "alkane-os")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!g.github
|
||||||
|
&& g.api_list()
|
||||||
|
.contains("gitea.bluefla.re/api/v1/repos/someone/alkane-os")
|
||||||
|
);
|
||||||
|
|
||||||
|
// Full gitea URL on the default host keeps the token path + gitea API.
|
||||||
|
let gh = ReleaseSource::from_url("https://gitea.bluefla.re/blueflare/alkane-os").unwrap();
|
||||||
|
assert!(!gh.github && gh.api_list().contains("/api/v1/repos/blueflare/alkane-os"));
|
||||||
|
|
||||||
|
// GitHub URL -> api.github.com, github path, and NEVER a token.
|
||||||
|
let h = ReleaseSource::from_url("https://github.com/acme/alkane-os.git/releases").unwrap();
|
||||||
|
assert!(h.github);
|
||||||
|
assert!(
|
||||||
|
h.token.is_none(),
|
||||||
|
"must not attach the gitea token to github"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
h.api_list(),
|
||||||
|
"https://api.github.com/repos/acme/alkane-os/releases?per_page=50"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Another gitea host -> no token (not the trusted host), gitea path.
|
||||||
|
let other = ReleaseSource::from_url("https://git.example.org/u/r").unwrap();
|
||||||
|
assert!(!other.github && other.token.is_none());
|
||||||
|
assert!(other
|
||||||
|
.api_list()
|
||||||
|
.starts_with("https://git.example.org/api/v1/repos/u/r"));
|
||||||
|
|
||||||
|
// Asset download token only for the trusted host.
|
||||||
|
assert!(ReleaseSource::for_asset_url(
|
||||||
|
"https://github.com/acme/r/releases/download/v1/x.afw"
|
||||||
|
)
|
||||||
|
.token
|
||||||
|
.is_none());
|
||||||
|
assert!(ReleaseSource::from_url("").is_none());
|
||||||
|
assert!(ReleaseSource::from_url("justonepart").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn source_defaults_to_alkane_os_on_gitea() {
|
fn source_defaults_to_alkane_os_on_gitea() {
|
||||||
std::env::remove_var("ALKANE_RELEASE_BASE");
|
std::env::remove_var("ALKANE_RELEASE_BASE");
|
||||||
@@ -401,4 +608,84 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert!(parsed[1].asset_for_board("zynq-7010").is_none());
|
assert!(parsed[1].asset_for_board("zynq-7010").is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn for_repo_builds_the_api_url_for_a_custom_repo() {
|
||||||
|
std::env::remove_var("ALKANE_RELEASE_BASE");
|
||||||
|
let src = ReleaseSource::for_repo("someorg", "some-firmware");
|
||||||
|
assert_eq!(src.owner, "someorg");
|
||||||
|
assert_eq!(src.repo, "some-firmware");
|
||||||
|
assert_eq!(
|
||||||
|
src.api_list(),
|
||||||
|
"https://gitea.bluefla.re/api/v1/repos/someorg/some-firmware/releases?limit=50"
|
||||||
|
);
|
||||||
|
// alkane_os() is for_repo("blueflare", "alkane-os").
|
||||||
|
let os = ReleaseSource::alkane_os();
|
||||||
|
assert_eq!(
|
||||||
|
(os.owner.as_str(), os.repo.as_str()),
|
||||||
|
("blueflare", "alkane-os")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn release_with(names: &[&str]) -> ReleaseInfo {
|
||||||
|
ReleaseInfo {
|
||||||
|
tag: "v0.1.2".into(),
|
||||||
|
name: String::new(),
|
||||||
|
prerelease: false,
|
||||||
|
draft: false,
|
||||||
|
published_at: String::new(),
|
||||||
|
afw_assets: names
|
||||||
|
.iter()
|
||||||
|
.map(|n| AfwAsset {
|
||||||
|
name: (*n).to_string(),
|
||||||
|
url: format!("https://example.invalid/{n}"),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compatible_boards_extracts_board_tokens_from_asset_names() {
|
||||||
|
let single = release_with(&["alkane-os-0.1.2-zynq-7010-armv7.afw"]);
|
||||||
|
assert_eq!(single.compatible_boards(), vec!["zynq-7010"]);
|
||||||
|
|
||||||
|
// Multi-board release: distinct boards in first-appearance order,
|
||||||
|
// duplicates (a second arch build of one board) collapse.
|
||||||
|
let multi = release_with(&[
|
||||||
|
"alkane-os-0.1.2-am335x-armv7.afw",
|
||||||
|
"alkane-os-0.1.2-zynq-7010-armv7.afw",
|
||||||
|
"alkane-os-0.1.2-allwinner-h616-aarch64.afw",
|
||||||
|
"alkane-os-0.1.2-am335x-arm.afw",
|
||||||
|
"alkane-os-0.1.2-cv1835-riscv64.afw",
|
||||||
|
]);
|
||||||
|
assert_eq!(
|
||||||
|
multi.compatible_boards(),
|
||||||
|
vec!["am335x", "zynq-7010", "allwinner-h616", "cv1835"]
|
||||||
|
);
|
||||||
|
|
||||||
|
// allwinner-h6 must not match an allwinner-h616 asset (and vice versa).
|
||||||
|
let h616 = release_with(&["alkane-os-0.1.2-allwinner-h616-aarch64.afw"]);
|
||||||
|
assert_eq!(h616.compatible_boards(), vec!["allwinner-h616"]);
|
||||||
|
let h6 = release_with(&["alkane-os-0.1.2-allwinner-h6-aarch64.afw"]);
|
||||||
|
assert_eq!(h6.compatible_boards(), vec!["allwinner-h6"]);
|
||||||
|
|
||||||
|
// No .afw assets, or an unrecognised board, yields nothing.
|
||||||
|
assert!(release_with(&[]).compatible_boards().is_empty());
|
||||||
|
assert!(release_with(&["alkane-os-0.1.2-mystery-board-arm.afw"])
|
||||||
|
.compatible_boards()
|
||||||
|
.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn is_compatible_with_matches_asset_for_board() {
|
||||||
|
let rel = release_with(&[
|
||||||
|
"alkane-os-0.1.2-zynq-7010-armv7.afw",
|
||||||
|
"alkane-os-0.1.2-a113d-aarch64.afw",
|
||||||
|
]);
|
||||||
|
assert!(rel.is_compatible_with("zynq-7010"));
|
||||||
|
assert!(rel.is_compatible_with("a113d"));
|
||||||
|
assert!(!rel.is_compatible_with("am335x"));
|
||||||
|
assert!(!rel.is_compatible_with("allwinner-h6"));
|
||||||
|
assert!(!release_with(&[]).is_compatible_with("zynq-7010"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ use alkane_flash::stock;
|
|||||||
use alkane_flash::stock::{InPlaceOptions, InPlaceOutcome, RestoreImages};
|
use alkane_flash::stock::{InPlaceOptions, InPlaceOutcome, RestoreImages};
|
||||||
use alkane_flash::stock_firmware;
|
use alkane_flash::stock_firmware;
|
||||||
use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport};
|
use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport};
|
||||||
|
use alkane_flash::zynq_nand;
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
@@ -1039,8 +1040,13 @@ fn latest_backup(dir: &Path) -> Option<PathBuf> {
|
|||||||
/// Boards this toolkit can install alkane onto, with the miner each is the
|
/// Boards this toolkit can install alkane onto, with the miner each is the
|
||||||
/// control board for. The install/restore gate is the .afw's board matching one
|
/// control board for. The install/restore gate is the .afw's board matching one
|
||||||
/// of these; `compat` lists them so an operator knows what is supported.
|
/// of these; `compat` lists them so an operator knows what is supported.
|
||||||
const SUPPORTED: &[(&str, &str)] =
|
const SUPPORTED: &[(&str, &str)] = &[
|
||||||
&[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")];
|
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
|
||||||
|
(
|
||||||
|
"a113d",
|
||||||
|
"Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
fn is_supported(board: &str) -> bool {
|
fn is_supported(board: &str) -> bool {
|
||||||
SUPPORTED.iter().any(|(b, _)| *b == board)
|
SUPPORTED.iter().any(|(b, _)| *b == board)
|
||||||
@@ -1112,14 +1118,48 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
|
|||||||
&["dry-run"],
|
&["dry-run"],
|
||||||
)?;
|
)?;
|
||||||
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||||
let firmware = opts.value("stock-firmware").ok_or(
|
|
||||||
"--stock-firmware <genuine Bitmain firmware file> is required \
|
|
||||||
(an OTA update .tar.gz or an SD recovery .zip for this board)",
|
|
||||||
)?;
|
|
||||||
// Restore reaches the alkane board over SSH as root; the board credential is
|
// Restore reaches the alkane board over SSH as root; the board credential is
|
||||||
// supplied via --password-file / ALKANE_BOARD_PASSWORD(_FILE).
|
// supplied via --password-file / ALKANE_BOARD_PASSWORD(_FILE).
|
||||||
let password = read_board_password(&opts)?;
|
let password = read_board_password(&opts)?;
|
||||||
|
|
||||||
|
// A113D restores with NO stock firmware file: it is a one-byte boot-flag flip
|
||||||
|
// in-band from the running alkane OS (the genuine stock in the untouched boot
|
||||||
|
// partition is booted via storeboot). Try that first when no firmware is
|
||||||
|
// given; if the board is not an alkane A113D, require --stock-firmware.
|
||||||
|
let firmware = match opts.value("stock-firmware") {
|
||||||
|
Some(f) => f,
|
||||||
|
None => {
|
||||||
|
if opts.flag("dry-run") {
|
||||||
|
println!("DRY RUN: would restore {host} to stock by flipping the A113D boot flag");
|
||||||
|
println!(
|
||||||
|
"(no stock firmware needed; the untouched stock boot partition is booted)."
|
||||||
|
);
|
||||||
|
println!("Re-run with --confirm FLASH.");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if opts.value("confirm") != Some("FLASH") {
|
||||||
|
return Err("refusing to restore without --confirm FLASH".into());
|
||||||
|
}
|
||||||
|
println!("restoring {host} to genuine stock (A113D flag flip, network-only)...");
|
||||||
|
match stock::restore_aml_flag(&host, password.as_deref()) {
|
||||||
|
Ok(()) => {
|
||||||
|
println!(
|
||||||
|
"restore reported success (boot flag cleared; stock boots via storeboot)."
|
||||||
|
);
|
||||||
|
println!("verify independently: the board should present genuine stock");
|
||||||
|
println!("(cgminer API on :4028, lighttpd 401 on :80, dropbear 2018.x).");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Err(alkane_flash::stock::StockError::NotApplicable) => {
|
||||||
|
return Err("this board is not an alkane A113D; pass --stock-firmware \
|
||||||
|
<genuine Bitmain OTA .tar.gz or SD .zip> to restore it"
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Parse the genuine vendor package for the stock kernel + rootfs. The kernel
|
// Parse the genuine vendor package for the stock kernel + rootfs. The kernel
|
||||||
// device tree is not in distributable Bitmain firmware; the toolkit supplies
|
// device tree is not in distributable Bitmain firmware; the toolkit supplies
|
||||||
// the correct per-board dtb, so any genuine package (OTA or SD) works here.
|
// the correct per-board dtb, so any genuine package (OTA or SD) works here.
|
||||||
@@ -1139,6 +1179,7 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
|
|||||||
let images = RestoreImages {
|
let images = RestoreImages {
|
||||||
kernel: &fw.kernel,
|
kernel: &fw.kernel,
|
||||||
rootfs: &fw.rootfs,
|
rootfs: &fw.rootfs,
|
||||||
|
dtb: fw.dtb.as_deref(),
|
||||||
};
|
};
|
||||||
stock::restore_to_stock(&host, &images, password.as_deref())?;
|
stock::restore_to_stock(&host, &images, password.as_deref())?;
|
||||||
println!("restore-to-stock reported success (stock images written, BOOT.bin preserved).");
|
println!("restore-to-stock reported success (stock images written, BOOT.bin preserved).");
|
||||||
@@ -1147,9 +1188,318 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Run a command as root on a stock board and print its output (drives the DSH
|
||||||
|
/// root-on-stock primitive; used to build and debug the flash operations).
|
||||||
|
fn run_root_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let opts = parse_args(args, ssh_values(), &[])?;
|
||||||
|
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||||
|
let cmd = opts.positionals.join(" ");
|
||||||
|
if cmd.trim().is_empty() {
|
||||||
|
return Err("usage: alkane-cli afw root-run --host <ip> <command...>".into());
|
||||||
|
}
|
||||||
|
let password = read_board_password(&opts)?;
|
||||||
|
let out = stock::root_exec(&host, password.as_deref(), &cmd)?;
|
||||||
|
print!("{out}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Readable zynq NAND install-from-stock: wrap the afw's zImage/rootfs as the
|
||||||
|
/// legacy uImages the stock U-Boot boots, carve the on-board genuine-stock
|
||||||
|
/// backup, write the boot slots and reboot. Drives the DSH root-on-stock
|
||||||
|
/// primitive; board must be on stock (credential root/root).
|
||||||
|
fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let opts = parse_args(
|
||||||
|
args,
|
||||||
|
&[ssh_values(), &["confirm"]].concat(),
|
||||||
|
&["allow-unsigned"],
|
||||||
|
)?;
|
||||||
|
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||||
|
let afw_path = opts
|
||||||
|
.positionals
|
||||||
|
.first()
|
||||||
|
.ok_or("usage: alkane-cli afw nand-install <afw> --host <ip> --confirm FLASH")?;
|
||||||
|
let verified = load_afw(afw_path, &opts)?;
|
||||||
|
if !zynq::owns_board(&verified.manifest.board) {
|
||||||
|
return Err(format!(
|
||||||
|
"nand-install is zynq-7010 only, not {}",
|
||||||
|
verified.manifest.board
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
if opts.value("confirm") != Some("FLASH") {
|
||||||
|
return Err("refusing to install without --confirm FLASH".into());
|
||||||
|
}
|
||||||
|
let kernel = verified
|
||||||
|
.image("kernel")
|
||||||
|
.ok_or("afw missing kernel image")?
|
||||||
|
.1;
|
||||||
|
let dtb = verified.image("dtb").ok_or("afw missing dtb image")?.1;
|
||||||
|
let rootfs = verified
|
||||||
|
.image("rootfs")
|
||||||
|
.ok_or("afw missing rootfs image")?
|
||||||
|
.1;
|
||||||
|
let password = read_board_password(&opts)?;
|
||||||
|
println!(
|
||||||
|
"installing {} onto stock board {host} (readable NAND path)...",
|
||||||
|
verified.manifest.board
|
||||||
|
);
|
||||||
|
zynq_nand::install_from_stock(&host, kernel, dtb, rootfs, password.as_deref())?;
|
||||||
|
println!(
|
||||||
|
"install reported success (on-board stock backup carved; boot slots written; rebooting)."
|
||||||
|
);
|
||||||
|
print!("{}", zynq_verify_hint(&host));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Readable zynq restore-to-stock: write the vendor stock kernel/dtb/rootfs
|
||||||
|
/// back to the boot slots over SSH (board on alkane). Needs the alkane image
|
||||||
|
/// that exposes the boot partitions.
|
||||||
|
fn run_nand_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let opts = parse_args(
|
||||||
|
args,
|
||||||
|
&[ssh_values(), &["confirm", "stock-firmware"]].concat(),
|
||||||
|
&["dry-run"],
|
||||||
|
)?;
|
||||||
|
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||||
|
let firmware = opts
|
||||||
|
.value("stock-firmware")
|
||||||
|
.ok_or("--stock-firmware <file> is required")?;
|
||||||
|
let fw = stock_firmware::parse(Path::new(firmware))?;
|
||||||
|
println!("stock firmware: {}", fw.summary());
|
||||||
|
if opts.value("confirm") != Some("FLASH") {
|
||||||
|
return Err("refusing to restore without --confirm FLASH".into());
|
||||||
|
}
|
||||||
|
let password = read_board_password(&opts)?;
|
||||||
|
println!("restoring {host} to genuine stock (readable NAND path)...");
|
||||||
|
zynq_nand::restore_to_stock(
|
||||||
|
&host,
|
||||||
|
&fw.kernel,
|
||||||
|
&fw.rootfs,
|
||||||
|
fw.dtb.as_deref(),
|
||||||
|
password.as_deref(),
|
||||||
|
)?;
|
||||||
|
println!(
|
||||||
|
"restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved)."
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Readable zynq on-board backup check: report whether a restorable genuine-
|
||||||
|
/// stock backup is present (board on alkane). Read-only.
|
||||||
|
fn run_nand_backup_check(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let opts = parse_args(args, ssh_values(), &[])?;
|
||||||
|
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||||
|
let password = read_board_password(&opts)?;
|
||||||
|
if zynq_nand::onboard_backup_present(&host, password.as_deref())? {
|
||||||
|
println!("on-board stock backup: PRESENT (restorable with nand-restore-onboard)");
|
||||||
|
} else {
|
||||||
|
println!("on-board stock backup: ABSENT");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Readable zynq restore-from-on-board-backup: copy the saved stock images back
|
||||||
|
/// to the boot slots (board on alkane), no vendor file needed.
|
||||||
|
fn run_nand_restore_onboard(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &[])?;
|
||||||
|
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||||
|
if opts.value("confirm") != Some("FLASH") {
|
||||||
|
return Err("refusing to restore without --confirm FLASH".into());
|
||||||
|
}
|
||||||
|
let password = read_board_password(&opts)?;
|
||||||
|
println!("restoring {host} to stock from its on-board backup (readable NAND path)...");
|
||||||
|
zynq_nand::restore_from_onboard(&host, password.as_deref())?;
|
||||||
|
println!("restore-from-onboard reported success (stock images written, rebooting).");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run a command as root on an alkane board over SSH and print its output
|
||||||
|
/// (the alkane-side analog of root-run; used to drive and debug the
|
||||||
|
/// alkane-side NAND operations: restore-to-stock and on-board backup/restore).
|
||||||
|
fn run_ssh_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let opts = parse_args(args, ssh_values(), &[])?;
|
||||||
|
let cmd = opts.positionals.join(" ");
|
||||||
|
if cmd.trim().is_empty() {
|
||||||
|
return Err("usage: alkane-cli afw ssh-run --host <ip> <command...>".into());
|
||||||
|
}
|
||||||
|
let (ssh, _secret) = ssh_options(&opts, "root")?;
|
||||||
|
let mut transport = SshTransport::connect(ssh, true)?;
|
||||||
|
let out = transport.root_command(&cmd, std::time::Duration::from_secs(120))?;
|
||||||
|
print!("{}", String::from_utf8_lossy(&out));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stream a local file to a stock board as root (drives the DSH root-on-stock
|
||||||
|
/// primitive; used to stage kernel/rootfs images for the flash operations).
|
||||||
|
fn run_root_put(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let opts = parse_args(args, &[ssh_values(), &["remote"]].concat(), &[])?;
|
||||||
|
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||||
|
let remote = opts
|
||||||
|
.value("remote")
|
||||||
|
.ok_or("--remote <path> is required")?
|
||||||
|
.to_owned();
|
||||||
|
let local = opts
|
||||||
|
.positionals
|
||||||
|
.first()
|
||||||
|
.ok_or("usage: alkane-cli afw root-put --host <ip> --remote <path> <local-file>")?;
|
||||||
|
let data = std::fs::read(local)?;
|
||||||
|
let password = read_board_password(&opts)?;
|
||||||
|
stock::root_put(&host, password.as_deref(), &data, &remote)?;
|
||||||
|
println!("put {} bytes -> {remote}", data.len());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Report whether an alkane board holds a restorable on-board stock backup.
|
||||||
|
/// Read-only (no FLASH confirmation).
|
||||||
|
fn run_backup_check(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let opts = parse_args(args, ssh_values(), &[])?;
|
||||||
|
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||||
|
let password = read_board_password(&opts)?;
|
||||||
|
let present = stock::onboard_stock_backup_present(&host, password.as_deref())?;
|
||||||
|
println!("on-board stock backup present: {present}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restore an alkane board to genuine stock from its on-board backup (no vendor
|
||||||
|
/// firmware file). Destructive; gated by --confirm FLASH.
|
||||||
|
fn run_restore_onboard(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["dry-run"])?;
|
||||||
|
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||||
|
let password = read_board_password(&opts)?;
|
||||||
|
if opts.flag("dry-run") {
|
||||||
|
println!(
|
||||||
|
"DRY RUN: would restore {host} to stock from its on-board backup \
|
||||||
|
(BOOT.bin preserved). Re-run with --confirm FLASH."
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if opts.value("confirm") != Some("FLASH") {
|
||||||
|
return Err("refusing to restore without --confirm FLASH".into());
|
||||||
|
}
|
||||||
|
println!("restoring {host} to stock from its on-board backup (network-only)...");
|
||||||
|
stock::restore_from_onboard_backup(
|
||||||
|
&host,
|
||||||
|
password.as_deref(),
|
||||||
|
std::time::Duration::from_secs(300),
|
||||||
|
)?;
|
||||||
|
println!(
|
||||||
|
"restore-from-onboard reported success. Verify independently the board answers as stock."
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a bootable SD installation-media card image (and optionally write it to
|
||||||
|
/// a device). Zynq-7010 only for now.
|
||||||
|
///
|
||||||
|
/// afw make-media --kind stock --stock-package <zip|dir> --out card.img
|
||||||
|
/// afw make-media --kind alkane --mode simpleboot|installer --afw <f.afw> --out card.img
|
||||||
|
/// [--allow-unsigned] [--write /dev/sdX --confirm WRITE]
|
||||||
|
fn run_make_media(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
use alkane_flash::sd_media;
|
||||||
|
let opts = parse_args(
|
||||||
|
args,
|
||||||
|
&[
|
||||||
|
"kind",
|
||||||
|
"mode",
|
||||||
|
"afw",
|
||||||
|
"stock-package",
|
||||||
|
"board",
|
||||||
|
"out",
|
||||||
|
"write",
|
||||||
|
"confirm",
|
||||||
|
"expect-board",
|
||||||
|
],
|
||||||
|
&["allow-unsigned"],
|
||||||
|
)?;
|
||||||
|
let kind = opts
|
||||||
|
.value("kind")
|
||||||
|
.ok_or("usage: alkane-cli afw make-media --kind <stock|alkane> ... --out <card.img>")?;
|
||||||
|
let board = opts.value("board").unwrap_or("zynq-7010");
|
||||||
|
if board != "zynq-7010" {
|
||||||
|
return Err(format!("make-media supports --board zynq-7010 only (got {board})").into());
|
||||||
|
}
|
||||||
|
let out = opts
|
||||||
|
.value("out")
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.or_else(|| opts.positionals.first().map(PathBuf::from))
|
||||||
|
.ok_or("make-media: --out <card.img> required")?;
|
||||||
|
let now = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs() as u32)
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
match kind {
|
||||||
|
"stock" => {
|
||||||
|
let pkg = opts
|
||||||
|
.value("stock-package")
|
||||||
|
.ok_or("make-media --kind stock needs --stock-package <zip|dir>")?;
|
||||||
|
let pkg_path = Path::new(pkg);
|
||||||
|
// Unpack a .zip to an ephemeral dir; use a directory as-is.
|
||||||
|
let staged;
|
||||||
|
let dir: PathBuf = if pkg_path.is_dir() {
|
||||||
|
pkg_path.to_path_buf()
|
||||||
|
} else if pkg_path
|
||||||
|
.extension()
|
||||||
|
.is_some_and(|e| e.eq_ignore_ascii_case("zip"))
|
||||||
|
{
|
||||||
|
staged =
|
||||||
|
std::env::temp_dir().join(format!("alkane-media-pkg-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&staged);
|
||||||
|
std::fs::create_dir_all(&staged)?;
|
||||||
|
let status = std::process::Command::new("unzip")
|
||||||
|
.args(["-o", "-q"])
|
||||||
|
.arg(pkg_path)
|
||||||
|
.arg("-d")
|
||||||
|
.arg(&staged)
|
||||||
|
.status()?;
|
||||||
|
if !status.success() {
|
||||||
|
return Err(format!("unzip {pkg} failed").into());
|
||||||
|
}
|
||||||
|
staged
|
||||||
|
} else {
|
||||||
|
return Err(
|
||||||
|
format!("--stock-package must be a directory or a .zip (got {pkg})").into(),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
sd_media::build_stock_recovery_card(&dir, &out)?;
|
||||||
|
}
|
||||||
|
"alkane" => {
|
||||||
|
let afw_path = opts
|
||||||
|
.value("afw")
|
||||||
|
.ok_or("make-media --kind alkane needs --afw <file.afw>")?;
|
||||||
|
let verified = load_afw(afw_path, &opts)?;
|
||||||
|
match opts.value("mode").unwrap_or("simpleboot") {
|
||||||
|
"simpleboot" | "simple-boot" => {
|
||||||
|
sd_media::build_zynq_simpleboot_card(&verified, &out, now)?
|
||||||
|
}
|
||||||
|
"installer" => sd_media::build_zynq_installer_card(&verified, &out, now)?,
|
||||||
|
other => {
|
||||||
|
return Err(format!("--mode must be simpleboot|installer (got {other})").into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other => return Err(format!("--kind must be stock|alkane (got {other})").into()),
|
||||||
|
}
|
||||||
|
println!("wrote card image: {}", out.display());
|
||||||
|
|
||||||
|
if let Some(dev) = opts.value("write") {
|
||||||
|
if opts.value("confirm") != Some("WRITE") {
|
||||||
|
return Err(format!(
|
||||||
|
"refusing to write to {dev} without --confirm WRITE (card image is at {})",
|
||||||
|
out.display()
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
eprintln!("writing {} to {dev} ...", out.display());
|
||||||
|
sd_media::write_image_to_device(&out, Path::new(dev))?;
|
||||||
|
println!("written to {dev}; sync complete");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn run_afw(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
fn run_afw(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let subcommand = args.first().ok_or(
|
let subcommand = args.first().ok_or(
|
||||||
"usage: alkane-cli afw <compat|fetch-latest|verify|inspect|plan|preflight|install|verify-live|restore|restore-stock>",
|
"usage: alkane-cli afw <compat|fetch-latest|verify|inspect|plan|preflight|install|verify-live|restore|restore-stock|backup-check|restore-onboard|make-media>",
|
||||||
)?;
|
)?;
|
||||||
let rest = &args[1..];
|
let rest = &args[1..];
|
||||||
match subcommand.as_str() {
|
match subcommand.as_str() {
|
||||||
@@ -1163,6 +1513,16 @@ fn run_afw(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
"verify-live" => run_verify_live(rest),
|
"verify-live" => run_verify_live(rest),
|
||||||
"restore" => run_restore(rest),
|
"restore" => run_restore(rest),
|
||||||
"restore-stock" => run_restore_stock(rest),
|
"restore-stock" => run_restore_stock(rest),
|
||||||
|
"backup-check" => run_backup_check(rest),
|
||||||
|
"restore-onboard" => run_restore_onboard(rest),
|
||||||
|
"root-run" => run_root_run(rest),
|
||||||
|
"root-put" => run_root_put(rest),
|
||||||
|
"ssh-run" => run_ssh_run(rest),
|
||||||
|
"nand-install" => run_nand_install(rest),
|
||||||
|
"nand-restore-stock" => run_nand_restore_stock(rest),
|
||||||
|
"nand-backup-check" => run_nand_backup_check(rest),
|
||||||
|
"nand-restore-onboard" => run_nand_restore_onboard(rest),
|
||||||
|
"make-media" => run_make_media(rest),
|
||||||
other => Err(format!("unknown afw subcommand {other}").into()),
|
other => Err(format!("unknown afw subcommand {other}").into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,660 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
//! Readable Amlogic A113D (Amlogic AXG, Antminer BHB42XXX) install/restore over
|
||||||
|
//! the FLAG-BASED boot chain. This is the Claude-domain counterpart of
|
||||||
|
//! `zynq_nand`: it drives the DSH root-on-stock primitive (`stock::root_exec` /
|
||||||
|
//! `stock::root_put`) for the from-stock install, and the alkane SSH transport
|
||||||
|
//! for the in-band restore, with the stock-access method never read here.
|
||||||
|
//!
|
||||||
|
//! Mechanism (CONFIRMED live 2026-11-13, see alkane-sdk-construction
|
||||||
|
//! alkane-a113d-image-bringup):
|
||||||
|
//!
|
||||||
|
//! - The OS files `alkane/{vmlinux.bin,devicetree.dtb,uramdisk.image.gz}` are
|
||||||
|
//! staged into the nvdata UBI volume (UBIFS), exactly as the alkane boot chain
|
||||||
|
//! reads them (`ubifsload`). Zero raw writes to the brick-sensitive regions.
|
||||||
|
//! - A one-byte-magic FLAG lives in the `misc` partition (the Android BCB block,
|
||||||
|
//! abs NAND 0x1000000) at erase-block 1 (offset 0x20000, abs 0x1020000). Block
|
||||||
|
//! 0 (the BCB) is never touched. The flag is the four bytes "ALAN".
|
||||||
|
//! - Stock U-Boot's `bootcmd` is set (once, in-band via /dev/nand_env from stock)
|
||||||
|
//! to `run checkalk; run storeboot`, where `checkalk` RAW-reads the flag page
|
||||||
|
//! (`nand read`, NO UBI) and, only if the magic matches, runs `alkboot` (which
|
||||||
|
//! mounts the nvdata UBIFS and boots alkane). When the flag is absent the stock
|
||||||
|
//! path is a pure raw read + `storeboot`, which boots genuine stock STABLY (a
|
||||||
|
//! ubi/ubifs op in the stock boot path instead makes stock's firstboot
|
||||||
|
//! supervisor reboot-loop - that is why the flag read must be raw).
|
||||||
|
//! - INSTALL (stock -> alkane): stage the files, write the env, set flag=ALAN.
|
||||||
|
//! - RESTORE (alkane -> stock): erase the flag block in-band from the running
|
||||||
|
//! alkane OS (which exposes `misc` as an MTD). One raw NAND erase, `reboot -f`,
|
||||||
|
//! and stock boots via `storeboot`. Fully network-only; the alkane payload and
|
||||||
|
//! the env are left in place, so re-install is just re-writing the flag.
|
||||||
|
//!
|
||||||
|
//! itest note: this vendor U-Boot's `itest.l *<mem>` does NOT compare correctly,
|
||||||
|
//! but `itest.b *<mem>` does, so `checkalk` tests the four magic bytes with
|
||||||
|
//! nested `itest.b`. CONFIRMED live 2026-11-13.
|
||||||
|
|
||||||
|
use crate::stock::StockError;
|
||||||
|
use crate::transport::{Remote, SshOptions, SshTransport};
|
||||||
|
use crate::uimage::crc32;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
pub const BOARD: &str = "a113d";
|
||||||
|
|
||||||
|
/// U-Boot env blob size on this board (CONFIRMED: `/dev/nand_env` is 64 KiB, a
|
||||||
|
/// standard U-Boot env = 4-byte little-endian CRC32 + NUL-separated key=value,
|
||||||
|
/// double-NUL terminated, 0x00-padded).
|
||||||
|
const ENV_SIZE: usize = 65536;
|
||||||
|
|
||||||
|
/// Flag: four magic bytes "ALAN" at misc (abs 0x1000000) erase-block 1.
|
||||||
|
const FLAG_ABS_OFFSET: u64 = 0x1020000; // misc base 0x1000000 + block 1 (0x20000)
|
||||||
|
const FLAG_BLOCK_IN_MISC: u64 = 0x20000; // offset of the flag block within the misc MTD
|
||||||
|
const FLAG_MAGIC: [u8; 4] = *b"ALAN";
|
||||||
|
|
||||||
|
/// Boot load addresses (CONFIRMED live) and the alkane console bootargs.
|
||||||
|
const KRNADDR: &str = "0x1200000";
|
||||||
|
const FDTADDR: &str = "0x8000000";
|
||||||
|
const RDADDR: &str = "0x8100000";
|
||||||
|
const ALK_BOOTARGS: &str = "console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend";
|
||||||
|
|
||||||
|
/// The on-board basenames inside the nvdata UBI volume's `alkane/` directory.
|
||||||
|
const ALKANE_DIR: &str = "alkane";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Shell abstraction: StockShell drives the DSH root primitive; AlkaneShell the
|
||||||
|
// alkane SSH transport. (Mirrors zynq_nand.)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
trait Shell {
|
||||||
|
fn exec(&mut self, cmd: &str) -> Result<String, StockError>;
|
||||||
|
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError>;
|
||||||
|
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StockShell {
|
||||||
|
host: String,
|
||||||
|
password: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Shell for StockShell {
|
||||||
|
fn exec(&mut self, cmd: &str) -> Result<String, StockError> {
|
||||||
|
crate::stock::root_exec(&self.host, self.password.as_deref(), cmd)
|
||||||
|
}
|
||||||
|
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError> {
|
||||||
|
// root_exec already carries a generous timeout in the method.
|
||||||
|
crate::stock::root_exec(&self.host, self.password.as_deref(), cmd)
|
||||||
|
}
|
||||||
|
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> {
|
||||||
|
crate::stock::root_put(&self.host, self.password.as_deref(), data, remote_path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct AlkaneShell {
|
||||||
|
transport: SshTransport,
|
||||||
|
_secret: TempFile,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AlkaneShell {
|
||||||
|
fn connect(host: &str, password: Option<&str>) -> Result<Self, StockError> {
|
||||||
|
// Password in a 0600 temp file; a throwaway empty known_hosts (the host
|
||||||
|
// key legitimately changes across stock<->alkane). Same stance as zynq.
|
||||||
|
let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?;
|
||||||
|
let known = temp_path("kh");
|
||||||
|
let _ = std::fs::File::create(&known);
|
||||||
|
let options = SshOptions {
|
||||||
|
host: host.to_owned(),
|
||||||
|
port: 22,
|
||||||
|
user: "root".to_owned(),
|
||||||
|
identity_file: None,
|
||||||
|
password_file: Some(secret.0.clone()),
|
||||||
|
known_hosts: Some(known),
|
||||||
|
root_method: crate::transport::RootMethod::Auto,
|
||||||
|
update_daemon_port: None,
|
||||||
|
};
|
||||||
|
let transport =
|
||||||
|
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
|
||||||
|
Ok(AlkaneShell {
|
||||||
|
transport,
|
||||||
|
_secret: secret,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Shell for AlkaneShell {
|
||||||
|
fn exec(&mut self, cmd: &str) -> Result<String, StockError> {
|
||||||
|
self.transport
|
||||||
|
.root_command(cmd, Duration::from_secs(120))
|
||||||
|
.map(|o| String::from_utf8_lossy(&o).into_owned())
|
||||||
|
.map_err(|e| StockError::Method(e.to_string()))
|
||||||
|
}
|
||||||
|
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError> {
|
||||||
|
self.transport
|
||||||
|
.root_command(cmd, Duration::from_secs(900))
|
||||||
|
.map(|o| String::from_utf8_lossy(&o).into_owned())
|
||||||
|
.map_err(|e| StockError::Method(e.to_string()))
|
||||||
|
}
|
||||||
|
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> {
|
||||||
|
let tmp = TempFile::with(data, "put")?;
|
||||||
|
self.transport
|
||||||
|
.push(&tmp.0, remote_path, Duration::from_secs(900))
|
||||||
|
.map_err(|e| StockError::Method(e.to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static TEMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||||
|
|
||||||
|
fn temp_path(tag: &str) -> PathBuf {
|
||||||
|
let n = TEMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
std::env::temp_dir().join(format!("alkane-aml-{}-{}-{}", std::process::id(), tag, n))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A 0600 temp file removed on drop.
|
||||||
|
struct TempFile(PathBuf);
|
||||||
|
impl TempFile {
|
||||||
|
fn with(contents: &[u8], tag: &str) -> Result<Self, StockError> {
|
||||||
|
let path = temp_path(tag);
|
||||||
|
write_private(&path, contents).map_err(|e| StockError::Io(e.to_string()))?;
|
||||||
|
Ok(TempFile(path))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for TempFile {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = std::fs::remove_file(&self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
|
||||||
|
use std::io::Write as _;
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
|
let mut f = std::fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.truncate(true)
|
||||||
|
.write(true)
|
||||||
|
.mode(0o600)
|
||||||
|
.open(path)?;
|
||||||
|
f.write_all(contents)?;
|
||||||
|
f.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
|
||||||
|
std::fs::write(path, contents)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// base64 (busybox-safe: decode a possibly line-wrapped stream).
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn b64_decode(s: &str) -> Option<Vec<u8>> {
|
||||||
|
const INV: u8 = 0xFF;
|
||||||
|
fn val(c: u8) -> u8 {
|
||||||
|
match c {
|
||||||
|
b'A'..=b'Z' => c - b'A',
|
||||||
|
b'a'..=b'z' => c - b'a' + 26,
|
||||||
|
b'0'..=b'9' => c - b'0' + 52,
|
||||||
|
b'+' => 62,
|
||||||
|
b'/' => 63,
|
||||||
|
_ => INV,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut acc = 0u32;
|
||||||
|
let mut bits = 0u32;
|
||||||
|
for &c in s.as_bytes() {
|
||||||
|
if c == b'=' {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let v = val(c);
|
||||||
|
if v == INV {
|
||||||
|
continue; // skip whitespace / newlines
|
||||||
|
}
|
||||||
|
acc = (acc << 6) | v as u32;
|
||||||
|
bits += 6;
|
||||||
|
if bits >= 8 {
|
||||||
|
bits -= 8;
|
||||||
|
out.push((acc >> bits) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn b64_encode(data: &[u8]) -> String {
|
||||||
|
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||||
|
for chunk in data.chunks(3) {
|
||||||
|
let b = [
|
||||||
|
chunk[0],
|
||||||
|
*chunk.get(1).unwrap_or(&0),
|
||||||
|
*chunk.get(2).unwrap_or(&0),
|
||||||
|
];
|
||||||
|
let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
|
||||||
|
out.push(T[((n >> 18) & 63) as usize] as char);
|
||||||
|
out.push(T[((n >> 12) & 63) as usize] as char);
|
||||||
|
out.push(if chunk.len() > 1 {
|
||||||
|
T[((n >> 6) & 63) as usize] as char
|
||||||
|
} else {
|
||||||
|
'='
|
||||||
|
});
|
||||||
|
out.push(if chunk.len() > 2 {
|
||||||
|
T[(n & 63) as usize] as char
|
||||||
|
} else {
|
||||||
|
'='
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// U-Boot environment (standard format) read / parse / build / write.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Read the 64 KiB U-Boot env blob from /dev/nand_env (stock only).
|
||||||
|
fn read_env(sh: &mut dyn Shell) -> Result<Vec<u8>, StockError> {
|
||||||
|
let out = sh.exec(
|
||||||
|
"echo B64START; dd if=/dev/nand_env bs=65536 count=1 2>/dev/null | base64; echo B64END",
|
||||||
|
)?;
|
||||||
|
let start = out
|
||||||
|
.find("B64START")
|
||||||
|
.ok_or_else(|| StockError::Method("env read: no marker".into()))?;
|
||||||
|
let end = out
|
||||||
|
.find("B64END")
|
||||||
|
.ok_or_else(|| StockError::Method("env read: no end marker".into()))?;
|
||||||
|
let b64 = &out[start + "B64START".len()..end];
|
||||||
|
let blob = b64_decode(b64).ok_or_else(|| StockError::Method("env read: bad base64".into()))?;
|
||||||
|
if blob.len() != ENV_SIZE {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"env read: {} bytes (expected {ENV_SIZE})",
|
||||||
|
blob.len()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]);
|
||||||
|
if crc32(&blob[4..]) != stored {
|
||||||
|
return Err(StockError::Method("env read: CRC mismatch".into()));
|
||||||
|
}
|
||||||
|
Ok(blob)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse the env body into ordered (key, value) pairs (up to the double-NUL).
|
||||||
|
fn parse_env(blob: &[u8]) -> Vec<(String, String)> {
|
||||||
|
let body = &blob[4..];
|
||||||
|
let end = body
|
||||||
|
.windows(2)
|
||||||
|
.position(|w| w == [0, 0])
|
||||||
|
.unwrap_or(body.len());
|
||||||
|
let mut vars = Vec::new();
|
||||||
|
for kv in body[..end].split(|&b| b == 0) {
|
||||||
|
if kv.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(eq) = kv.iter().position(|&b| b == b'=') {
|
||||||
|
let k = String::from_utf8_lossy(&kv[..eq]).into_owned();
|
||||||
|
let v = String::from_utf8_lossy(&kv[eq + 1..]).into_owned();
|
||||||
|
vars.push((k, v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
vars
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a 64 KiB env blob from ordered (key,value) pairs: CRC32 + body +
|
||||||
|
/// double-NUL + 0x00 padding (what a clean `saveenv` produces).
|
||||||
|
fn build_env(vars: &[(String, String)]) -> Result<Vec<u8>, StockError> {
|
||||||
|
let mut body = Vec::with_capacity(ENV_SIZE);
|
||||||
|
for (k, v) in vars {
|
||||||
|
body.extend_from_slice(k.as_bytes());
|
||||||
|
body.push(b'=');
|
||||||
|
body.extend_from_slice(v.as_bytes());
|
||||||
|
body.push(0);
|
||||||
|
}
|
||||||
|
body.push(0); // terminating double-NUL (last var's NUL + this one)
|
||||||
|
if body.len() > ENV_SIZE - 4 {
|
||||||
|
return Err(StockError::Method("env too large".into()));
|
||||||
|
}
|
||||||
|
body.resize(ENV_SIZE - 4, 0);
|
||||||
|
let crc = crc32(&body);
|
||||||
|
let mut blob = Vec::with_capacity(ENV_SIZE);
|
||||||
|
blob.extend_from_slice(&crc.to_le_bytes());
|
||||||
|
blob.extend_from_slice(&body);
|
||||||
|
Ok(blob)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set (or insert, preserving order) a variable.
|
||||||
|
fn set_var(vars: &mut Vec<(String, String)>, key: &str, value: &str) {
|
||||||
|
if let Some(slot) = vars.iter_mut().find(|(k, _)| k == key) {
|
||||||
|
slot.1 = value.to_owned();
|
||||||
|
} else {
|
||||||
|
vars.push((key.to_owned(), value.to_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write the env blob to /dev/nand_env and read it back byte-exact BEFORE any
|
||||||
|
/// reboot (the env is only consumed at next boot, so a verified read-back cannot
|
||||||
|
/// brick). On a read-back mismatch the caller must restore the previous env.
|
||||||
|
fn write_env(sh: &mut dyn Shell, blob: &[u8]) -> Result<(), StockError> {
|
||||||
|
let b64 = b64_encode(blob);
|
||||||
|
// Stream the blob to a temp file, then dd it to /dev/nand_env in one write.
|
||||||
|
sh.put(b64.as_bytes(), "/tmp/.alkenv.b64")?;
|
||||||
|
let out = sh.exec(
|
||||||
|
"base64 -d /tmp/.alkenv.b64 > /tmp/.alkenv.bin 2>/dev/null; \
|
||||||
|
dd if=/tmp/.alkenv.bin of=/dev/nand_env bs=65536 count=1 2>/dev/null; sync; \
|
||||||
|
echo RB=$(dd if=/dev/nand_env bs=65536 count=1 2>/dev/null | md5sum | cut -d' ' -f1); \
|
||||||
|
rm -f /tmp/.alkenv.b64 /tmp/.alkenv.bin",
|
||||||
|
)?;
|
||||||
|
let want = md5_hex(blob);
|
||||||
|
let got = out
|
||||||
|
.split("RB=")
|
||||||
|
.nth(1)
|
||||||
|
.map(|s| s.trim().to_owned())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if got != want {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"env write read-back mismatch: wrote {want}, read {got}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn md5_hex(data: &[u8]) -> String {
|
||||||
|
crate::md5::md5_hex(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// MTD / flag helpers.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Find the /dev/mtdN whose /proc/mtd label matches `name`.
|
||||||
|
fn find_mtd(sh: &mut dyn Shell, name: &str) -> Result<String, StockError> {
|
||||||
|
let out = sh.exec("cat /proc/mtd")?;
|
||||||
|
for line in out.lines() {
|
||||||
|
if line.contains(&format!("\"{name}\"")) {
|
||||||
|
if let Some((dev, _)) = line.split_once(':') {
|
||||||
|
return Ok(format!("/dev/{}", dev.trim()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(StockError::Method(format!("no '{name}' MTD on this board")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Discover the nvdata UBI volume's name (never assumed: vendor histories leave
|
||||||
|
/// different names). Looks for an already-attached ubi volume on the nvdata MTD.
|
||||||
|
fn discover_nvdata_volume(sh: &mut dyn Shell) -> Result<(String, String), StockError> {
|
||||||
|
// Returns (mountpoint, volume_name). On stock the vendor mounts nvdata (e.g.
|
||||||
|
// at /tmp/miner); find the ubifs mount whose volume sits on the nvdata MTD.
|
||||||
|
let mounts = sh.exec("cat /proc/mounts")?;
|
||||||
|
for line in mounts.lines() {
|
||||||
|
// e.g. "/dev/ubi2_0 /tmp/miner ubifs rw,..."
|
||||||
|
let mut it = line.split_whitespace();
|
||||||
|
let dev = it.next().unwrap_or("");
|
||||||
|
let mnt = it.next().unwrap_or("");
|
||||||
|
let fs = it.next().unwrap_or("");
|
||||||
|
if fs == "ubifs" && dev.contains("ubi") {
|
||||||
|
// read the volume name from sysfs: /sys/class/ubi/<ubiX_0>/name
|
||||||
|
let base = dev.trim_start_matches("/dev/");
|
||||||
|
let name = sh
|
||||||
|
.exec(&format!("cat /sys/class/ubi/{base}/name 2>/dev/null"))?
|
||||||
|
.trim()
|
||||||
|
.to_owned();
|
||||||
|
// Only accept the nvdata volume (skip the small config_data volume).
|
||||||
|
// nvdata is the large one; confirm by its mount not being /config.
|
||||||
|
if !name.is_empty() && mnt != "/config" {
|
||||||
|
return Ok((mnt.to_owned(), name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(StockError::Method(
|
||||||
|
"could not find the mounted nvdata UBI volume".into(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write the ALAN flag into misc block 1 (flag=alkane). `misc_dev` is the misc
|
||||||
|
/// MTD device on the running OS (stock: /dev/mtd2; alkane: whatever /proc/mtd
|
||||||
|
/// shows for "misc").
|
||||||
|
fn set_flag_alkane(sh: &mut dyn Shell, misc_dev: &str) -> Result<(), StockError> {
|
||||||
|
// one page: magic + 0xFF pad
|
||||||
|
let mut page = FLAG_MAGIC.to_vec();
|
||||||
|
page.resize(2048, 0xFF);
|
||||||
|
sh.put(&page, "/tmp/.alkflag")?;
|
||||||
|
let out = sh.exec(&format!(
|
||||||
|
"flash_erase {misc_dev} 0x{FLAG_BLOCK_IN_MISC:x} 1 >/dev/null 2>&1; \
|
||||||
|
nandwrite -s 0x{FLAG_BLOCK_IN_MISC:x} -p {misc_dev} /tmp/.alkflag >/dev/null 2>&1; sync; \
|
||||||
|
echo RB=$(dd if={misc_dev} bs=2048 skip={blk} count=1 2>/dev/null | md5sum | cut -d' ' -f1); \
|
||||||
|
rm -f /tmp/.alkflag",
|
||||||
|
blk = FLAG_BLOCK_IN_MISC / 2048
|
||||||
|
))?;
|
||||||
|
let want = md5_hex(&page);
|
||||||
|
let got = out
|
||||||
|
.split("RB=")
|
||||||
|
.nth(1)
|
||||||
|
.map(|s| s.trim().to_owned())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if got != want {
|
||||||
|
return Err(StockError::Method("flag write read-back mismatch".into()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Erase the flag block (flag=stock).
|
||||||
|
fn clear_flag(sh: &mut dyn Shell, misc_dev: &str) -> Result<(), StockError> {
|
||||||
|
sh.exec(&format!(
|
||||||
|
"flash_erase {misc_dev} 0x{FLAG_BLOCK_IN_MISC:x} 1 >/dev/null 2>&1; sync; echo CLEARED"
|
||||||
|
))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// The flag-based boot-chain env vars.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// checkalk raw-reads the flag page and tests the four magic bytes with nested
|
||||||
|
/// `itest.b` (this vendor U-Boot mis-compares `itest.l *<mem>`); only on a match
|
||||||
|
/// does it run alkboot. No ubi/ubifs here - that keeps the stock path raw.
|
||||||
|
fn checkalk_value() -> String {
|
||||||
|
format!(
|
||||||
|
"nand read 0x08000000 0x{FLAG_ABS_OFFSET:x} 0x800; \
|
||||||
|
if itest.b *0x08000000 == 0x{a:02x}; then \
|
||||||
|
if itest.b *0x08000001 == 0x{l:02x}; then \
|
||||||
|
if itest.b *0x08000002 == 0x{a2:02x}; then \
|
||||||
|
if itest.b *0x08000003 == 0x{n:02x}; then run alkboot; fi; fi; fi; fi",
|
||||||
|
a = FLAG_MAGIC[0],
|
||||||
|
l = FLAG_MAGIC[1],
|
||||||
|
a2 = FLAG_MAGIC[2],
|
||||||
|
n = FLAG_MAGIC[3],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// alkboot mounts the nvdata UBIFS and boots alkane from `alkane/`.
|
||||||
|
fn alkboot_value(volume: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"setenv bootargs ${{alkbootargs}}; ubi part nvdata; ubifsmount ubi0:{volume}; \
|
||||||
|
ubifsload ${{krnaddr}} {ALKANE_DIR}/vmlinux.bin; \
|
||||||
|
ubifsload ${{fdtaddr}} {ALKANE_DIR}/devicetree.dtb; \
|
||||||
|
ubifsload ${{rdaddr}} {ALKANE_DIR}/uramdisk.image.gz; \
|
||||||
|
booti ${{krnaddr}} ${{rdaddr}} ${{fdtaddr}}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Install the flag-based boot env (preserving all existing stock vars). Leaves
|
||||||
|
/// bootcmd = "run checkalk; run storeboot".
|
||||||
|
fn install_boot_env(sh: &mut dyn Shell, volume: &str) -> Result<(), StockError> {
|
||||||
|
let blob = read_env(sh)?;
|
||||||
|
let mut vars = parse_env(&blob);
|
||||||
|
set_var(&mut vars, "krnaddr", KRNADDR);
|
||||||
|
set_var(&mut vars, "fdtaddr", FDTADDR);
|
||||||
|
set_var(&mut vars, "rdaddr", RDADDR);
|
||||||
|
set_var(&mut vars, "alkbootargs", ALK_BOOTARGS);
|
||||||
|
set_var(&mut vars, "alkboot", &alkboot_value(volume));
|
||||||
|
set_var(&mut vars, "checkalk", &checkalk_value());
|
||||||
|
set_var(&mut vars, "bootcmd", "run checkalk; run storeboot");
|
||||||
|
let new_blob = build_env(&vars)?;
|
||||||
|
write_env(sh, &new_blob)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reboot_stock(sh: &mut dyn Shell) {
|
||||||
|
let _ = sh.exec("sync; reboot");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reboot_alkane(sh: &mut dyn Shell) {
|
||||||
|
// plain `reboot` no-ops on the minimal init; `reboot -f` triggers PSCI reset.
|
||||||
|
let _ = sh.exec("sync; reboot -f");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Public API (dispatched from stock.rs for board == a113d).
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Install alkane onto an A113D running genuine stock, network-only, over the
|
||||||
|
/// DSH root-on-stock primitive. Stages the OS files into the nvdata UBI volume,
|
||||||
|
/// installs the flag-based boot env, and sets flag=alkane; the next boot runs
|
||||||
|
/// alkane. Zero raw writes outside the flag block in `misc`.
|
||||||
|
pub fn install_from_stock(
|
||||||
|
host: &str,
|
||||||
|
kernel_image: &[u8],
|
||||||
|
dtb: &[u8],
|
||||||
|
uramdisk: &[u8],
|
||||||
|
password: Option<&str>,
|
||||||
|
) -> Result<(), StockError> {
|
||||||
|
let mut sh = StockShell {
|
||||||
|
host: host.to_owned(),
|
||||||
|
password: password.map(|s| s.to_owned()),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Guard: this board must be A113D stock (has a 'misc' MTD and a mounted
|
||||||
|
// nvdata UBI). If not, defer to the compiled-in method.
|
||||||
|
let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default();
|
||||||
|
if !proc_mtd.contains("\"nvdata\"") || !proc_mtd.contains("\"misc\"") {
|
||||||
|
return Err(StockError::NotApplicable);
|
||||||
|
}
|
||||||
|
|
||||||
|
let misc = find_mtd(&mut sh, "misc")?;
|
||||||
|
let (mount, volume) = discover_nvdata_volume(&mut sh)?;
|
||||||
|
|
||||||
|
// Stage the three files into <mount>/alkane/ and read-back verify.
|
||||||
|
let dir = format!("{mount}/{ALKANE_DIR}");
|
||||||
|
sh.exec(&format!("mkdir -p {dir}"))?;
|
||||||
|
// rootfs -> dtb -> kernel (kernel lands last).
|
||||||
|
stage_file(&mut sh, uramdisk, &format!("{dir}/uramdisk.image.gz"))?;
|
||||||
|
stage_file(&mut sh, dtb, &format!("{dir}/devicetree.dtb"))?;
|
||||||
|
stage_file(&mut sh, kernel_image, &format!("{dir}/vmlinux.bin"))?;
|
||||||
|
sh.exec("sync")?;
|
||||||
|
|
||||||
|
// Install the flag-based boot env (read-back verified before reboot).
|
||||||
|
install_boot_env(&mut sh, &volume)?;
|
||||||
|
|
||||||
|
// Set flag=alkane, then reboot into alkane.
|
||||||
|
set_flag_alkane(&mut sh, &misc)?;
|
||||||
|
reboot_stock(&mut sh);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stage one file to a UBIFS path and prove its read-back md5 before continuing.
|
||||||
|
fn stage_file(sh: &mut dyn Shell, data: &[u8], dest: &str) -> Result<(), StockError> {
|
||||||
|
let tmp = "/tmp/.alkstage";
|
||||||
|
sh.put(data, tmp)?;
|
||||||
|
let out = sh.exec_long(&format!(
|
||||||
|
"cp -f {tmp} {dest} && sync; echo RB=$(md5sum {dest} | cut -d' ' -f1); rm -f {tmp}"
|
||||||
|
))?;
|
||||||
|
let want = md5_hex(data);
|
||||||
|
let got = out
|
||||||
|
.split("RB=")
|
||||||
|
.nth(1)
|
||||||
|
.map(|s| s.trim().to_owned())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if got != want {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"staged {dest} md5 mismatch: want {want}, got {got}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restore an A113D running alkane back to genuine stock, network-only, in-band
|
||||||
|
/// from the running alkane OS: erase the flag block (flag=stock) and reboot.
|
||||||
|
/// Stock boots via `storeboot` from the untouched `boot` MTD; the alkane payload
|
||||||
|
/// and env are left in place, so a re-install is just re-writing the flag.
|
||||||
|
pub fn restore_to_stock(host: &str, password: Option<&str>) -> Result<(), StockError> {
|
||||||
|
let mut sh = AlkaneShell::connect(host, password)?;
|
||||||
|
|
||||||
|
// Guard: must be the alkane a113d image (exposes 'misc' and 'nvdata' MTDs,
|
||||||
|
// mainline 6.18.48). If 'misc' is absent this is not applicable.
|
||||||
|
let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default();
|
||||||
|
if !proc_mtd.contains("\"misc\"") {
|
||||||
|
return Err(StockError::NotApplicable);
|
||||||
|
}
|
||||||
|
let misc = find_mtd(&mut sh, "misc")?;
|
||||||
|
clear_flag(&mut sh, &misc)?;
|
||||||
|
reboot_alkane(&mut sh);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The on-board stock backup is structural on this board: `storeboot` always
|
||||||
|
/// boots genuine stock from the `boot` MTD (mtd4), which this install never
|
||||||
|
/// writes. So a complete backup is present whenever the board is an A113D.
|
||||||
|
pub fn onboard_backup_present(host: &str, password: Option<&str>) -> Result<bool, StockError> {
|
||||||
|
// Best-effort confirm over alkane that the flag chain is in place; if we
|
||||||
|
// cannot reach alkane, report not-applicable so the caller falls through.
|
||||||
|
let mut sh = AlkaneShell::connect(host, password)?;
|
||||||
|
let proc_mtd = sh.exec("cat /proc/mtd 2>/dev/null").unwrap_or_default();
|
||||||
|
if proc_mtd.contains("\"misc\"") {
|
||||||
|
Ok(true)
|
||||||
|
} else {
|
||||||
|
Err(StockError::NotApplicable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn env_roundtrips_with_crc() {
|
||||||
|
let vars = vec![
|
||||||
|
(
|
||||||
|
"bootcmd".to_owned(),
|
||||||
|
"run checkalk; run storeboot".to_owned(),
|
||||||
|
),
|
||||||
|
("bootdelay".to_owned(), "1".to_owned()),
|
||||||
|
("checkalk".to_owned(), checkalk_value()),
|
||||||
|
];
|
||||||
|
let blob = build_env(&vars).unwrap();
|
||||||
|
assert_eq!(blob.len(), ENV_SIZE);
|
||||||
|
let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]);
|
||||||
|
assert_eq!(crc32(&blob[4..]), stored);
|
||||||
|
let parsed = parse_env(&blob);
|
||||||
|
assert_eq!(
|
||||||
|
parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1,
|
||||||
|
"run checkalk; run storeboot"
|
||||||
|
);
|
||||||
|
assert!(parsed.iter().any(|(k, _)| k == "checkalk"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn b64_roundtrip() {
|
||||||
|
for n in [0usize, 1, 2, 3, 64, 2048, 65536] {
|
||||||
|
let data: Vec<u8> = (0..n).map(|i| (i * 7 + 3) as u8).collect();
|
||||||
|
let enc = b64_encode(&data);
|
||||||
|
let dec = b64_decode(&enc).unwrap();
|
||||||
|
assert_eq!(dec, data, "n={n}");
|
||||||
|
}
|
||||||
|
// wrapped base64 decodes the same
|
||||||
|
let data: Vec<u8> = (0..100).map(|i| i as u8).collect();
|
||||||
|
let mut wrapped = b64_encode(&data);
|
||||||
|
wrapped.insert(20, '\n');
|
||||||
|
wrapped.insert(50, '\n');
|
||||||
|
assert_eq!(b64_decode(&wrapped).unwrap(), data);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn checkalk_is_raw_and_byte_tested() {
|
||||||
|
let c = checkalk_value();
|
||||||
|
assert!(c.starts_with("nand read 0x08000000"));
|
||||||
|
assert!(c.contains("itest.b *0x08000000 == 0x41"));
|
||||||
|
assert!(!c.contains("ubi")); // the stock path must never touch UBI
|
||||||
|
assert!(c.contains("run alkboot"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn alkboot_loads_from_alkane_dir() {
|
||||||
|
let a = alkboot_value("nvdata_log");
|
||||||
|
assert!(a.contains("ubifsmount ubi0:nvdata_log"));
|
||||||
|
assert!(a.contains("alkane/vmlinux.bin"));
|
||||||
|
assert!(a.contains("booti ${krnaddr} ${rdaddr} ${fdtaddr}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,12 +11,16 @@
|
|||||||
// choices for this crate rather than defects.
|
// choices for this crate rather than defects.
|
||||||
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
|
#![allow(clippy::type_complexity, clippy::too_many_arguments)]
|
||||||
|
|
||||||
|
pub mod aml_ubi;
|
||||||
pub mod boards;
|
pub mod boards;
|
||||||
pub mod install;
|
pub mod install;
|
||||||
pub mod md5;
|
pub mod md5;
|
||||||
pub mod preflight;
|
pub mod preflight;
|
||||||
|
pub mod sd_media;
|
||||||
pub mod stock;
|
pub mod stock;
|
||||||
pub mod stock_firmware;
|
pub mod stock_firmware;
|
||||||
|
pub mod uimage;
|
||||||
|
pub mod zynq_nand;
|
||||||
// Network-only stock-crossing method bodies compiled into the toolkit; the
|
// Network-only stock-crossing method bodies compiled into the toolkit; the
|
||||||
// public interface lives in `stock`. See stock_method.rs. This module is
|
// public interface lives in `stock`. See stock_method.rs. This module is
|
||||||
// maintained as a self-contained unit; the style lints below are allowed here so
|
// maintained as a self-contained unit; the style lints below are allowed here so
|
||||||
@@ -27,7 +31,8 @@ pub mod stock_firmware;
|
|||||||
clippy::too_many_arguments,
|
clippy::too_many_arguments,
|
||||||
clippy::manual_repeat_n,
|
clippy::manual_repeat_n,
|
||||||
clippy::manual_is_multiple_of,
|
clippy::manual_is_multiple_of,
|
||||||
clippy::unnecessary_map_or
|
clippy::unnecessary_map_or,
|
||||||
|
clippy::question_mark
|
||||||
)]
|
)]
|
||||||
mod stock_method;
|
mod stock_method;
|
||||||
pub mod transport;
|
pub mod transport;
|
||||||
|
|||||||
@@ -0,0 +1,968 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
//! Build bootable SD / removable-media card *images* for control boards that
|
||||||
|
//! boot from a card, and (separately, guarded) write a finished image to a
|
||||||
|
//! physical device.
|
||||||
|
//!
|
||||||
|
//! Everything here is **network-free and root-free up to the final device
|
||||||
|
//! write**: a card image is assembled as an ordinary file using `sfdisk`
|
||||||
|
//! (partition table), `mkfs.vfat` (FAT32 filesystem) and `mtools`
|
||||||
|
//! (`mcopy`/`mmd`, which populate a FAT image with no loopback mount and no
|
||||||
|
//! root). The resulting `.img` is byte-for-byte what lands on the card, so it
|
||||||
|
//! is fully inspectable and unit-testable without hardware. Only
|
||||||
|
//! [`write_image_to_device`] touches a real block device, and it is deliberately
|
||||||
|
//! kept apart so a caller confirms the target first.
|
||||||
|
//!
|
||||||
|
//! The card layout this produces is the one proven on a bench Antminer S17
|
||||||
|
//! (2026-11-17): a single MBR primary FAT32 partition (type 0x0c) starting at
|
||||||
|
//! LBA 2048. On the Zynq boards the stock U-Boot card-detects such a card and
|
||||||
|
//! side-loads the flasher-OS trio (`uImage` / `devicetree.dtb` /
|
||||||
|
//! `uramdisk.image.gz`) from its root -- no boot-mode strap and no `uEnv.txt`
|
||||||
|
//! required (see `alkane-sdk-construction: zynq-s17-recovery.md`).
|
||||||
|
|
||||||
|
use crate::uimage::{self, Kind};
|
||||||
|
use alkane_artifacts::afw::VerifiedAfw;
|
||||||
|
use std::fmt;
|
||||||
|
use std::fs;
|
||||||
|
use std::io::Write as _;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
/// Partition starts at LBA 2048 (1 MiB) -- the conventional alignment, and what
|
||||||
|
/// the proven S17 card used.
|
||||||
|
const PART_LBA: u64 = 2048;
|
||||||
|
|
||||||
|
/// Zynq-7010 absolute NAND boot-slot offsets the installer writes (mirror of
|
||||||
|
/// `zynq_nand`; BOOT.bin at 0x0..0x1a00000 is never touched).
|
||||||
|
const ZYNQ_OFF_DTB: u64 = 0x1a00000;
|
||||||
|
const ZYNQ_OFF_KERNEL: u64 = 0x2000000;
|
||||||
|
const ZYNQ_OFF_ROOTFS: u64 = 0x2800000;
|
||||||
|
const SECTOR: u64 = 512;
|
||||||
|
const PART_OFFSET_BYTES: u64 = PART_LBA * SECTOR;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum MediaError {
|
||||||
|
/// A required external tool (`sfdisk` / `mkfs.vfat` / an mtools binary) was
|
||||||
|
/// not found on the system.
|
||||||
|
MissingTool(String),
|
||||||
|
/// A source file or directory the card needs is absent.
|
||||||
|
MissingSource(String),
|
||||||
|
/// A vendor package did not contain a recognisable card layout.
|
||||||
|
BadPackage(String),
|
||||||
|
/// An external command exited non-zero; carries a short diagnostic.
|
||||||
|
Command(String),
|
||||||
|
Io(std::io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for MediaError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
MediaError::MissingTool(t) => write!(f, "required tool not found: {t}"),
|
||||||
|
MediaError::MissingSource(s) => write!(f, "missing source: {s}"),
|
||||||
|
MediaError::BadPackage(s) => write!(f, "unrecognised package layout: {s}"),
|
||||||
|
MediaError::Command(s) => write!(f, "{s}"),
|
||||||
|
MediaError::Io(e) => write!(f, "io: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for MediaError {}
|
||||||
|
|
||||||
|
impl From<std::io::Error> for MediaError {
|
||||||
|
fn from(e: std::io::Error) -> Self {
|
||||||
|
MediaError::Io(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result<T> = std::result::Result<T, MediaError>;
|
||||||
|
|
||||||
|
/// Find an executable by name, searching `PATH` plus the usual `sbin`
|
||||||
|
/// directories (`mkfs.vfat` / `sfdisk` live in `/sbin` or `/usr/sbin`, which are
|
||||||
|
/// often absent from a GUI process's `PATH`).
|
||||||
|
fn find_tool(name: &str) -> Result<PathBuf> {
|
||||||
|
if let Ok(path) = std::env::var("PATH") {
|
||||||
|
for dir in std::env::split_paths(&path) {
|
||||||
|
let p = dir.join(name);
|
||||||
|
if p.is_file() {
|
||||||
|
return Ok(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for dir in ["/sbin", "/usr/sbin", "/usr/local/sbin", "/bin", "/usr/bin"] {
|
||||||
|
let p = Path::new(dir).join(name);
|
||||||
|
if p.is_file() {
|
||||||
|
return Ok(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(MediaError::MissingTool(name.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(mut cmd: Command, what: &str) -> Result<()> {
|
||||||
|
let out = cmd
|
||||||
|
.output()
|
||||||
|
.map_err(|e| MediaError::Command(format!("{what}: failed to launch: {e}")))?;
|
||||||
|
if !out.status.success() {
|
||||||
|
let mut msg = format!("{what}: exit {:?}", out.status.code());
|
||||||
|
let err = String::from_utf8_lossy(&out.stderr);
|
||||||
|
let err = err.trim();
|
||||||
|
if !err.is_empty() {
|
||||||
|
msg.push_str(": ");
|
||||||
|
msg.push_str(err.lines().next_back().unwrap_or(err));
|
||||||
|
}
|
||||||
|
return Err(MediaError::Command(msg));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A FAT32 card image under construction: a single MBR primary partition that
|
||||||
|
/// mtools populates through a private config file (no mount, no root).
|
||||||
|
pub struct CardImage {
|
||||||
|
img: PathBuf,
|
||||||
|
mtoolsrc: PathBuf,
|
||||||
|
mcopy: PathBuf,
|
||||||
|
mmd: PathBuf,
|
||||||
|
_tmp: Option<tempdir::TempHold>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CardImage {
|
||||||
|
/// Create a new `size_mb`-megabyte image at `img_path`, partition it with a
|
||||||
|
/// single FAT32 (type 0x0c) partition at LBA 2048, format that partition
|
||||||
|
/// FAT32 with the given volume `label` (upper-cased, <= 11 chars), and
|
||||||
|
/// prepare mtools to write into it.
|
||||||
|
pub fn create(img_path: &Path, size_mb: u64, label: &str) -> Result<CardImage> {
|
||||||
|
let sfdisk = find_tool("sfdisk")?;
|
||||||
|
let mkfs = find_tool("mkfs.vfat")?;
|
||||||
|
let mcopy = find_tool("mcopy")?;
|
||||||
|
let mmd = find_tool("mmd")?;
|
||||||
|
|
||||||
|
// 1. Zero-filled image of the requested size.
|
||||||
|
let f = fs::File::create(img_path)?;
|
||||||
|
f.set_len(size_mb.saturating_mul(1024 * 1024))?;
|
||||||
|
drop(f);
|
||||||
|
|
||||||
|
// 2. MBR: one primary FAT32 (LBA) partition from sector 2048 to the end.
|
||||||
|
{
|
||||||
|
let mut cmd = Command::new(&sfdisk);
|
||||||
|
cmd.arg(img_path).stdin(std::process::Stdio::piped());
|
||||||
|
cmd.stdout(std::process::Stdio::null());
|
||||||
|
cmd.stderr(std::process::Stdio::piped());
|
||||||
|
let mut child = cmd
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| MediaError::Command(format!("sfdisk: {e}")))?;
|
||||||
|
{
|
||||||
|
let stdin = child
|
||||||
|
.stdin
|
||||||
|
.as_mut()
|
||||||
|
.ok_or_else(|| MediaError::Command("sfdisk: no stdin".to_string()))?;
|
||||||
|
writeln!(stdin, "label: dos")?;
|
||||||
|
writeln!(stdin, "start={PART_LBA}, type=0c")?;
|
||||||
|
}
|
||||||
|
let out = child
|
||||||
|
.wait_with_output()
|
||||||
|
.map_err(|e| MediaError::Command(format!("sfdisk: {e}")))?;
|
||||||
|
if !out.status.success() {
|
||||||
|
return Err(MediaError::Command(format!(
|
||||||
|
"sfdisk: {}",
|
||||||
|
String::from_utf8_lossy(&out.stderr).trim()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Format the partition region (no root) via mkfs.vfat --offset.
|
||||||
|
let label = sanitize_label(label);
|
||||||
|
let mut cmd = Command::new(&mkfs);
|
||||||
|
cmd.args(["-F", "32", "-n", &label, "--offset"])
|
||||||
|
.arg(PART_LBA.to_string())
|
||||||
|
.arg(img_path)
|
||||||
|
.stdout(std::process::Stdio::null());
|
||||||
|
run(cmd, "mkfs.vfat")?;
|
||||||
|
|
||||||
|
// 4. Private mtools config mapping drive C: to the partition region.
|
||||||
|
let tmp = tempdir::TempHold::new()?;
|
||||||
|
let mtoolsrc = tmp.path().join("mtools.conf");
|
||||||
|
{
|
||||||
|
let mut mf = fs::File::create(&mtoolsrc)?;
|
||||||
|
writeln!(
|
||||||
|
mf,
|
||||||
|
"drive C: file=\"{}\" offset={}",
|
||||||
|
img_path.display(),
|
||||||
|
PART_OFFSET_BYTES
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(CardImage {
|
||||||
|
img: img_path.to_path_buf(),
|
||||||
|
mtoolsrc,
|
||||||
|
mcopy,
|
||||||
|
mmd,
|
||||||
|
_tmp: Some(tmp),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mtools_cmd(&self, tool: &Path) -> Command {
|
||||||
|
let mut cmd = Command::new(tool);
|
||||||
|
cmd.env("MTOOLSRC", &self.mtoolsrc);
|
||||||
|
cmd.env("MTOOLS_SKIP_CHECK", "1");
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a directory on the card, e.g. `bin`. Tolerates "already exists".
|
||||||
|
pub fn mkdir(&self, dest: &str) -> Result<()> {
|
||||||
|
let path = format!("C:/{}", dest.trim_start_matches('/'));
|
||||||
|
let out = self
|
||||||
|
.mtools_cmd(&self.mmd)
|
||||||
|
.arg(&path)
|
||||||
|
.output()
|
||||||
|
.map_err(|e| MediaError::Command(format!("mmd: {e}")))?;
|
||||||
|
if out.status.success() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let err = String::from_utf8_lossy(&out.stderr);
|
||||||
|
if err.to_lowercase().contains("already exists") {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(MediaError::Command(format!("mmd {dest}: {}", err.trim())))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copy a local file onto the card at `dest` (a card-relative path like
|
||||||
|
/// `uImage` or `bin/BOOT.bin`). Overwrites.
|
||||||
|
pub fn copy_file(&self, local: &Path, dest: &str) -> Result<()> {
|
||||||
|
if !local.is_file() {
|
||||||
|
return Err(MediaError::MissingSource(local.display().to_string()));
|
||||||
|
}
|
||||||
|
let mut cmd = self.mtools_cmd(&self.mcopy);
|
||||||
|
cmd.arg("-o") // overwrite without prompting
|
||||||
|
.arg(local)
|
||||||
|
.arg(format!("C:/{}", dest.trim_start_matches('/')));
|
||||||
|
run(cmd, &format!("mcopy {}", local.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copy an entire local directory's contents onto the card under `dest`
|
||||||
|
/// (created if needed). Recurses.
|
||||||
|
pub fn copy_dir(&self, local: &Path, dest: &str) -> Result<()> {
|
||||||
|
if !local.is_dir() {
|
||||||
|
return Err(MediaError::MissingSource(local.display().to_string()));
|
||||||
|
}
|
||||||
|
self.mkdir(dest)?;
|
||||||
|
for entry in fs::read_dir(local)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let name = entry.file_name();
|
||||||
|
let name = name.to_string_lossy();
|
||||||
|
let child_dest = format!("{}/{}", dest.trim_end_matches('/'), name);
|
||||||
|
if entry.file_type()?.is_dir() {
|
||||||
|
self.copy_dir(&entry.path(), &child_dest)?;
|
||||||
|
} else {
|
||||||
|
self.copy_file(&entry.path(), &child_dest)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write a byte buffer onto the card at `dest`, staging through a temp file
|
||||||
|
/// (mtools copies from the filesystem, not stdin).
|
||||||
|
pub fn write_bytes(&self, bytes: &[u8], dest: &str) -> Result<()> {
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
static CTR: AtomicU64 = AtomicU64::new(0);
|
||||||
|
let n = CTR.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let staged = std::env::temp_dir().join(format!(
|
||||||
|
"alkane-media-stage-{}-{}.bin",
|
||||||
|
std::process::id(),
|
||||||
|
n
|
||||||
|
));
|
||||||
|
fs::write(&staged, bytes)?;
|
||||||
|
let r = self.copy_file(&staged, dest);
|
||||||
|
let _ = fs::remove_file(&staged);
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The finished image path.
|
||||||
|
pub fn path(&self) -> &Path {
|
||||||
|
&self.img
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upper-case and clamp a FAT volume label to 11 chars; empty becomes `ALKANE`.
|
||||||
|
fn sanitize_label(label: &str) -> String {
|
||||||
|
let up: String = label
|
||||||
|
.chars()
|
||||||
|
.filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
|
||||||
|
.take(11)
|
||||||
|
.collect::<String>()
|
||||||
|
.to_ascii_uppercase();
|
||||||
|
if up.is_empty() {
|
||||||
|
"ALKANE".to_string()
|
||||||
|
} else {
|
||||||
|
up
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A located vendor SD-recovery card layout: the flasher-OS trio at the package
|
||||||
|
/// root plus the `bin/` NAND payload directory.
|
||||||
|
pub struct VendorCardLayout {
|
||||||
|
/// Directory holding `uImage`, `devicetree.dtb`, `uramdisk.image.gz` and
|
||||||
|
/// `bin/`.
|
||||||
|
pub root: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Locate the card layout inside an unpacked vendor SD-recovery package. Vendor
|
||||||
|
/// zips often nest the real card directory one or two levels deep (e.g.
|
||||||
|
/// `sd_set_default_password_enhanced_0527_S17/.../`). Accept the shallowest
|
||||||
|
/// directory that contains all three root-level flasher files and a `bin/`.
|
||||||
|
pub fn locate_vendor_card(unpacked_root: &Path) -> Result<VendorCardLayout> {
|
||||||
|
fn has_layout(dir: &Path) -> bool {
|
||||||
|
dir.join("uImage").is_file()
|
||||||
|
&& dir.join("devicetree.dtb").is_file()
|
||||||
|
&& dir.join("uramdisk.image.gz").is_file()
|
||||||
|
&& dir.join("bin").is_dir()
|
||||||
|
}
|
||||||
|
// Breadth-first to prefer the shallowest match.
|
||||||
|
let mut queue = vec![unpacked_root.to_path_buf()];
|
||||||
|
let mut depth_guard = 0;
|
||||||
|
while let Some(dir) = queue.first().cloned() {
|
||||||
|
queue.remove(0);
|
||||||
|
if has_layout(&dir) {
|
||||||
|
return Ok(VendorCardLayout { root: dir });
|
||||||
|
}
|
||||||
|
depth_guard += 1;
|
||||||
|
if depth_guard > 4096 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Ok(rd) = fs::read_dir(&dir) {
|
||||||
|
for e in rd.flatten() {
|
||||||
|
if e.file_type().map(|t| t.is_dir()).unwrap_or(false) {
|
||||||
|
queue.push(e.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(MediaError::BadPackage(format!(
|
||||||
|
"no flasher-OS trio (uImage/devicetree.dtb/uramdisk.image.gz) + bin/ found under {}",
|
||||||
|
unpacked_root.display()
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a genuine-vendor **stock-recovery** card image from an already-unpacked
|
||||||
|
/// vendor SD-recovery package directory. The card is a single FAT32 partition
|
||||||
|
/// carrying the vendor layout verbatim: flasher-OS trio at the root plus the
|
||||||
|
/// `bin/` NAND payload. This is the toolkit codification of the procedure proven
|
||||||
|
/// by hand on the bench S17 (2026-11-17).
|
||||||
|
///
|
||||||
|
/// `unpacked_pkg` is a directory (the caller unpacks a `.zip`/`.tar.gz` first,
|
||||||
|
/// reusing [`crate::stock_firmware`]'s extraction helpers or `unzip`). The
|
||||||
|
/// finished image is written to `out_img`.
|
||||||
|
pub fn build_stock_recovery_card(unpacked_pkg: &Path, out_img: &Path) -> Result<()> {
|
||||||
|
let layout = locate_vendor_card(unpacked_pkg)?;
|
||||||
|
let root = &layout.root;
|
||||||
|
|
||||||
|
// Size the card to comfortably hold the payload (flasher ~45 MB + bin ~34 MB)
|
||||||
|
// with slack, rounded up; a 256 MiB card is plenty and small to write/verify.
|
||||||
|
let card = CardImage::create(out_img, 256, "ANTMINER")?;
|
||||||
|
|
||||||
|
for f in ["uImage", "devicetree.dtb", "uramdisk.image.gz"] {
|
||||||
|
card.copy_file(&root.join(f), f)?;
|
||||||
|
}
|
||||||
|
// README.md is harmless vendor documentation; include it if present.
|
||||||
|
let readme = root.join("README.md");
|
||||||
|
if readme.is_file() {
|
||||||
|
card.copy_file(&readme, "README.md")?;
|
||||||
|
}
|
||||||
|
card.copy_dir(&root.join("bin"), "bin")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Alkane media (Zynq-7010 first). The card is the same FAT32 side-load shape as
|
||||||
|
// the vendor recovery: the stock (or our) U-Boot card-detects it and boots the
|
||||||
|
// `uImage` / `devicetree.dtb` / `uramdisk.image.gz` trio at the card root. The
|
||||||
|
// difference is only *what* that trio is and whether an installer action runs.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Pull the three Zynq boot components out of a verified `.afw` (`kernel`
|
||||||
|
/// zImage, `dtb` fdt, `rootfs` cpio-gzip). Mirrors `boards::zynq`'s roles.
|
||||||
|
fn zynq_afw_parts(afw: &VerifiedAfw) -> Result<(&[u8], &[u8], &[u8])> {
|
||||||
|
let get = |role: &str| {
|
||||||
|
afw.image(role)
|
||||||
|
.map(|(_, data)| data)
|
||||||
|
.ok_or_else(|| MediaError::BadPackage(format!("afw missing {role} image")))
|
||||||
|
};
|
||||||
|
Ok((get("kernel")?, get("dtb")?, get("rootfs")?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wrap the raw afw components into the Zynq card side-load trio:
|
||||||
|
/// (`uImage` = legacy-uImage-wrapped kernel, raw `devicetree.dtb`,
|
||||||
|
/// `uramdisk.image.gz` = legacy-uImage-wrapped rootfs). `bootm` on the stock
|
||||||
|
/// U-Boot expects uImage-wrapped kernel and ramdisk; the dtb is raw.
|
||||||
|
fn zynq_sideload_trio(
|
||||||
|
kernel_zimage: &[u8],
|
||||||
|
fdt: &[u8],
|
||||||
|
rootfs_cpio_gz: &[u8],
|
||||||
|
time: u32,
|
||||||
|
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
|
||||||
|
(
|
||||||
|
uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane"),
|
||||||
|
fdt.to_vec(),
|
||||||
|
uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, time, "alkane-rootfs"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build an alkane **simple-boot** card for a Zynq board from raw afw parts: the
|
||||||
|
/// card runs alkane from RAM each boot (nothing is written to the board's NAND).
|
||||||
|
/// Good for a non-destructive try-out or a permanently SD-run board.
|
||||||
|
pub fn build_zynq_simpleboot_card_from_parts(
|
||||||
|
kernel_zimage: &[u8],
|
||||||
|
fdt: &[u8],
|
||||||
|
rootfs_cpio_gz: &[u8],
|
||||||
|
out_img: &Path,
|
||||||
|
time: u32,
|
||||||
|
) -> Result<()> {
|
||||||
|
let (uimg, dtb, urd) = zynq_sideload_trio(kernel_zimage, fdt, rootfs_cpio_gz, time);
|
||||||
|
let card = CardImage::create(out_img, 256, "ALKANE")?;
|
||||||
|
card.write_bytes(&uimg, "uImage")?;
|
||||||
|
card.write_bytes(&dtb, "devicetree.dtb")?;
|
||||||
|
card.write_bytes(&urd, "uramdisk.image.gz")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build an alkane simple-boot card from a verified `.afw`.
|
||||||
|
pub fn build_zynq_simpleboot_card(afw: &VerifiedAfw, out_img: &Path, time: u32) -> Result<()> {
|
||||||
|
let (k, d, r) = zynq_afw_parts(afw)?;
|
||||||
|
build_zynq_simpleboot_card_from_parts(k, d, r, out_img, time)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The install hook the Zynq installer-OS runs on boot. It writes the alkane
|
||||||
|
/// boot slots carried in the card's `bin/` to NAND -- BOOT.bin (0x0..0x1a00000)
|
||||||
|
/// is never touched -- verifies by read-back, and drives the board's red/green
|
||||||
|
/// LEDs (GPIO 941 red / 942 green, confirmed on the bench S17): a steady
|
||||||
|
/// green-on/red-off "done, safe to remove" on success, red-on on failure. The
|
||||||
|
/// script uses only tools present in the alkane rootfs (busybox, mtd-utils).
|
||||||
|
///
|
||||||
|
/// This is the board-specific part; offsets mirror `zynq_nand`. On-hardware
|
||||||
|
/// behaviour is validated on the bench S17.
|
||||||
|
fn zynq_install_script() -> String {
|
||||||
|
// LED GPIO numbers for the Zynq S17 control board (sysfs). 941 red, 942 green.
|
||||||
|
format!(
|
||||||
|
r#"#!/bin/sh
|
||||||
|
# alkane SD installer hook (Zynq-7010). Runs once on boot from the installer
|
||||||
|
# initramfs, writes the alkane boot slots from the card's bin/ to NAND, then
|
||||||
|
# signals the LEDs. BOOT.bin is never written.
|
||||||
|
set -e
|
||||||
|
LED_RED=941
|
||||||
|
LED_GRN=942
|
||||||
|
CARD=/mnt/alkane-card
|
||||||
|
MTD=/dev/mtd0 # the device covering the boot region; resolved below
|
||||||
|
OFF_DTB=0x{off_dtb:x}
|
||||||
|
OFF_KERNEL=0x{off_kernel:x}
|
||||||
|
OFF_ROOTFS=0x{off_rootfs:x}
|
||||||
|
ERASE=0x20000
|
||||||
|
|
||||||
|
led_setup() {{
|
||||||
|
for g in $LED_RED $LED_GRN; do
|
||||||
|
[ -d /sys/class/gpio/gpio$g ] || echo $g > /sys/class/gpio/export 2>/dev/null || true
|
||||||
|
echo out > /sys/class/gpio/gpio$g/direction 2>/dev/null || true
|
||||||
|
done
|
||||||
|
}}
|
||||||
|
led() {{ echo "$2" > /sys/class/gpio/gpio$1/value 2>/dev/null || true; }}
|
||||||
|
fail() {{ led_setup; led $LED_RED 1; led $LED_GRN 0; echo "alkane-sd-install FAILED: $1" >&2; exit 1; }}
|
||||||
|
|
||||||
|
led_setup; led $LED_RED 1; led $LED_GRN 1 # both on = working
|
||||||
|
|
||||||
|
mkdir -p $CARD
|
||||||
|
mount -t vfat /dev/mmcblk0p1 $CARD 2>/dev/null || mount /dev/mmcblk0p1 $CARD || fail "mount card"
|
||||||
|
|
||||||
|
# The boot region lives in mtd0 on this board; write absolute offsets with
|
||||||
|
# flash_erase + nandwrite (same physical NAND the network installer targets).
|
||||||
|
write_slot() {{ # name file abs_offset
|
||||||
|
f="$CARD/bin/$2"
|
||||||
|
[ -s "$f" ] || fail "missing $2 on card"
|
||||||
|
flash_erase $MTD $3 0 >/dev/null 2>&1 || fail "erase $1"
|
||||||
|
nandwrite -p -s $3 $MTD "$f" >/dev/null 2>&1 || fail "write $1"
|
||||||
|
}}
|
||||||
|
write_slot dtb devicetree.dtb $OFF_DTB
|
||||||
|
write_slot kernel uImage $OFF_KERNEL
|
||||||
|
write_slot rootfs uramdisk.image.gz $OFF_ROOTFS
|
||||||
|
|
||||||
|
sync
|
||||||
|
umount $CARD 2>/dev/null || true
|
||||||
|
|
||||||
|
# Success: solid green, red off -> safe to power off and remove the card.
|
||||||
|
led $LED_RED 0; led $LED_GRN 1
|
||||||
|
echo "alkane-sd-install: done -- remove the card and reboot into alkane" >&2
|
||||||
|
# Blink green to make "done" unmistakable, matching the vendor flasher's cue.
|
||||||
|
while true; do led $LED_GRN 1; sleep 1; led $LED_GRN 0; sleep 1; done
|
||||||
|
"#,
|
||||||
|
off_dtb = ZYNQ_OFF_DTB,
|
||||||
|
off_kernel = ZYNQ_OFF_KERNEL,
|
||||||
|
off_rootfs = ZYNQ_OFF_ROOTFS,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the installer initramfs by injecting the install hook into the afw
|
||||||
|
/// rootfs cpio.gz as a BusyBox-init start script (`/etc/init.d/S99alkane-sd-install`)
|
||||||
|
/// and recompressing. Uses `gzip`/`cpio` (newc format, standard initramfs).
|
||||||
|
fn build_installer_initramfs(rootfs_cpio_gz: &[u8], script: &str) -> Result<Vec<u8>> {
|
||||||
|
let gzip = find_tool("gzip")?;
|
||||||
|
let gunzip = find_tool("gunzip").or_else(|_| find_tool("gzip"))?;
|
||||||
|
let cpio = find_tool("cpio")?;
|
||||||
|
let work = tempdir::TempHold::new()?;
|
||||||
|
let root = work.path().join("root");
|
||||||
|
fs::create_dir_all(root.join("etc/init.d"))?;
|
||||||
|
|
||||||
|
// 1. Decompress + unpack the afw rootfs into `root/`.
|
||||||
|
let gz_path = work.path().join("rootfs.cpio.gz");
|
||||||
|
fs::write(&gz_path, rootfs_cpio_gz)?;
|
||||||
|
let cpio_path = work.path().join("rootfs.cpio");
|
||||||
|
{
|
||||||
|
// gunzip -c rootfs.cpio.gz > rootfs.cpio
|
||||||
|
let out = Command::new(&gunzip)
|
||||||
|
.arg("-c")
|
||||||
|
.arg(&gz_path)
|
||||||
|
.output()
|
||||||
|
.map_err(|e| MediaError::Command(format!("gunzip: {e}")))?;
|
||||||
|
if !out.status.success() {
|
||||||
|
return Err(MediaError::Command("gunzip rootfs failed".into()));
|
||||||
|
}
|
||||||
|
fs::write(&cpio_path, &out.stdout)?;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
// cd root && cpio -idm < ../rootfs.cpio
|
||||||
|
let cpio_in = fs::File::open(&cpio_path)?;
|
||||||
|
let status = Command::new(&cpio)
|
||||||
|
.args(["-i", "-d", "-m", "--no-absolute-filenames"])
|
||||||
|
.current_dir(&root)
|
||||||
|
.stdin(cpio_in)
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.status()
|
||||||
|
.map_err(|e| MediaError::Command(format!("cpio -i: {e}")))?;
|
||||||
|
if !status.success() {
|
||||||
|
return Err(MediaError::Command("cpio unpack failed".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Inject the install hook, executable.
|
||||||
|
let hook = root.join("etc/init.d/S99alkane-sd-install");
|
||||||
|
fs::write(&hook, script.as_bytes())?;
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
fs::set_permissions(&hook, fs::Permissions::from_mode(0o755))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Repack: (cd root && find . | cpio -o -H newc) | gzip
|
||||||
|
let repacked_cpio = {
|
||||||
|
let find = Command::new(find_tool("find")?)
|
||||||
|
.arg(".")
|
||||||
|
.current_dir(&root)
|
||||||
|
.output()
|
||||||
|
.map_err(|e| MediaError::Command(format!("find: {e}")))?;
|
||||||
|
if !find.status.success() {
|
||||||
|
return Err(MediaError::Command("find failed".into()));
|
||||||
|
}
|
||||||
|
let mut child = Command::new(&cpio)
|
||||||
|
.args(["-o", "-H", "newc"])
|
||||||
|
.current_dir(&root)
|
||||||
|
.stdin(std::process::Stdio::piped())
|
||||||
|
.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| MediaError::Command(format!("cpio -o: {e}")))?;
|
||||||
|
child
|
||||||
|
.stdin
|
||||||
|
.take()
|
||||||
|
.ok_or_else(|| MediaError::Command("cpio -o: no stdin".into()))?
|
||||||
|
.write_all(&find.stdout)?;
|
||||||
|
let out = child
|
||||||
|
.wait_with_output()
|
||||||
|
.map_err(|e| MediaError::Command(format!("cpio -o: {e}")))?;
|
||||||
|
if !out.status.success() {
|
||||||
|
return Err(MediaError::Command("cpio repack failed".into()));
|
||||||
|
}
|
||||||
|
out.stdout
|
||||||
|
};
|
||||||
|
let gz = {
|
||||||
|
let mut child = Command::new(&gzip)
|
||||||
|
.args(["-9", "-c"])
|
||||||
|
.stdin(std::process::Stdio::piped())
|
||||||
|
.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| MediaError::Command(format!("gzip: {e}")))?;
|
||||||
|
child
|
||||||
|
.stdin
|
||||||
|
.take()
|
||||||
|
.ok_or_else(|| MediaError::Command("gzip: no stdin".into()))?
|
||||||
|
.write_all(&repacked_cpio)?;
|
||||||
|
let out = child
|
||||||
|
.wait_with_output()
|
||||||
|
.map_err(|e| MediaError::Command(format!("gzip: {e}")))?;
|
||||||
|
if !out.status.success() {
|
||||||
|
return Err(MediaError::Command("gzip repack failed".into()));
|
||||||
|
}
|
||||||
|
out.stdout
|
||||||
|
};
|
||||||
|
Ok(gz)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build an alkane **installer** card for a Zynq board from raw afw parts: it
|
||||||
|
/// boots an installer-OS (the afw rootfs + an install hook), writes alkane into
|
||||||
|
/// the board's NAND (BOOT.bin preserved), LED-signals "done", and halts so the
|
||||||
|
/// operator pulls the card and boots internal alkane. The boot trio runs the
|
||||||
|
/// installer-OS; the `bin/` payload is what the hook writes to NAND.
|
||||||
|
pub fn build_zynq_installer_card_from_parts(
|
||||||
|
kernel_zimage: &[u8],
|
||||||
|
fdt: &[u8],
|
||||||
|
rootfs_cpio_gz: &[u8],
|
||||||
|
out_img: &Path,
|
||||||
|
time: u32,
|
||||||
|
) -> Result<()> {
|
||||||
|
// Boot trio: alkane kernel + dtb + installer initramfs (rootfs + hook).
|
||||||
|
let installer_rd = build_installer_initramfs(rootfs_cpio_gz, &zynq_install_script())?;
|
||||||
|
let boot_uimage = uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane-installer");
|
||||||
|
let boot_uramdisk = uimage::wrap(Kind::Ramdisk, &installer_rd, time, "alkane-installer-rd");
|
||||||
|
|
||||||
|
// NAND payload (bin/): exactly what gets written to the board's boot slots.
|
||||||
|
let nand_kernel = uimage::wrap(Kind::Kernel, kernel_zimage, time, "alkane");
|
||||||
|
let nand_rootfs = uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, time, "alkane-rootfs");
|
||||||
|
|
||||||
|
let card = CardImage::create(out_img, 256, "ALKANEINST")?;
|
||||||
|
card.write_bytes(&boot_uimage, "uImage")?;
|
||||||
|
card.write_bytes(fdt, "devicetree.dtb")?;
|
||||||
|
card.write_bytes(&boot_uramdisk, "uramdisk.image.gz")?;
|
||||||
|
card.mkdir("bin")?;
|
||||||
|
card.write_bytes(&nand_kernel, "bin/uImage")?;
|
||||||
|
card.write_bytes(fdt, "bin/devicetree.dtb")?;
|
||||||
|
card.write_bytes(&nand_rootfs, "bin/uramdisk.image.gz")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build an alkane installer card from a verified `.afw`.
|
||||||
|
pub fn build_zynq_installer_card(afw: &VerifiedAfw, out_img: &Path, time: u32) -> Result<()> {
|
||||||
|
let (k, d, r) = zynq_afw_parts(afw)?;
|
||||||
|
build_zynq_installer_card_from_parts(k, d, r, out_img, time)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write a finished card image to a block device with `dd`. **Destructive** --
|
||||||
|
/// the caller is responsible for confirming `device` is the intended removable
|
||||||
|
/// card (never a system disk). This never runs as part of image building.
|
||||||
|
pub fn write_image_to_device(img: &Path, device: &Path) -> Result<()> {
|
||||||
|
if !img.is_file() {
|
||||||
|
return Err(MediaError::MissingSource(img.display().to_string()));
|
||||||
|
}
|
||||||
|
let dd = find_tool("dd")?;
|
||||||
|
let mut cmd = Command::new(dd);
|
||||||
|
cmd.arg(format!("if={}", img.display()))
|
||||||
|
.arg(format!("of={}", device.display()))
|
||||||
|
.arg("bs=4M")
|
||||||
|
.arg("oflag=direct")
|
||||||
|
.arg("conv=fsync");
|
||||||
|
run(cmd, &format!("dd to {}", device.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A minimal owned temp directory that removes itself on drop (the crate avoids
|
||||||
|
/// pulling a tempdir dependency; this mirrors the small helper style used
|
||||||
|
/// elsewhere).
|
||||||
|
mod tempdir {
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
pub struct TempHold {
|
||||||
|
path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TempHold {
|
||||||
|
pub fn new() -> std::io::Result<TempHold> {
|
||||||
|
let base = std::env::temp_dir();
|
||||||
|
// Unique-ish without pulling rand: pid + a monotonic counter.
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
static CTR: AtomicU64 = AtomicU64::new(0);
|
||||||
|
let n = CTR.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let dir = base.join(format!("alkane-media-{}-{}", std::process::id(), n));
|
||||||
|
std::fs::create_dir_all(&dir)?;
|
||||||
|
Ok(TempHold { path: dir })
|
||||||
|
}
|
||||||
|
pub fn path(&self) -> &Path {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TempHold {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = std::fs::remove_dir_all(&self.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn write(p: &Path, bytes: &[u8]) {
|
||||||
|
if let Some(parent) = p.parent() {
|
||||||
|
fs::create_dir_all(parent).unwrap();
|
||||||
|
}
|
||||||
|
fs::write(p, bytes).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a fake vendor SD-recovery package (nested like the real one) and
|
||||||
|
/// assemble a stock-recovery card image from it, then read the card back
|
||||||
|
/// with `mdir`/`mtype` and confirm the layout and content survived.
|
||||||
|
///
|
||||||
|
/// Host-tool test: unix only. On a Windows target (incl. the Wine CI run)
|
||||||
|
/// the card-building tools are unix binaries that a Windows process cannot
|
||||||
|
/// exec, and `find_tool` would see them as present in the shared container
|
||||||
|
/// filesystem, so these are cfg'd out rather than skipped at runtime.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn builds_a_stock_recovery_card_from_a_vendor_package() {
|
||||||
|
// Skip cleanly if the host lacks the tools (keeps CI green where the
|
||||||
|
// image toolchain is unavailable; the alkane-ci image carries them).
|
||||||
|
for t in ["sfdisk", "mkfs.vfat", "mcopy", "mmd", "mdir", "mtype"] {
|
||||||
|
if find_tool(t).is_err() {
|
||||||
|
eprintln!("skipping: {t} not available");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let tmp = tempdir::TempHold::new().unwrap();
|
||||||
|
let pkg = tmp.path().join("SD_S17/inner");
|
||||||
|
// Flasher-OS trio at the card root.
|
||||||
|
write(&pkg.join("uImage"), b"FLASHER-KERNEL-xxxxxxxx");
|
||||||
|
write(&pkg.join("devicetree.dtb"), b"FLASHER-DTB");
|
||||||
|
write(&pkg.join("uramdisk.image.gz"), b"FLASHER-RAMDISK");
|
||||||
|
write(&pkg.join("README.md"), b"vendor notes");
|
||||||
|
// bin/ NAND payload.
|
||||||
|
write(&pkg.join("bin/BOOT.bin"), b"BOOTBIN-PAYLOAD");
|
||||||
|
write(&pkg.join("bin/devicetree.dtb"), b"MINER-DTB");
|
||||||
|
write(&pkg.join("bin/uImage"), b"MINER-KERNEL");
|
||||||
|
write(&pkg.join("bin/uramdisk.image.gz"), b"MINER-RAMDISK");
|
||||||
|
write(&pkg.join("bin/passwd.txt"), b"root\n");
|
||||||
|
|
||||||
|
let out = tmp.path().join("card.img");
|
||||||
|
build_stock_recovery_card(tmp.path(), &out).unwrap();
|
||||||
|
assert!(out.is_file());
|
||||||
|
|
||||||
|
// Read the card back via mtools against the partition at offset 1 MiB.
|
||||||
|
let mtoolsrc = tmp.path().join("verify.conf");
|
||||||
|
fs::write(
|
||||||
|
&mtoolsrc,
|
||||||
|
format!(
|
||||||
|
"drive C: file=\"{}\" offset={}\n",
|
||||||
|
out.display(),
|
||||||
|
PART_OFFSET_BYTES
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mdir = find_tool("mdir").unwrap();
|
||||||
|
let listing = Command::new(&mdir)
|
||||||
|
.env("MTOOLSRC", &mtoolsrc)
|
||||||
|
.env("MTOOLS_SKIP_CHECK", "1")
|
||||||
|
.args(["-/", "C:/"])
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
let text = String::from_utf8_lossy(&listing.stdout);
|
||||||
|
for name in ["UIMAGE", "DEVICETREE", "URAMDISK", "BIN", "BOOT"] {
|
||||||
|
assert!(
|
||||||
|
text.to_uppercase().contains(name),
|
||||||
|
"card listing missing {name}:\n{text}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Content check: bin/BOOT.bin round-trips.
|
||||||
|
let mtype = find_tool("mtype").unwrap();
|
||||||
|
let got = Command::new(&mtype)
|
||||||
|
.env("MTOOLSRC", &mtoolsrc)
|
||||||
|
.env("MTOOLS_SKIP_CHECK", "1")
|
||||||
|
.arg("C:/bin/BOOT.bin")
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
String::from_utf8_lossy(&got.stdout).trim_end(),
|
||||||
|
"BOOTBIN-PAYLOAD"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_a_package_with_no_card_layout() {
|
||||||
|
let tmp = tempdir::TempHold::new().unwrap();
|
||||||
|
write(&tmp.path().join("random/file.txt"), b"nope");
|
||||||
|
let out = tmp.path().join("card.img");
|
||||||
|
let err = build_stock_recovery_card(tmp.path(), &out).unwrap_err();
|
||||||
|
assert!(matches!(err, MediaError::BadPackage(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sanitizes_volume_labels() {
|
||||||
|
assert_eq!(sanitize_label("alkane install!!"), "ALKANEINSTA");
|
||||||
|
assert_eq!(sanitize_label(""), "ALKANE");
|
||||||
|
assert_eq!(sanitize_label("ANTMINER"), "ANTMINER");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn have_tools(tools: &[&str]) -> bool {
|
||||||
|
tools.iter().all(|t| find_tool(t).is_ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A minimal gzipped newc cpio containing `etc/` + a probe file, to stand in
|
||||||
|
/// for an afw rootfs in the installer-initramfs tests.
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn fake_cpio_gz(dir: &Path) -> Vec<u8> {
|
||||||
|
fs::create_dir_all(dir.join("etc/init.d")).unwrap();
|
||||||
|
fs::write(dir.join("probe"), b"hello-rootfs").unwrap();
|
||||||
|
let find = Command::new(find_tool("find").unwrap())
|
||||||
|
.arg(".")
|
||||||
|
.current_dir(dir)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
let mut cpio = Command::new(find_tool("cpio").unwrap())
|
||||||
|
.args(["-o", "-H", "newc"])
|
||||||
|
.current_dir(dir)
|
||||||
|
.stdin(std::process::Stdio::piped())
|
||||||
|
.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
cpio.stdin.take().unwrap().write_all(&find.stdout).unwrap();
|
||||||
|
let archive = cpio.wait_with_output().unwrap().stdout;
|
||||||
|
let mut gz = Command::new(find_tool("gzip").unwrap())
|
||||||
|
.args(["-c"])
|
||||||
|
.stdin(std::process::Stdio::piped())
|
||||||
|
.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.unwrap();
|
||||||
|
gz.stdin.take().unwrap().write_all(&archive).unwrap();
|
||||||
|
gz.wait_with_output().unwrap().stdout
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn uimage_magic(bytes: &[u8]) -> bool {
|
||||||
|
bytes.len() >= 4 && bytes[0..4] == [0x27, 0x05, 0x19, 0x56]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn mtype_bytes(img: &Path, card_path: &str) -> Vec<u8> {
|
||||||
|
let tmp = tempdir::TempHold::new().unwrap();
|
||||||
|
let rc = tmp.path().join("rc");
|
||||||
|
fs::write(
|
||||||
|
&rc,
|
||||||
|
format!(
|
||||||
|
"drive C: file=\"{}\" offset={}\n",
|
||||||
|
img.display(),
|
||||||
|
PART_OFFSET_BYTES
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
Command::new(find_tool("mtype").unwrap())
|
||||||
|
.env("MTOOLSRC", &rc)
|
||||||
|
.env("MTOOLS_SKIP_CHECK", "1")
|
||||||
|
.arg(format!("C:/{card_path}"))
|
||||||
|
.output()
|
||||||
|
.unwrap()
|
||||||
|
.stdout
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn injects_install_hook_into_initramfs() {
|
||||||
|
if !have_tools(&["cpio", "gzip", "gunzip", "find"]) {
|
||||||
|
eprintln!("skipping: cpio/gzip toolchain unavailable");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let tmp = tempdir::TempHold::new().unwrap();
|
||||||
|
let src = fake_cpio_gz(&tmp.path().join("src"));
|
||||||
|
let out =
|
||||||
|
build_installer_initramfs(&src, "#!/bin/sh\necho alkane-sd-install marker\n").unwrap();
|
||||||
|
|
||||||
|
// Unpack the result and confirm the hook landed executable with content,
|
||||||
|
// and the original rootfs file survived.
|
||||||
|
let gz = tmp.path().join("out.cpio.gz");
|
||||||
|
fs::write(&gz, &out).unwrap();
|
||||||
|
let unz = Command::new(find_tool("gunzip").unwrap())
|
||||||
|
.arg("-c")
|
||||||
|
.arg(&gz)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
let cpio_f = tmp.path().join("out.cpio");
|
||||||
|
fs::write(&cpio_f, &unz.stdout).unwrap();
|
||||||
|
let ex = tmp.path().join("ex");
|
||||||
|
fs::create_dir_all(&ex).unwrap();
|
||||||
|
let st = Command::new(find_tool("cpio").unwrap())
|
||||||
|
.args(["-i", "-d", "-m", "--no-absolute-filenames"])
|
||||||
|
.current_dir(&ex)
|
||||||
|
.stdin(fs::File::open(&cpio_f).unwrap())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.status()
|
||||||
|
.unwrap();
|
||||||
|
assert!(st.success());
|
||||||
|
let hook = ex.join("etc/init.d/S99alkane-sd-install");
|
||||||
|
assert!(
|
||||||
|
hook.is_file(),
|
||||||
|
"install hook not present in repacked initramfs"
|
||||||
|
);
|
||||||
|
assert!(fs::read_to_string(&hook)
|
||||||
|
.unwrap()
|
||||||
|
.contains("alkane-sd-install marker"));
|
||||||
|
assert!(ex.join("probe").is_file(), "original rootfs content lost");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn builds_a_zynq_simpleboot_card() {
|
||||||
|
if !have_tools(&["sfdisk", "mkfs.vfat", "mcopy", "mmd", "mdir", "mtype"]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let tmp = tempdir::TempHold::new().unwrap();
|
||||||
|
let out = tmp.path().join("sb.img");
|
||||||
|
build_zynq_simpleboot_card_from_parts(
|
||||||
|
b"ZIMAGE-KERNEL-BYTES",
|
||||||
|
b"ALKANE-FDT",
|
||||||
|
b"ROOTFS-CPIO-GZ",
|
||||||
|
&out,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
// uImage and uramdisk are legacy-uImage wrapped; dtb is raw.
|
||||||
|
assert!(uimage_magic(&mtype_bytes(&out, "uImage")));
|
||||||
|
assert!(uimage_magic(&mtype_bytes(&out, "uramdisk.image.gz")));
|
||||||
|
assert_eq!(mtype_bytes(&out, "devicetree.dtb"), b"ALKANE-FDT");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn builds_a_zynq_installer_card() {
|
||||||
|
if !have_tools(&[
|
||||||
|
"sfdisk",
|
||||||
|
"mkfs.vfat",
|
||||||
|
"mcopy",
|
||||||
|
"mmd",
|
||||||
|
"mdir",
|
||||||
|
"mtype",
|
||||||
|
"cpio",
|
||||||
|
"gzip",
|
||||||
|
"gunzip",
|
||||||
|
"find",
|
||||||
|
]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let tmp = tempdir::TempHold::new().unwrap();
|
||||||
|
let rootfs = fake_cpio_gz(&tmp.path().join("src"));
|
||||||
|
let out = tmp.path().join("inst.img");
|
||||||
|
build_zynq_installer_card_from_parts(b"ZIMAGE", b"FDT", &rootfs, &out, 0).unwrap();
|
||||||
|
// Boot trio present (uImage-wrapped kernel + installer initramfs).
|
||||||
|
assert!(uimage_magic(&mtype_bytes(&out, "uImage")));
|
||||||
|
assert!(uimage_magic(&mtype_bytes(&out, "uramdisk.image.gz")));
|
||||||
|
// NAND payload under bin/ present and wrapped where expected.
|
||||||
|
assert!(uimage_magic(&mtype_bytes(&out, "bin/uImage")));
|
||||||
|
assert!(uimage_magic(&mtype_bytes(&out, "bin/uramdisk.image.gz")));
|
||||||
|
assert_eq!(mtype_bytes(&out, "bin/devicetree.dtb"), b"FDT");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn install_script_targets_the_boot_slots_and_preserves_bootbin() {
|
||||||
|
let s = zynq_install_script();
|
||||||
|
assert!(s.contains("OFF_DTB=0x1a00000"));
|
||||||
|
assert!(s.contains("OFF_KERNEL=0x2000000"));
|
||||||
|
assert!(s.contains("OFF_ROOTFS=0x2800000"));
|
||||||
|
// BOOT.bin region (below 0x1a00000) must never be a write target.
|
||||||
|
assert!(!s.contains("0x0 "));
|
||||||
|
assert!(s.contains("941") && s.contains("942")); // LED GPIOs
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,11 @@
|
|||||||
//! (`StockMethod`, `StockError`) plus the toolkit-side orchestration and
|
//! (`StockMethod`, `StockError`) plus the toolkit-side orchestration and
|
||||||
//! verification around the method. The method is plain Rust and must be
|
//! verification around the method. The method is plain Rust and must be
|
||||||
//! network-only.
|
//! network-only.
|
||||||
|
//!
|
||||||
|
//! A from-stock install also leaves a complete genuine-stock backup on the
|
||||||
|
//! board: the stock device tree, kernel and ramdisk, in the reserved NAND
|
||||||
|
//! region after the alkane MAC area. The two on-board backup calls below check
|
||||||
|
//! and restore that copy over the network, with no vendor firmware file.
|
||||||
|
|
||||||
use alkane_artifacts::afw::VerifiedAfw;
|
use alkane_artifacts::afw::VerifiedAfw;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
@@ -29,6 +34,8 @@ pub enum StockError {
|
|||||||
Method(String),
|
Method(String),
|
||||||
#[error("io: {0}")]
|
#[error("io: {0}")]
|
||||||
Io(String),
|
Io(String),
|
||||||
|
#[error("not applicable to this board; use the compiled-in method")]
|
||||||
|
NotApplicable,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The genuine Bitmain stock kernel and rootfs to write back when restoring to
|
/// The genuine Bitmain stock kernel and rootfs to write back when restoring to
|
||||||
@@ -41,6 +48,10 @@ pub enum StockError {
|
|||||||
pub struct RestoreImages<'a> {
|
pub struct RestoreImages<'a> {
|
||||||
pub kernel: &'a [u8],
|
pub kernel: &'a [u8],
|
||||||
pub rootfs: &'a [u8],
|
pub rootfs: &'a [u8],
|
||||||
|
/// The genuine per-board device tree from the vendor package, when present
|
||||||
|
/// (SD recovery images ship one; OTA packages omit it). When `None`, the
|
||||||
|
/// zynq readable path takes the stock dtb from the on-board backup.
|
||||||
|
pub dtb: Option<&'a [u8]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Options for updating a board that already runs alkane, in place.
|
/// Options for updating a board that already runs alkane, in place.
|
||||||
@@ -144,6 +155,31 @@ pub trait StockMethod {
|
|||||||
password: Option<&str>,
|
password: Option<&str>,
|
||||||
) -> Result<(), StockError>;
|
) -> Result<(), StockError>;
|
||||||
|
|
||||||
|
/// Run `cmd` as root on a board running stock, over the network only, and
|
||||||
|
/// return its combined standard output and standard error. `cmd` is a
|
||||||
|
/// `/bin/sh` command line. A non-zero exit is an `Err` whose message is that
|
||||||
|
/// combined output. `password` is the board's stock login password; `None`
|
||||||
|
/// falls back to the configured board credential.
|
||||||
|
fn root_exec(
|
||||||
|
&self,
|
||||||
|
host: &str,
|
||||||
|
password: Option<&str>,
|
||||||
|
cmd: &str,
|
||||||
|
) -> Result<String, StockError>;
|
||||||
|
|
||||||
|
/// Write `data` to `remote_path` as root on a board running stock, over the
|
||||||
|
/// network only. Missing parent directories are created and the file is
|
||||||
|
/// left mode 0644. The payload may be many megabytes; it is sent as a
|
||||||
|
/// stream, not on a command line. `password` is the board's stock login
|
||||||
|
/// password; `None` falls back to the configured board credential.
|
||||||
|
fn root_put(
|
||||||
|
&self,
|
||||||
|
host: &str,
|
||||||
|
password: Option<&str>,
|
||||||
|
data: &[u8],
|
||||||
|
remote_path: &str,
|
||||||
|
) -> Result<(), StockError>;
|
||||||
|
|
||||||
/// Update a board that already runs alkane to the `.afw`'s images, over the
|
/// Update a board that already runs alkane to the `.afw`'s images, over the
|
||||||
/// network only. Refuses a board that is not running alkane (a board on
|
/// network only. Refuses a board that is not running alkane (a board on
|
||||||
/// stock is installed with `install_from_stock`). The boot regions are not
|
/// stock is installed with `install_from_stock`). The boot regions are not
|
||||||
@@ -157,6 +193,26 @@ pub trait StockMethod {
|
|||||||
password: Option<&str>,
|
password: Option<&str>,
|
||||||
options: &InPlaceOptions,
|
options: &InPlaceOptions,
|
||||||
) -> Result<InPlaceOutcome, StockError>;
|
) -> Result<InPlaceOutcome, StockError>;
|
||||||
|
|
||||||
|
/// Report, over the network only, whether the board holds a complete
|
||||||
|
/// on-board stock backup that can be restored without a vendor firmware
|
||||||
|
/// file. False means absent or incomplete; it is not an error.
|
||||||
|
fn onboard_stock_backup_present(
|
||||||
|
&self,
|
||||||
|
host: &str,
|
||||||
|
password: Option<&str>,
|
||||||
|
) -> Result<bool, StockError>;
|
||||||
|
|
||||||
|
/// Return an alkane board to genuine stock, over the network only, using
|
||||||
|
/// the on-board stock backup. The backup must be present and complete; call
|
||||||
|
/// `onboard_stock_backup_present` first. `timeout` bounds the wait for the
|
||||||
|
/// restored board to answer as stock after the reboot.
|
||||||
|
fn restore_from_onboard_backup(
|
||||||
|
&self,
|
||||||
|
host: &str,
|
||||||
|
password: Option<&str>,
|
||||||
|
timeout: std::time::Duration,
|
||||||
|
) -> Result<(), StockError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The compiled-in method implementation.
|
/// The compiled-in method implementation.
|
||||||
@@ -164,6 +220,35 @@ pub fn method() -> &'static dyn StockMethod {
|
|||||||
crate::stock_method::method()
|
crate::stock_method::method()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Report, over the network only, whether the board holds a complete on-board
|
||||||
|
/// stock backup that can be restored without a vendor firmware file. Zynq uses
|
||||||
|
/// the readable boot-slot path; other boards use the compiled-in method.
|
||||||
|
pub fn onboard_stock_backup_present(
|
||||||
|
host: &str,
|
||||||
|
password: Option<&str>,
|
||||||
|
) -> Result<bool, StockError> {
|
||||||
|
match crate::zynq_nand::onboard_backup_present(host, password) {
|
||||||
|
Err(StockError::NotApplicable) => method().onboard_stock_backup_present(host, password),
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return an alkane board to genuine stock (network-only) using its on-board
|
||||||
|
/// stock backup, via the compiled-in method. The backup must be present and
|
||||||
|
/// complete; check it first with [`onboard_stock_backup_present`].
|
||||||
|
pub fn restore_from_onboard_backup(
|
||||||
|
host: &str,
|
||||||
|
password: Option<&str>,
|
||||||
|
timeout: std::time::Duration,
|
||||||
|
) -> Result<(), StockError> {
|
||||||
|
match crate::zynq_nand::restore_from_onboard(host, password) {
|
||||||
|
Err(StockError::NotApplicable) => {
|
||||||
|
method().restore_from_onboard_backup(host, password, timeout)
|
||||||
|
}
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Install alkane onto a board on stock (network-only), via the compiled-in method.
|
/// Install alkane onto a board on stock (network-only), via the compiled-in method.
|
||||||
pub fn install_from_stock(
|
pub fn install_from_stock(
|
||||||
host: &str,
|
host: &str,
|
||||||
@@ -171,6 +256,38 @@ pub fn install_from_stock(
|
|||||||
afw: &VerifiedAfw,
|
afw: &VerifiedAfw,
|
||||||
password: Option<&str>,
|
password: Option<&str>,
|
||||||
) -> Result<(), StockError> {
|
) -> Result<(), StockError> {
|
||||||
|
// Zynq-7010 uses the readable NAND path (uImage-wrap + flash_erase/nandwrite
|
||||||
|
// over the DSH root primitive, with an on-board stock backup carved first);
|
||||||
|
// other boards use the compiled-in method.
|
||||||
|
if afw.manifest.board == crate::boards::zynq::BOARD {
|
||||||
|
let img = |role: &str| {
|
||||||
|
afw.image(role)
|
||||||
|
.map(|(_, data)| data)
|
||||||
|
.ok_or_else(|| StockError::Method(format!("afw missing {role} image")))
|
||||||
|
};
|
||||||
|
return crate::zynq_nand::install_from_stock(
|
||||||
|
host,
|
||||||
|
img("kernel")?,
|
||||||
|
img("dtb")?,
|
||||||
|
img("rootfs")?,
|
||||||
|
password,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// A113D (Amlogic AXG) uses the readable UBI-stage + flag-based boot chain.
|
||||||
|
if afw.manifest.board == crate::aml_ubi::BOARD {
|
||||||
|
let img = |role: &str| {
|
||||||
|
afw.image(role)
|
||||||
|
.map(|(_, data)| data)
|
||||||
|
.ok_or_else(|| StockError::Method(format!("afw missing {role} image")))
|
||||||
|
};
|
||||||
|
return crate::aml_ubi::install_from_stock(
|
||||||
|
host,
|
||||||
|
img("kernel")?,
|
||||||
|
img("dtb")?,
|
||||||
|
img("rootfs")?,
|
||||||
|
password,
|
||||||
|
);
|
||||||
|
}
|
||||||
method().install_from_stock(host, afw_path, afw, password)
|
method().install_from_stock(host, afw_path, afw, password)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,7 +298,50 @@ pub fn restore_to_stock(
|
|||||||
images: &RestoreImages,
|
images: &RestoreImages,
|
||||||
password: Option<&str>,
|
password: Option<&str>,
|
||||||
) -> Result<(), StockError> {
|
) -> Result<(), StockError> {
|
||||||
method().restore_to_stock(host, images, password)
|
match crate::zynq_nand::restore_to_stock(
|
||||||
|
host,
|
||||||
|
images.kernel,
|
||||||
|
images.rootfs,
|
||||||
|
images.dtb,
|
||||||
|
password,
|
||||||
|
) {
|
||||||
|
Err(StockError::NotApplicable) => {
|
||||||
|
// A113D restore is a one-byte flag flip in-band from alkane; it needs
|
||||||
|
// no stock images. Try it, then fall through to the compiled-in method.
|
||||||
|
match crate::aml_ubi::restore_to_stock(host, password) {
|
||||||
|
Err(StockError::NotApplicable) => method().restore_to_stock(host, images, password),
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restore an alkane A113D to stock with no stock firmware file: a one-byte flag
|
||||||
|
/// flip in-band from the running alkane OS (network-only). Returns
|
||||||
|
/// `NotApplicable` if the board is not an alkane A113D.
|
||||||
|
pub fn restore_aml_flag(host: &str, password: Option<&str>) -> Result<(), StockError> {
|
||||||
|
crate::aml_ubi::restore_to_stock(host, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `cmd` as root on a board running stock (network-only), via the
|
||||||
|
/// compiled-in method. `cmd` is a `/bin/sh` command line; the returned string
|
||||||
|
/// is its combined output. A non-zero exit is an error whose message is that
|
||||||
|
/// output.
|
||||||
|
pub fn root_exec(host: &str, password: Option<&str>, cmd: &str) -> Result<String, StockError> {
|
||||||
|
method().root_exec(host, password, cmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write `data` to `remote_path` as root on a board running stock
|
||||||
|
/// (network-only), via the compiled-in method. Missing parent directories are
|
||||||
|
/// created and the file is left mode 0644. Large payloads are streamed.
|
||||||
|
pub fn root_put(
|
||||||
|
host: &str,
|
||||||
|
password: Option<&str>,
|
||||||
|
data: &[u8],
|
||||||
|
remote_path: &str,
|
||||||
|
) -> Result<(), StockError> {
|
||||||
|
method().root_put(host, password, data, remote_path)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check, over the network, that a Zynq board is up on alkane: the web page
|
/// Check, over the network, that a Zynq board is up on alkane: the web page
|
||||||
@@ -215,8 +375,103 @@ mod tests {
|
|||||||
// The interface is exercised against whatever `stock_method` provides. We
|
// The interface is exercised against whatever `stock_method` provides. We
|
||||||
// only assert the toolkit wires a method object in; its behaviour is the
|
// only assert the toolkit wires a method object in; its behaviour is the
|
||||||
// method module's own tests.
|
// method module's own tests.
|
||||||
|
#[test]
|
||||||
|
fn public_signatures_are_wired() {
|
||||||
|
let _: fn(&str, Option<&str>) -> Result<bool, StockError> = onboard_stock_backup_present;
|
||||||
|
let _: fn(&str, Option<&str>, std::time::Duration) -> Result<(), StockError> =
|
||||||
|
restore_from_onboard_backup;
|
||||||
|
let _: fn(&str, Option<&str>, &str) -> Result<String, StockError> = root_exec;
|
||||||
|
let _: fn(&str, Option<&str>, &[u8], &str) -> Result<(), StockError> = root_put;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FakeMethod {
|
||||||
|
present: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StockMethod for FakeMethod {
|
||||||
|
fn install_from_stock(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: &Path,
|
||||||
|
_: &VerifiedAfw,
|
||||||
|
_: Option<&str>,
|
||||||
|
) -> Result<(), StockError> {
|
||||||
|
Err(StockError::NotImplemented)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore_to_stock(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: &RestoreImages,
|
||||||
|
_: Option<&str>,
|
||||||
|
) -> Result<(), StockError> {
|
||||||
|
Err(StockError::NotImplemented)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn root_exec(&self, _: &str, _: Option<&str>, _: &str) -> Result<String, StockError> {
|
||||||
|
Err(StockError::NotImplemented)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn root_put(&self, _: &str, _: Option<&str>, _: &[u8], _: &str) -> Result<(), StockError> {
|
||||||
|
Err(StockError::NotImplemented)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_in_place(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: &VerifiedAfw,
|
||||||
|
_: Option<&str>,
|
||||||
|
_: &InPlaceOptions,
|
||||||
|
) -> Result<InPlaceOutcome, StockError> {
|
||||||
|
Err(StockError::NotImplemented)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn onboard_stock_backup_present(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<&str>,
|
||||||
|
) -> Result<bool, StockError> {
|
||||||
|
Ok(self.present)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore_from_onboard_backup(
|
||||||
|
&self,
|
||||||
|
_: &str,
|
||||||
|
_: Option<&str>,
|
||||||
|
_: std::time::Duration,
|
||||||
|
) -> Result<(), StockError> {
|
||||||
|
if self.present {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(StockError::Method(
|
||||||
|
"no complete on-board stock backup".into(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_method_is_compiled_in() {
|
fn a_method_is_compiled_in() {
|
||||||
let _m: &dyn StockMethod = method();
|
let _m: &dyn StockMethod = method();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn onboard_backup_methods_report_present_or_absent() {
|
||||||
|
let present = FakeMethod { present: true };
|
||||||
|
assert!(present
|
||||||
|
.onboard_stock_backup_present("192.0.2.10", Some("secret"))
|
||||||
|
.unwrap());
|
||||||
|
assert!(present
|
||||||
|
.restore_from_onboard_backup("192.0.2.10", Some("secret"), std::time::Duration::ZERO)
|
||||||
|
.is_ok());
|
||||||
|
|
||||||
|
let absent = FakeMethod { present: false };
|
||||||
|
assert!(!absent
|
||||||
|
.onboard_stock_backup_present("192.0.2.10", None)
|
||||||
|
.unwrap());
|
||||||
|
assert!(matches!(
|
||||||
|
absent.restore_from_onboard_backup("192.0.2.10", None, std::time::Duration::ZERO),
|
||||||
|
Err(StockError::Method(_))
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,152 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
//! Legacy U-Boot image (`uImage`) header builder.
|
||||||
|
//!
|
||||||
|
//! The Zynq (Antminer S17/S19-class) stock U-Boot boots a legacy uImage: a
|
||||||
|
//! 64-byte big-endian header (magic `0x27051956`) in front of the payload. We
|
||||||
|
//! wrap the kernel (a raw ARM `zImage`) and the ramdisk (a gzipped cpio) in this
|
||||||
|
//! header so the board's own U-Boot boots them unchanged. The device tree is
|
||||||
|
//! written raw (no header).
|
||||||
|
//!
|
||||||
|
//! The header parameters below were read directly off a genuine stock S17 NAND
|
||||||
|
//! (kernel: type Kernel, uncompressed, load/entry `0x8000`; ramdisk: type
|
||||||
|
//! RAMDisk, gzip, load/entry `0`), so the images we write match exactly what the
|
||||||
|
//! stock boot chain already boots.
|
||||||
|
|
||||||
|
/// Legacy uImage magic (big-endian).
|
||||||
|
pub const IH_MAGIC: u32 = 0x2705_1956;
|
||||||
|
/// Header length in bytes.
|
||||||
|
pub const HEADER_LEN: usize = 64;
|
||||||
|
|
||||||
|
// ih_os
|
||||||
|
const IH_OS_LINUX: u8 = 5;
|
||||||
|
// ih_arch
|
||||||
|
const IH_ARCH_ARM: u8 = 2;
|
||||||
|
// ih_type
|
||||||
|
const IH_TYPE_KERNEL: u8 = 2;
|
||||||
|
const IH_TYPE_RAMDISK: u8 = 3;
|
||||||
|
// ih_comp
|
||||||
|
const IH_COMP_NONE: u8 = 0;
|
||||||
|
const IH_COMP_GZIP: u8 = 1;
|
||||||
|
|
||||||
|
/// A CRC-32 (IEEE 802.3, the variant U-Boot uses) over `data`.
|
||||||
|
pub fn crc32(data: &[u8]) -> u32 {
|
||||||
|
let mut crc: u32 = 0xFFFF_FFFF;
|
||||||
|
for &byte in data {
|
||||||
|
crc ^= byte as u32;
|
||||||
|
for _ in 0..8 {
|
||||||
|
let mask = (crc & 1).wrapping_neg();
|
||||||
|
crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
!crc
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which kind of uImage to build.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Kind {
|
||||||
|
/// ARM Linux kernel, uncompressed, load/entry 0x8000 (what the stock S17
|
||||||
|
/// kernel uImage uses).
|
||||||
|
Kernel,
|
||||||
|
/// ARM Linux ramdisk, gzip, load/entry 0 (what the stock S17 ramdisk uImage
|
||||||
|
/// uses).
|
||||||
|
Ramdisk,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Kind {
|
||||||
|
fn ih_type(self) -> u8 {
|
||||||
|
match self {
|
||||||
|
Kind::Kernel => IH_TYPE_KERNEL,
|
||||||
|
Kind::Ramdisk => IH_TYPE_RAMDISK,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn ih_comp(self) -> u8 {
|
||||||
|
match self {
|
||||||
|
Kind::Kernel => IH_COMP_NONE,
|
||||||
|
Kind::Ramdisk => IH_COMP_GZIP,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn load_entry(self) -> u32 {
|
||||||
|
match self {
|
||||||
|
Kind::Kernel => 0x8000,
|
||||||
|
Kind::Ramdisk => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wrap `payload` in a legacy uImage header of the given `kind` and return the
|
||||||
|
/// full image (header followed by payload). `time` is the header timestamp; pass
|
||||||
|
/// a fixed value for a reproducible image. `name` is truncated to 31 bytes.
|
||||||
|
pub fn wrap(kind: Kind, payload: &[u8], time: u32, name: &str) -> Vec<u8> {
|
||||||
|
let mut hdr = [0u8; HEADER_LEN];
|
||||||
|
hdr[0..4].copy_from_slice(&IH_MAGIC.to_be_bytes());
|
||||||
|
// hdr[4..8] header CRC: filled in last, over the header with this field zero.
|
||||||
|
hdr[8..12].copy_from_slice(&time.to_be_bytes());
|
||||||
|
hdr[12..16].copy_from_slice(&(payload.len() as u32).to_be_bytes());
|
||||||
|
hdr[16..20].copy_from_slice(&kind.load_entry().to_be_bytes());
|
||||||
|
hdr[20..24].copy_from_slice(&kind.load_entry().to_be_bytes());
|
||||||
|
hdr[24..28].copy_from_slice(&crc32(payload).to_be_bytes());
|
||||||
|
hdr[28] = IH_OS_LINUX;
|
||||||
|
hdr[29] = IH_ARCH_ARM;
|
||||||
|
hdr[30] = kind.ih_type();
|
||||||
|
hdr[31] = kind.ih_comp();
|
||||||
|
let name_bytes = name.as_bytes();
|
||||||
|
let n = name_bytes.len().min(31);
|
||||||
|
hdr[32..32 + n].copy_from_slice(&name_bytes[..n]);
|
||||||
|
// Header CRC over the 64-byte header with the hcrc field (4..8) zeroed.
|
||||||
|
let hcrc = crc32(&hdr);
|
||||||
|
hdr[4..8].copy_from_slice(&hcrc.to_be_bytes());
|
||||||
|
|
||||||
|
let mut out = Vec::with_capacity(HEADER_LEN + payload.len());
|
||||||
|
out.extend_from_slice(&hdr);
|
||||||
|
out.extend_from_slice(payload);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn crc32_known_vector() {
|
||||||
|
// CRC-32/ISO-HDLC of "123456789" is 0xCBF43926.
|
||||||
|
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
|
||||||
|
assert_eq!(crc32(b""), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn header_shape_and_fields() {
|
||||||
|
let img = wrap(Kind::Kernel, b"payload-bytes", 0, "alkane");
|
||||||
|
assert_eq!(img.len(), HEADER_LEN + 13);
|
||||||
|
assert_eq!(&img[0..4], &IH_MAGIC.to_be_bytes());
|
||||||
|
assert_eq!(u32::from_be_bytes([img[12], img[13], img[14], img[15]]), 13);
|
||||||
|
// kernel: load/entry 0x8000, type kernel, comp none
|
||||||
|
assert_eq!(&img[16..20], &0x8000u32.to_be_bytes());
|
||||||
|
assert_eq!(&img[20..24], &0x8000u32.to_be_bytes());
|
||||||
|
assert_eq!(img[28], IH_OS_LINUX);
|
||||||
|
assert_eq!(img[29], IH_ARCH_ARM);
|
||||||
|
assert_eq!(img[30], IH_TYPE_KERNEL);
|
||||||
|
assert_eq!(img[31], IH_COMP_NONE);
|
||||||
|
assert_eq!(&img[64..], b"payload-bytes");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ramdisk_fields() {
|
||||||
|
let img = wrap(Kind::Ramdisk, b"rd", 0, "rd");
|
||||||
|
assert_eq!(&img[16..20], &0u32.to_be_bytes());
|
||||||
|
assert_eq!(img[30], IH_TYPE_RAMDISK);
|
||||||
|
assert_eq!(img[31], IH_COMP_GZIP);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn header_crc_validates() {
|
||||||
|
let img = wrap(Kind::Kernel, b"abc", 0x1234, "n");
|
||||||
|
let mut hdr = [0u8; HEADER_LEN];
|
||||||
|
hdr.copy_from_slice(&img[..HEADER_LEN]);
|
||||||
|
let stored = u32::from_be_bytes([hdr[4], hdr[5], hdr[6], hdr[7]]);
|
||||||
|
hdr[4..8].copy_from_slice(&[0, 0, 0, 0]);
|
||||||
|
assert_eq!(crc32(&hdr), stored);
|
||||||
|
// data CRC over payload
|
||||||
|
let dcrc = u32::from_be_bytes([img[24], img[25], img[26], img[27]]);
|
||||||
|
assert_eq!(crc32(b"abc"), dcrc);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,809 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
//! Readable Zynq-7010 NAND install / restore / on-board-backup, driven entirely
|
||||||
|
//! over the network through two small root shells:
|
||||||
|
//!
|
||||||
|
//! * a board on **stock** is reached with the DSH root-on-stock primitives
|
||||||
|
//! (`crate::stock::root_exec` / `root_put`): this is the only compartmentalised
|
||||||
|
//! piece, and it is used only to get a root shell;
|
||||||
|
//! * a board on **alkane** is reached with ordinary SSH (`crate::transport`).
|
||||||
|
//!
|
||||||
|
//! Everything else -- what to write, where, in what form, and the read-back
|
||||||
|
//! verification -- lives here in plain, auditable Rust. The NAND writes
|
||||||
|
//! themselves are the same `flash_erase` + `nandwrite` MTD operations on both
|
||||||
|
//! sides; only the way we obtain the root shell differs.
|
||||||
|
//!
|
||||||
|
//! Absolute NAND map (Micron MT29F2G08, 256 MiB, 128 KiB erase, 2 KiB page),
|
||||||
|
//! confirmed on a genuine stock S17 and mirrored by the alkane board DT:
|
||||||
|
//! ```text
|
||||||
|
//! 0x00000000 BOOT.bin (FSBL + bitstream + stock U-Boot + env) NEVER written
|
||||||
|
//! 0x01a00000 device tree (raw fdt)
|
||||||
|
//! 0x02000000 kernel (legacy uImage)
|
||||||
|
//! 0x02800000 rootfs (legacy uImage ramdisk)
|
||||||
|
//! 0x04800000 stock `configs` (UBI) exposed read-only on alkane
|
||||||
|
//! 0x05000000 alkane-cfg (persisted MAC)
|
||||||
|
//! 0x06000000 on-board genuine-stock backup (stock `ramfs-bak` region)
|
||||||
|
//! 0x08000000 stock `reserve1` / nvdata (UBI) left untouched
|
||||||
|
//! ```
|
||||||
|
//! On a board running alkane the boot slots are exposed as the named partitions
|
||||||
|
//! `boot-dtb` / `boot-kernel` / `boot-rootfs` / `stock-backup` (see the board
|
||||||
|
//! DT); on stock they fall inside `mtd0` / `mtd1` / `ramfs-bak`. Because we map
|
||||||
|
//! an absolute offset to whichever MTD partition contains it, the same code
|
||||||
|
//! writes the same physical NAND on both sides.
|
||||||
|
|
||||||
|
use crate::md5::md5_hex;
|
||||||
|
use crate::stock::StockError;
|
||||||
|
use crate::transport::{Remote, SshOptions, SshTransport};
|
||||||
|
use crate::uimage::{self, Kind};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
/// NAND erase-block size (128 KiB).
|
||||||
|
const ERASE: u64 = 0x20000;
|
||||||
|
/// NAND page size (2 KiB); `nandwrite -p` pads the final page with 0xFF.
|
||||||
|
const PAGE: u64 = 0x800;
|
||||||
|
|
||||||
|
/// Absolute boot-slot offsets (see the module map).
|
||||||
|
const OFF_DTB: u64 = 0x1a00000;
|
||||||
|
const OFF_KERNEL: u64 = 0x2000000;
|
||||||
|
const OFF_ROOTFS: u64 = 0x2800000;
|
||||||
|
const OFF_STOCK_BACKUP: u64 = 0x6000000;
|
||||||
|
/// BOOT.bin occupies 0x0..0x1a00000 and is never written.
|
||||||
|
const BOOTBIN_PRESERVE: u64 = 0x1a00000;
|
||||||
|
|
||||||
|
/// Slot ceilings (so a too-large image is refused before any erase).
|
||||||
|
const SLOT_DTB: u64 = 0x600000;
|
||||||
|
const SLOT_KERNEL: u64 = 0x800000;
|
||||||
|
const SLOT_ROOTFS: u64 = 0x2000000;
|
||||||
|
const SLOT_STOCK_BACKUP: u64 = 0x2000000;
|
||||||
|
|
||||||
|
/// Where the backup data lives inside the 32 MiB stock-backup region: the first
|
||||||
|
/// erase block holds the manifest, the images follow, each erase-block aligned.
|
||||||
|
const BK_MANIFEST: u64 = OFF_STOCK_BACKUP; // 0x6000000
|
||||||
|
const BK_MAGIC: &[u8; 8] = b"ALKSTKB1";
|
||||||
|
|
||||||
|
fn round_up(value: u64, to: u64) -> u64 {
|
||||||
|
value.div_ceil(to) * to
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Root shells
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// A root shell on the target board: run a `/bin/sh` command as root and stream
|
||||||
|
/// a byte payload to a file as root. Both sides implement this; the NAND code
|
||||||
|
/// below is written once against it.
|
||||||
|
trait Shell {
|
||||||
|
fn exec(&mut self, cmd: &str) -> Result<String, StockError>;
|
||||||
|
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError>;
|
||||||
|
/// Longer-running command (large nandwrite / nanddump).
|
||||||
|
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stock board: root obtained through the compartmentalised DSH primitive.
|
||||||
|
struct StockShell {
|
||||||
|
host: String,
|
||||||
|
password: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Shell for StockShell {
|
||||||
|
fn exec(&mut self, cmd: &str) -> Result<String, StockError> {
|
||||||
|
crate::stock::root_exec(&self.host, self.password.as_deref(), cmd)
|
||||||
|
}
|
||||||
|
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError> {
|
||||||
|
crate::stock::root_exec(&self.host, self.password.as_deref(), cmd)
|
||||||
|
}
|
||||||
|
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> {
|
||||||
|
crate::stock::root_put(&self.host, self.password.as_deref(), data, remote_path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Alkane board: root over ordinary SSH. A throwaway known-hosts file is used
|
||||||
|
/// so a board whose SSH host key legitimately changed across an install still
|
||||||
|
/// connects (accept-new), which is the norm on the bench.
|
||||||
|
struct AlkaneShell {
|
||||||
|
transport: SshTransport,
|
||||||
|
_secret: TempFile,
|
||||||
|
}
|
||||||
|
|
||||||
|
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
|
fn temp_path(tag: &str) -> std::path::PathBuf {
|
||||||
|
let n = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||||
|
std::env::temp_dir().join(format!("alkane-{}-{}-{}", std::process::id(), tag, n))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A 0600 temp file removed on drop.
|
||||||
|
struct TempFile(std::path::PathBuf);
|
||||||
|
impl TempFile {
|
||||||
|
fn with(contents: &[u8], tag: &str) -> Result<Self, StockError> {
|
||||||
|
let path = temp_path(tag);
|
||||||
|
write_private(&path, contents).map_err(|e| StockError::Io(e.to_string()))?;
|
||||||
|
Ok(TempFile(path))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for TempFile {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = std::fs::remove_file(&self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
|
||||||
|
use std::io::Write as _;
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
|
let mut f = std::fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.truncate(true)
|
||||||
|
.write(true)
|
||||||
|
.mode(0o600)
|
||||||
|
.open(path)?;
|
||||||
|
f.write_all(contents)?;
|
||||||
|
f.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
|
||||||
|
std::fs::write(path, contents)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AlkaneShell {
|
||||||
|
fn connect(host: &str, password: Option<&str>) -> Result<Self, StockError> {
|
||||||
|
let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?;
|
||||||
|
let known = temp_path("kh");
|
||||||
|
let _ = std::fs::File::create(&known); // empty -> accept-new always accepts
|
||||||
|
let options = SshOptions {
|
||||||
|
host: host.to_owned(),
|
||||||
|
port: 22,
|
||||||
|
user: "root".to_owned(),
|
||||||
|
identity_file: None,
|
||||||
|
password_file: Some(secret.0.clone()),
|
||||||
|
known_hosts: Some(known),
|
||||||
|
root_method: crate::transport::RootMethod::Auto,
|
||||||
|
update_daemon_port: None,
|
||||||
|
};
|
||||||
|
let transport =
|
||||||
|
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
|
||||||
|
Ok(AlkaneShell {
|
||||||
|
transport,
|
||||||
|
_secret: secret,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Shell for AlkaneShell {
|
||||||
|
fn exec(&mut self, cmd: &str) -> Result<String, StockError> {
|
||||||
|
self.transport
|
||||||
|
.root_command(cmd, Duration::from_secs(120))
|
||||||
|
.map(|o| String::from_utf8_lossy(&o).into_owned())
|
||||||
|
.map_err(|e| StockError::Method(e.to_string()))
|
||||||
|
}
|
||||||
|
fn exec_long(&mut self, cmd: &str) -> Result<String, StockError> {
|
||||||
|
self.transport
|
||||||
|
.root_command(cmd, Duration::from_secs(900))
|
||||||
|
.map(|o| String::from_utf8_lossy(&o).into_owned())
|
||||||
|
.map_err(|e| StockError::Method(e.to_string()))
|
||||||
|
}
|
||||||
|
fn put(&mut self, data: &[u8], remote_path: &str) -> Result<(), StockError> {
|
||||||
|
let tmp = TempFile::with(data, "put")?;
|
||||||
|
self.transport
|
||||||
|
.push(&tmp.0, remote_path, Duration::from_secs(900))
|
||||||
|
.map_err(|e| StockError::Method(e.to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// MTD table: map an absolute NAND offset to (device, relative offset)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct Mtd {
|
||||||
|
dev: String, // e.g. "mtd2"
|
||||||
|
base: u64, // absolute NAND offset of the partition start
|
||||||
|
size: u64,
|
||||||
|
#[allow(dead_code)]
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read the MTD partition table. Each partition's absolute base comes from
|
||||||
|
/// `/sys/class/mtd/<dev>/offset` when present (alkane, where partitions are not
|
||||||
|
/// contiguous), falling back to the cumulative sum of sizes in `/proc/mtd`
|
||||||
|
/// order (stock, where they are contiguous from 0).
|
||||||
|
fn read_mtd_table(sh: &mut dyn Shell) -> Result<Vec<Mtd>, StockError> {
|
||||||
|
// name + size from /proc/mtd (always present); offset from sysfs if present.
|
||||||
|
let proc = sh.exec("cat /proc/mtd")?;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut cursor = 0u64;
|
||||||
|
for line in proc.lines() {
|
||||||
|
let line = line.trim();
|
||||||
|
if !line.starts_with("mtd") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// "mtd0: 02800000 00020000 \"name\""
|
||||||
|
let (dev, rest) = match line.split_once(':') {
|
||||||
|
Some(v) => v,
|
||||||
|
None => continue,
|
||||||
|
};
|
||||||
|
let mut it = rest.split_whitespace();
|
||||||
|
let size = it
|
||||||
|
.next()
|
||||||
|
.and_then(|h| u64::from_str_radix(h, 16).ok())
|
||||||
|
.ok_or_else(|| StockError::Method(format!("bad /proc/mtd line: {line}")))?;
|
||||||
|
let _erase = it.next();
|
||||||
|
let name = line.split('"').nth(1).unwrap_or("").to_owned();
|
||||||
|
let base = match sysfs_offset(sh, dev) {
|
||||||
|
Some(off) => off,
|
||||||
|
None => cursor,
|
||||||
|
};
|
||||||
|
cursor = cursor.max(base) + size;
|
||||||
|
out.push(Mtd {
|
||||||
|
dev: dev.to_owned(),
|
||||||
|
base,
|
||||||
|
size,
|
||||||
|
name,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if out.is_empty() {
|
||||||
|
return Err(StockError::Method("no MTD partitions found".into()));
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sysfs_offset(sh: &mut dyn Shell, dev: &str) -> Option<u64> {
|
||||||
|
let out = sh
|
||||||
|
.exec(&format!("cat /sys/class/mtd/{dev}/offset 2>/dev/null"))
|
||||||
|
.ok()?;
|
||||||
|
out.trim().parse::<u64>().ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Find the partition that contains `abs` and holding at least `len` bytes from
|
||||||
|
/// there; return (device, relative offset).
|
||||||
|
fn locate(table: &[Mtd], abs: u64, len: u64) -> Result<(&str, u64), StockError> {
|
||||||
|
for m in table {
|
||||||
|
if abs >= m.base && abs < m.base + m.size {
|
||||||
|
let rel = abs - m.base;
|
||||||
|
if rel + len > m.size {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"write of {len} B at abs 0x{abs:x} overruns {} (rel 0x{rel:x}, size 0x{:x})",
|
||||||
|
m.dev, m.size
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
return Ok((&m.dev, rel));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(StockError::Method(format!(
|
||||||
|
"no MTD partition exposes absolute offset 0x{abs:x} (is the boot region mapped?)"
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// NAND primitives
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// MD5 of `data` padded with 0xFF up to the next page boundary -- what a
|
||||||
|
/// `nandwrite -p` of `data` leaves on flash and what `nanddump -l <rounded>`
|
||||||
|
/// reads back.
|
||||||
|
fn padded_md5(data: &[u8]) -> String {
|
||||||
|
let rounded = round_up(data.len() as u64, PAGE) as usize;
|
||||||
|
let mut buf = data.to_vec();
|
||||||
|
buf.resize(rounded, 0xFF);
|
||||||
|
md5_hex(&buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write `data` to absolute NAND offset `abs`, staging it in `/tmp/alk`, erasing
|
||||||
|
/// the covering erase blocks, writing with `nandwrite -p`, and verifying the
|
||||||
|
/// read-back against the padded MD5. `abs` must be erase-block aligned.
|
||||||
|
fn write_abs(
|
||||||
|
sh: &mut dyn Shell,
|
||||||
|
table: &[Mtd],
|
||||||
|
abs: u64,
|
||||||
|
data: &[u8],
|
||||||
|
label: &str,
|
||||||
|
) -> Result<(), StockError> {
|
||||||
|
if abs < BOOTBIN_PRESERVE {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"refusing to write {label} at 0x{abs:x}: inside preserved BOOT.bin"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if !abs.is_multiple_of(ERASE) {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"{label} offset 0x{abs:x} is not erase-block aligned"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let (dev, rel) = locate(table, abs, data.len() as u64)?;
|
||||||
|
let dev = dev.to_owned();
|
||||||
|
let blocks = round_up(data.len() as u64, ERASE) / ERASE;
|
||||||
|
let remote = format!("/tmp/alk/{label}.img");
|
||||||
|
sh.exec("mkdir -p /tmp/alk")?;
|
||||||
|
sh.put(data, &remote)?;
|
||||||
|
// Confirm the staged payload arrived intact before we erase anything.
|
||||||
|
let put_md5 = first_token(&sh.exec(&format!("md5sum {remote}"))?);
|
||||||
|
if put_md5 != md5_hex(data) {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"{label}: staged copy md5 {put_md5} != {} (transfer corrupted)",
|
||||||
|
md5_hex(data)
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
sh.exec_long(&format!(
|
||||||
|
"flash_erase /dev/{dev} 0x{rel:x} {blocks} >/dev/null 2>&1 && \
|
||||||
|
nandwrite -p -s 0x{rel:x} /dev/{dev} {remote} >/dev/null 2>&1 && echo WROTE"
|
||||||
|
))
|
||||||
|
.and_then(|o| {
|
||||||
|
if o.contains("WROTE") {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(StockError::Method(format!(
|
||||||
|
"{label}: erase/write failed: {o}"
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
let readlen = round_up(data.len() as u64, PAGE);
|
||||||
|
let back = first_token(&sh.exec_long(&format!(
|
||||||
|
"nanddump -s 0x{rel:x} -l {readlen} /dev/{dev} 2>/dev/null | md5sum"
|
||||||
|
))?);
|
||||||
|
let want = padded_md5(data);
|
||||||
|
if back != want {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"{label}: read-back md5 {back} != {want} at /dev/{dev} rel 0x{rel:x} \
|
||||||
|
(write did not persist)"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
sh.exec(&format!("rm -f {remote}"))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copy `len` bytes already on NAND from absolute `src` to absolute `dst`
|
||||||
|
/// (used when carving the on-board stock backup). `dst` must be erase aligned.
|
||||||
|
fn copy_abs(
|
||||||
|
sh: &mut dyn Shell,
|
||||||
|
table: &[Mtd],
|
||||||
|
src: u64,
|
||||||
|
dst: u64,
|
||||||
|
len: u64,
|
||||||
|
label: &str,
|
||||||
|
) -> Result<(), StockError> {
|
||||||
|
let (sdev, srel) = locate(table, src, len)?;
|
||||||
|
let sdev = sdev.to_owned();
|
||||||
|
let (ddev, drel) = locate(table, dst, len)?;
|
||||||
|
let ddev = ddev.to_owned();
|
||||||
|
let blocks = round_up(len, ERASE) / ERASE;
|
||||||
|
let tmp = format!("/tmp/alk/{label}.bak");
|
||||||
|
sh.exec("mkdir -p /tmp/alk")?;
|
||||||
|
let out = sh.exec_long(&format!(
|
||||||
|
"nanddump -s 0x{srel:x} -l {len} /dev/{sdev} -f {tmp} >/dev/null 2>&1 && \
|
||||||
|
flash_erase /dev/{ddev} 0x{drel:x} {blocks} >/dev/null 2>&1 && \
|
||||||
|
nandwrite -p -s 0x{drel:x} /dev/{ddev} {tmp} >/dev/null 2>&1 && \
|
||||||
|
rm -f {tmp} && echo COPIED"
|
||||||
|
))?;
|
||||||
|
if !out.contains("COPIED") {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"{label}: backup copy failed: {out}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read `len` (even) bytes from NAND at (dev, rel) as raw bytes, via
|
||||||
|
/// `od -v -x`, which is the only `od` form the stock busybox understands (no
|
||||||
|
/// `-A`/`-t`). The leading octal address column and trailing byte-count line are
|
||||||
|
/// discarded by [`parse_od`].
|
||||||
|
fn read_small(sh: &mut dyn Shell, dev: &str, rel: u64, len: u64) -> Result<Vec<u8>, StockError> {
|
||||||
|
let out = sh.exec(&format!(
|
||||||
|
"nanddump -s 0x{rel:x} -l {len} /dev/{dev} 2>/dev/null | od -v -x"
|
||||||
|
))?;
|
||||||
|
Ok(parse_od(&out))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read a big-endian u32 at byte `field_off` within the image whose header
|
||||||
|
/// starts at the (page-aligned) absolute NAND offset `region_abs`. `nanddump`
|
||||||
|
/// needs a page-aligned `-s`, so we read the first 64 bytes of the region and
|
||||||
|
/// slice the field in Rust (used to size the genuine stock images from their
|
||||||
|
/// uImage / fdt headers before backing up).
|
||||||
|
fn read_header_u32_be(
|
||||||
|
sh: &mut dyn Shell,
|
||||||
|
table: &[Mtd],
|
||||||
|
region_abs: u64,
|
||||||
|
field_off: usize,
|
||||||
|
) -> Result<u32, StockError> {
|
||||||
|
let (dev, rel) = locate(table, region_abs, 64)?;
|
||||||
|
let dev = dev.to_owned();
|
||||||
|
let b = read_small(sh, &dev, rel, 64)?;
|
||||||
|
if b.len() < field_off + 4 {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"short header read at 0x{region_abs:x} ({} bytes)",
|
||||||
|
b.len()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(u32::from_be_bytes([
|
||||||
|
b[field_off],
|
||||||
|
b[field_off + 1],
|
||||||
|
b[field_off + 2],
|
||||||
|
b[field_off + 3],
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn first_token(s: &str) -> String {
|
||||||
|
s.split_whitespace().next().unwrap_or("").to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// On-board stock backup manifest
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct BackupManifest {
|
||||||
|
kernel_abs: u64,
|
||||||
|
kernel_len: u64,
|
||||||
|
dtb_abs: u64,
|
||||||
|
dtb_len: u64,
|
||||||
|
rootfs_abs: u64,
|
||||||
|
rootfs_len: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BackupManifest {
|
||||||
|
fn encode(&self) -> Vec<u8> {
|
||||||
|
let mut v = Vec::with_capacity(64);
|
||||||
|
v.extend_from_slice(BK_MAGIC);
|
||||||
|
for n in [
|
||||||
|
self.kernel_abs,
|
||||||
|
self.kernel_len,
|
||||||
|
self.dtb_abs,
|
||||||
|
self.dtb_len,
|
||||||
|
self.rootfs_abs,
|
||||||
|
self.rootfs_len,
|
||||||
|
] {
|
||||||
|
v.extend_from_slice(&n.to_be_bytes());
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
fn decode(b: &[u8]) -> Option<Self> {
|
||||||
|
if b.len() < 8 + 6 * 8 || &b[..8] != BK_MAGIC {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let g = |i: usize| {
|
||||||
|
let mut a = [0u8; 8];
|
||||||
|
a.copy_from_slice(&b[8 + i * 8..8 + i * 8 + 8]);
|
||||||
|
u64::from_be_bytes(a)
|
||||||
|
};
|
||||||
|
Some(BackupManifest {
|
||||||
|
kernel_abs: g(0),
|
||||||
|
kernel_len: g(1),
|
||||||
|
dtb_abs: g(2),
|
||||||
|
dtb_len: g(3),
|
||||||
|
rootfs_abs: g(4),
|
||||||
|
rootfs_len: g(5),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Carve the genuine stock kernel + dtb + ramdisk (still on NAND) into the
|
||||||
|
/// stock-backup region, with a manifest in its first block, so the board can be
|
||||||
|
/// returned to its own factory stock later with no vendor file. Called on the
|
||||||
|
/// stock side during a from-stock install, before the boot slots are overwritten.
|
||||||
|
fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, StockError> {
|
||||||
|
// Size the genuine images from their on-NAND headers (uImage data size at
|
||||||
|
// header offset 12; fdt totalsize at offset 4).
|
||||||
|
let kernel_len = 64 + read_header_u32_be(sh, table, OFF_KERNEL, 12)? as u64;
|
||||||
|
let dtb_len = read_header_u32_be(sh, table, OFF_DTB, 4)? as u64;
|
||||||
|
let rootfs_len = 64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64;
|
||||||
|
// Sanity: headers must look like a uImage/fdt, sizes within slots.
|
||||||
|
if !(64..=SLOT_KERNEL).contains(&kernel_len) || !(64..=SLOT_ROOTFS).contains(&rootfs_len) {
|
||||||
|
return Err(StockError::Method(format!(
|
||||||
|
"stock image sizes implausible (kernel {kernel_len}, rootfs {rootfs_len}); \
|
||||||
|
refusing to back up"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let k_dst = BK_MANIFEST + ERASE; // images follow the manifest block
|
||||||
|
let d_dst = k_dst + round_up(kernel_len, ERASE);
|
||||||
|
let r_dst = d_dst + round_up(dtb_len, ERASE);
|
||||||
|
if r_dst + round_up(rootfs_len, ERASE) > OFF_STOCK_BACKUP + SLOT_STOCK_BACKUP {
|
||||||
|
return Err(StockError::Method(
|
||||||
|
"stock backup does not fit in the 32 MiB backup region".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
copy_abs(sh, table, OFF_KERNEL, k_dst, kernel_len, "stock-kernel")?;
|
||||||
|
copy_abs(sh, table, OFF_DTB, d_dst, dtb_len, "stock-dtb")?;
|
||||||
|
copy_abs(sh, table, OFF_ROOTFS, r_dst, rootfs_len, "stock-rootfs")?;
|
||||||
|
let manifest = BackupManifest {
|
||||||
|
kernel_abs: k_dst,
|
||||||
|
kernel_len,
|
||||||
|
dtb_abs: d_dst,
|
||||||
|
dtb_len,
|
||||||
|
rootfs_abs: r_dst,
|
||||||
|
rootfs_len,
|
||||||
|
};
|
||||||
|
write_abs(
|
||||||
|
sh,
|
||||||
|
table,
|
||||||
|
BK_MANIFEST,
|
||||||
|
&manifest.encode(),
|
||||||
|
"stock-backup-manifest",
|
||||||
|
)?;
|
||||||
|
Ok(manifest)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read and validate the on-board backup manifest, if present.
|
||||||
|
fn read_backup_manifest(
|
||||||
|
sh: &mut dyn Shell,
|
||||||
|
table: &[Mtd],
|
||||||
|
) -> Result<Option<BackupManifest>, StockError> {
|
||||||
|
let (dev, rel) = match locate(table, BK_MANIFEST, 64) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(_) => return Ok(None), // region not mapped -> treat as absent
|
||||||
|
};
|
||||||
|
let dev = dev.to_owned();
|
||||||
|
// Pull the 64-byte manifest off NAND via `od -v -x` (busybox-safe) and parse.
|
||||||
|
let bytes = read_small(sh, &dev, rel, 64)?;
|
||||||
|
Ok(BackupManifest::decode(&bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse `od` hex output into bytes. Accepts both `-tx1` (byte hex) and `-x`
|
||||||
|
/// (little-endian 16-bit words).
|
||||||
|
fn parse_od(s: &str) -> Vec<u8> {
|
||||||
|
let toks: Vec<&str> = s.split_whitespace().collect();
|
||||||
|
// Heuristic: 2-char tokens are bytes (-tx1); 4-char tokens are LE words (-x).
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for t in &toks {
|
||||||
|
match t.len() {
|
||||||
|
2 => {
|
||||||
|
if let Ok(b) = u8::from_str_radix(t, 16) {
|
||||||
|
out.push(b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
4 => {
|
||||||
|
if let Ok(w) = u16::from_str_radix(t, 16) {
|
||||||
|
out.push((w & 0xff) as u8);
|
||||||
|
out.push((w >> 8) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Operations
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// What to write to the three boot slots (already in the exact on-NAND form:
|
||||||
|
/// kernel and rootfs as legacy uImages, dtb as a raw fdt).
|
||||||
|
struct BootImages {
|
||||||
|
kernel_uimage: Vec<u8>,
|
||||||
|
dtb: Vec<u8>,
|
||||||
|
rootfs_uimage: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_boot_slots(sh: &mut dyn Shell, table: &[Mtd], img: &BootImages) -> Result<(), StockError> {
|
||||||
|
// rootfs, dtb, kernel order: an interrupted run never leaves a new rootfs
|
||||||
|
// under an old kernel.
|
||||||
|
if img.rootfs_uimage.len() as u64 > SLOT_ROOTFS {
|
||||||
|
return Err(StockError::Method("rootfs over slot ceiling".into()));
|
||||||
|
}
|
||||||
|
if img.dtb.len() as u64 > SLOT_DTB {
|
||||||
|
return Err(StockError::Method("dtb over slot ceiling".into()));
|
||||||
|
}
|
||||||
|
if img.kernel_uimage.len() as u64 > SLOT_KERNEL {
|
||||||
|
return Err(StockError::Method("kernel over slot ceiling".into()));
|
||||||
|
}
|
||||||
|
write_abs(sh, table, OFF_ROOTFS, &img.rootfs_uimage, "rootfs")?;
|
||||||
|
write_abs(sh, table, OFF_DTB, &img.dtb, "dtb")?;
|
||||||
|
write_abs(sh, table, OFF_KERNEL, &img.kernel_uimage, "kernel")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the connected board is a Zynq, so the readable boot-slot path
|
||||||
|
/// applies. Other boards fall back to the compiled-in method.
|
||||||
|
fn shell_is_zynq(sh: &mut dyn Shell) -> bool {
|
||||||
|
sh.exec(
|
||||||
|
"(grep -qi zynq /proc/cpuinfo 2>/dev/null || \
|
||||||
|
grep -qai zynq /proc/device-tree/compatible 2>/dev/null) && echo yes || true",
|
||||||
|
)
|
||||||
|
.map(|o| o.contains("yes"))
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reboot(sh: &mut dyn Shell) {
|
||||||
|
// Best-effort: the reboot drops the shell, so ignore the result.
|
||||||
|
let _ = sh.exec("sync; (sleep 1; reboot) >/dev/null 2>&1 &");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Install alkane onto a board currently on stock, over the network. The afw
|
||||||
|
/// ships a raw `zImage`, a raw fdt and a gzipped cpio rootfs; we wrap the kernel
|
||||||
|
/// and rootfs as the legacy uImages the preserved stock U-Boot boots, carve the
|
||||||
|
/// genuine stock backup first, then write the boot slots and reboot.
|
||||||
|
pub fn install_from_stock(
|
||||||
|
host: &str,
|
||||||
|
kernel_zimage: &[u8],
|
||||||
|
dtb: &[u8],
|
||||||
|
rootfs_cpio_gz: &[u8],
|
||||||
|
password: Option<&str>,
|
||||||
|
) -> Result<(), StockError> {
|
||||||
|
let mut sh = StockShell {
|
||||||
|
host: host.to_owned(),
|
||||||
|
password: password.map(str::to_owned),
|
||||||
|
};
|
||||||
|
if first_token(&sh.exec("id -u")?) != "0" {
|
||||||
|
return Err(StockError::Auth(
|
||||||
|
"did not obtain root on the stock board".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let table = read_mtd_table(&mut sh)?;
|
||||||
|
// Carve the genuine-stock backup from the live stock NAND before any write.
|
||||||
|
carve_backup(&mut sh, &table)?;
|
||||||
|
let img = BootImages {
|
||||||
|
kernel_uimage: uimage::wrap(Kind::Kernel, kernel_zimage, 0, "alkane-kernel"),
|
||||||
|
dtb: dtb.to_vec(),
|
||||||
|
rootfs_uimage: uimage::wrap(Kind::Ramdisk, rootfs_cpio_gz, 0, "alkane-rootfs"),
|
||||||
|
};
|
||||||
|
write_boot_slots(&mut sh, &table, &img)?;
|
||||||
|
reboot(&mut sh);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return an alkane board to genuine stock by writing the vendor images back to
|
||||||
|
/// the boot slots over SSH. `dtb` is the genuine per-board device tree (from the
|
||||||
|
/// vendor package); if `None`, the stock dtb saved in the on-board backup is
|
||||||
|
/// used. `kernel`/`rootfs` are the vendor legacy uImages, written as-is.
|
||||||
|
pub fn restore_to_stock(
|
||||||
|
host: &str,
|
||||||
|
kernel_uimage: &[u8],
|
||||||
|
rootfs_uimage: &[u8],
|
||||||
|
dtb: Option<&[u8]>,
|
||||||
|
password: Option<&str>,
|
||||||
|
) -> Result<(), StockError> {
|
||||||
|
let mut sh = AlkaneShell::connect(host, password)?;
|
||||||
|
if !shell_is_zynq(&mut sh) {
|
||||||
|
return Err(StockError::NotApplicable);
|
||||||
|
}
|
||||||
|
let table = read_mtd_table(&mut sh)?;
|
||||||
|
if rootfs_uimage.len() as u64 > SLOT_ROOTFS || kernel_uimage.len() as u64 > SLOT_KERNEL {
|
||||||
|
return Err(StockError::Method("vendor image over slot ceiling".into()));
|
||||||
|
}
|
||||||
|
// rootfs, dtb, kernel order (same safety ordering as install).
|
||||||
|
write_abs(&mut sh, &table, OFF_ROOTFS, rootfs_uimage, "rootfs")?;
|
||||||
|
match dtb {
|
||||||
|
Some(d) => {
|
||||||
|
if d.len() as u64 > SLOT_DTB {
|
||||||
|
return Err(StockError::Method("dtb over slot ceiling".into()));
|
||||||
|
}
|
||||||
|
write_abs(&mut sh, &table, OFF_DTB, d, "dtb")?;
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// No vendor dtb (an OTA package omits it): restore the genuine
|
||||||
|
// per-board dtb from the on-board backup by copying within NAND.
|
||||||
|
let manifest = read_backup_manifest(&mut sh, &table)?.ok_or_else(|| {
|
||||||
|
StockError::Method(
|
||||||
|
"no stock dtb supplied and no on-board backup to take one from".into(),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
copy_abs(
|
||||||
|
&mut sh,
|
||||||
|
&table,
|
||||||
|
manifest.dtb_abs,
|
||||||
|
OFF_DTB,
|
||||||
|
manifest.dtb_len,
|
||||||
|
"dtb",
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
write_abs(&mut sh, &table, OFF_KERNEL, kernel_uimage, "kernel")?;
|
||||||
|
reboot(&mut sh);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the board holds a complete, restorable on-board stock backup.
|
||||||
|
pub fn onboard_backup_present(host: &str, password: Option<&str>) -> Result<bool, StockError> {
|
||||||
|
let mut sh = AlkaneShell::connect(host, password)?;
|
||||||
|
if !shell_is_zynq(&mut sh) {
|
||||||
|
return Err(StockError::NotApplicable);
|
||||||
|
}
|
||||||
|
let table = read_mtd_table(&mut sh)?;
|
||||||
|
Ok(read_backup_manifest(&mut sh, &table)?.is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Return an alkane board to stock using only the on-board backup (no vendor
|
||||||
|
/// file): copy the saved stock kernel, dtb and rootfs back to the boot slots.
|
||||||
|
pub fn restore_from_onboard(host: &str, password: Option<&str>) -> Result<(), StockError> {
|
||||||
|
let mut sh = AlkaneShell::connect(host, password)?;
|
||||||
|
if !shell_is_zynq(&mut sh) {
|
||||||
|
return Err(StockError::NotApplicable);
|
||||||
|
}
|
||||||
|
let table = read_mtd_table(&mut sh)?;
|
||||||
|
let manifest = read_backup_manifest(&mut sh, &table)?
|
||||||
|
.ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))?;
|
||||||
|
// Copy within NAND: backup region -> boot slots.
|
||||||
|
copy_abs(
|
||||||
|
&mut sh,
|
||||||
|
&table,
|
||||||
|
manifest.rootfs_abs,
|
||||||
|
OFF_ROOTFS,
|
||||||
|
manifest.rootfs_len,
|
||||||
|
"rootfs",
|
||||||
|
)?;
|
||||||
|
copy_abs(
|
||||||
|
&mut sh,
|
||||||
|
&table,
|
||||||
|
manifest.dtb_abs,
|
||||||
|
OFF_DTB,
|
||||||
|
manifest.dtb_len,
|
||||||
|
"dtb",
|
||||||
|
)?;
|
||||||
|
copy_abs(
|
||||||
|
&mut sh,
|
||||||
|
&table,
|
||||||
|
manifest.kernel_abs,
|
||||||
|
OFF_KERNEL,
|
||||||
|
manifest.kernel_len,
|
||||||
|
"kernel",
|
||||||
|
)?;
|
||||||
|
reboot(&mut sh);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_up_works() {
|
||||||
|
assert_eq!(round_up(1, PAGE), PAGE);
|
||||||
|
assert_eq!(round_up(PAGE, PAGE), PAGE);
|
||||||
|
assert_eq!(round_up(PAGE + 1, PAGE), 2 * PAGE);
|
||||||
|
assert_eq!(round_up(0, ERASE), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn padded_md5_matches_manual_pad() {
|
||||||
|
let data = b"hello";
|
||||||
|
let mut padded = data.to_vec();
|
||||||
|
padded.resize(PAGE as usize, 0xFF);
|
||||||
|
assert_eq!(padded_md5(data), md5_hex(&padded));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn manifest_roundtrips() {
|
||||||
|
let m = BackupManifest {
|
||||||
|
kernel_abs: 0x6020000,
|
||||||
|
kernel_len: 4006832,
|
||||||
|
dtb_abs: 0x6420000,
|
||||||
|
dtb_len: 7650,
|
||||||
|
rootfs_abs: 0x6440000,
|
||||||
|
rootfs_len: 26620582,
|
||||||
|
};
|
||||||
|
let enc = m.encode();
|
||||||
|
let dec = BackupManifest::decode(&enc).unwrap();
|
||||||
|
assert_eq!(dec.kernel_abs, m.kernel_abs);
|
||||||
|
assert_eq!(dec.rootfs_len, m.rootfs_len);
|
||||||
|
assert!(BackupManifest::decode(b"nope").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn locate_maps_absolute_to_partition() {
|
||||||
|
let table = vec![
|
||||||
|
Mtd {
|
||||||
|
dev: "mtd0".into(),
|
||||||
|
base: 0x0,
|
||||||
|
size: 0x2800000,
|
||||||
|
name: "x".into(),
|
||||||
|
},
|
||||||
|
Mtd {
|
||||||
|
dev: "mtd1".into(),
|
||||||
|
base: 0x2800000,
|
||||||
|
size: 0x2000000,
|
||||||
|
name: "y".into(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
assert_eq!(locate(&table, 0x2000000, 100).unwrap(), ("mtd0", 0x2000000));
|
||||||
|
assert_eq!(locate(&table, 0x2800000, 100).unwrap(), ("mtd1", 0));
|
||||||
|
assert!(locate(&table, 0x9000000, 1).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_od_both_forms() {
|
||||||
|
// -tx1 byte form
|
||||||
|
assert_eq!(parse_od("41 42 43"), vec![0x41, 0x42, 0x43]);
|
||||||
|
// -x little-endian word form -> bytes
|
||||||
|
assert_eq!(parse_od("4241"), vec![0x41, 0x42]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><g stroke="currentColor" stroke-width="24" stroke-linecap="round" fill="none"><path d="M256 150 L256 118"/><path d="M256 118 L214 74"/><path d="M256 118 L298 74"/><path d="M168 232 L88 196"/><path d="M164 302 L78 302"/><path d="M168 372 L88 414"/><path d="M344 232 L424 196"/><path d="M348 302 L434 302"/><path d="M344 372 L424 414"/></g><ellipse cx="256" cy="300" rx="96" ry="138" fill="currentColor"/><circle cx="256" cy="162" r="56" fill="currentColor"/></svg>
|
||||||
|
After Width: | Height: | Size: 526 B |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="currentColor" d="M448 80l0 48c0 44.2-100.3 80-224 80S0 172.2 0 128L0 80C0 35.8 100.3 0 224 0S448 35.8 448 80zM393.2 214.7c20.8-7.4 39.9-16.9 54.8-28.6L448 288c0 44.2-100.3 80-224 80S0 332.2 0 288L0 186.1c14.9 11.8 34 21.2 54.8 28.6C99.7 230.7 159.5 240 224 240s124.3-9.3 169.2-25.3zM0 346.1c14.9 11.8 34 21.2 54.8 28.6C99.7 390.7 159.5 400 224 400s124.3-9.3 169.2-25.3c20.8-7.4 39.9-16.9 54.8-28.6L448 432c0 44.2-100.3 80-224 80S0 476.2 0 432L0 346.1z"/></svg>
|
||||||
|
After Width: | Height: | Size: 535 B |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M495.9 166.6c3.2 8.7 .5 18.4-6.4 24.6l-43.3 39.4c1.1 8.3 1.7 16.8 1.7 25.4s-.6 17.1-1.7 25.4l43.3 39.4c6.9 6.2 9.6 15.9 6.4 24.6c-4.4 11.9-9.7 23.3-15.8 34.3l-4.7 8.1c-6.6 11-14 21.4-22.1 31.2c-5.9 7.2-15.7 9.6-24.5 6.8l-55.7-17.7c-13.4 10.3-28.2 18.9-44 25.4l-12.5 57.1c-2 9.1-9 16.3-18.2 17.8c-13.8 2.3-28 3.5-42.5 3.5s-28.7-1.2-42.5-3.5c-9.2-1.5-16.2-8.7-18.2-17.8l-12.5-57.1c-15.8-6.5-30.6-15.1-44-25.4L83.1 425.9c-8.8 2.8-18.6 .3-24.5-6.8c-8.1-9.8-15.5-20.2-22.1-31.2l-4.7-8.1c-6.1-11-11.4-22.4-15.8-34.3c-3.2-8.7-.5-18.4 6.4-24.6l43.3-39.4C64.6 273.1 64 264.6 64 256s.6-17.1 1.7-25.4L22.4 191.2c-6.9-6.2-9.6-15.9-6.4-24.6c4.4-11.9 9.7-23.3 15.8-34.3l4.7-8.1c6.6-11 14-21.4 22.1-31.2c5.9-7.2 15.7-9.6 24.5-6.8l55.7 17.7c13.4-10.3 28.2-18.9 44-25.4l12.5-57.1c2-9.1 9-16.3 18.2-17.8C227.3 1.2 241.5 0 256 0s28.7 1.2 42.5 3.5c9.2 1.5 16.2 8.7 18.2 17.8l12.5 57.1c15.8 6.5 30.6 15.1 44 25.4l55.7-17.7c8.8-2.8 18.6-.3 24.5 6.8c8.1 9.8 15.5 20.2 22.1 31.2l4.7 8.1c6.1 11 11.4 22.4 15.8 34.3zM256 336a80 80 0 1 0 0-160 80 80 0 1 0 0 160z"/></svg>
|
||||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path fill="currentColor" d="M64 0C28.7 0 0 28.7 0 64L0 448c0 35.3 28.7 64 64 64l256 0c35.3 0 64-28.7 64-64l0-277.5c0-17-6.7-33.3-18.7-45.3l-90.5-90.5C262.7 6.7 246.5 0 229.5 0L64 0zM96 96c0-8.8 7.2-16 16-16s16 7.2 16 16l0 64c0 8.8-7.2 16-16 16s-16-7.2-16-16l0-64zm80 0c0-8.8 7.2-16 16-16s16 7.2 16 16l0 64c0 8.8-7.2 16-16 16s-16-7.2-16-16l0-64zm80 0c0-8.8 7.2-16 16-16s16 7.2 16 16l0 64c0 8.8-7.2 16-16 16s-16-7.2-16-16l0-64z"/></svg>
|
||||||
|
After Width: | Height: | Size: 498 B |
@@ -137,18 +137,93 @@ fn parse_http_json(raw: &[u8]) -> Option<Value> {
|
|||||||
serde_json::from_str(body.trim()).ok()
|
serde_json::from_str(body.trim()).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Read the raw HTTP response head (status line + headers) of a GET on :80.
|
||||||
|
async fn http_response_head(ip: IpAddr, path: &str) -> Option<String> {
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
let connect = tokio::net::TcpStream::connect((ip, 80));
|
||||||
|
let mut stream = tokio::time::timeout(CONNECT_TIMEOUT, connect)
|
||||||
|
.await
|
||||||
|
.ok()?
|
||||||
|
.ok()?;
|
||||||
|
let request = format!("GET {path} HTTP/1.0\r\nHost: {ip}\r\nConnection: close\r\n\r\n");
|
||||||
|
stream.write_all(request.as_bytes()).await.ok()?;
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
let _ = tokio::time::timeout(READ_TIMEOUT, async {
|
||||||
|
let mut chunk = [0u8; 2048];
|
||||||
|
loop {
|
||||||
|
match stream.read(&mut chunk).await {
|
||||||
|
Ok(0) | Err(_) => break,
|
||||||
|
Ok(n) => {
|
||||||
|
raw.extend_from_slice(&chunk[..n]);
|
||||||
|
if raw.windows(4).any(|w| w == b"\r\n\r\n") || raw.len() > 8192 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let text = String::from_utf8_lossy(&raw);
|
||||||
|
let head = text.split("\r\n\r\n").next().unwrap_or("").to_string();
|
||||||
|
(!head.is_empty()).then_some(head)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A stock Antminer whose miner API (:4028) is down -- e.g. no hashboards, so
|
||||||
|
/// the miner software is not running -- still serves its vendor web UI on :80
|
||||||
|
/// with a `Digest realm="antMiner Configuration"` challenge. asic-rs cannot
|
||||||
|
/// identify such a board without the API, so recognise it here. The control
|
||||||
|
/// board/model are unknown from :80 alone, so the row is marked stock with an
|
||||||
|
/// unknown board; the operator picks the control board when flashing.
|
||||||
|
pub async fn detect_stock_antminer(ip: IpAddr) -> Option<MinerRow> {
|
||||||
|
let head = http_response_head(ip, "/").await?;
|
||||||
|
let lower = head.to_ascii_lowercase();
|
||||||
|
let is_stock_antminer = lower.contains("antminer configuration")
|
||||||
|
|| (lower.contains("server: lighttpd") && lower.contains(" 401 "));
|
||||||
|
if !is_stock_antminer {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(MinerRow {
|
||||||
|
ip: ip.to_string(),
|
||||||
|
brand: "Antminer".to_string(),
|
||||||
|
model: "Stock (model unknown)".to_string(),
|
||||||
|
firmware: "Stock".to_string(),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A stock Antminer the scan could identify as such but whose control board is
|
||||||
|
/// unknown (e.g. found only by its :80 vendor web UI). Alkane can still be
|
||||||
|
/// installed once the operator picks the control board, so the install flow
|
||||||
|
/// offers it with a manual board selector.
|
||||||
|
pub fn is_unidentified_stock_antminer(row: &MinerRow) -> bool {
|
||||||
|
row.brand.to_ascii_lowercase().contains("antminer")
|
||||||
|
&& row.firmware.eq_ignore_ascii_case("Stock")
|
||||||
|
&& board_family(row).is_none()
|
||||||
|
}
|
||||||
|
|
||||||
/// Whether the row is a board running Alkane OS (found by `detect`).
|
/// Whether the row is a board running Alkane OS (found by `detect`).
|
||||||
pub fn is_alkane(row: &MinerRow) -> bool {
|
pub fn is_alkane(row: &MinerRow) -> bool {
|
||||||
row.alkane_board.is_some()
|
row.alkane_board.is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The alkane-os board family the row's control board is, when it can be told:
|
/// The alkane-os board family the row's control board is, when it can be told:
|
||||||
/// what an Alkane board reports, or for a stock Antminer the Zynq-7010 (S17/T17
|
/// what an Alkane board reports, the stock Antminer Zynq-7010 (S17/T17 era,
|
||||||
/// era, "XIL (C49)") control board.
|
/// "XIL (C49)") control board, or the stock Amlogic A113D ("AML (C76)") control
|
||||||
|
/// board.
|
||||||
pub fn board_family(row: &MinerRow) -> Option<String> {
|
pub fn board_family(row: &MinerRow) -> Option<String> {
|
||||||
if let Some(board) = &row.alkane_board {
|
if let Some(board) = &row.alkane_board {
|
||||||
return (!board.is_empty()).then(|| board.clone());
|
return (!board.is_empty()).then(|| board.clone());
|
||||||
}
|
}
|
||||||
|
// A stock A113D (Amlogic AXG) control board -- the "a113d" install target
|
||||||
|
// (board_labels maps a113d -> "AML (C76)"). Decided on the control-board
|
||||||
|
// code, not the brand: asic-rs has no make for the Antminer BHB42XXX and
|
||||||
|
// reports its brand as "Unknown" (model "Unknown: ANTMINER BHB42XXX"), so
|
||||||
|
// the generic brand guard below would otherwise reject it. The "AML" code is
|
||||||
|
// only ever derived for an Amlogic Antminer control board, so this is
|
||||||
|
// specific on its own.
|
||||||
|
if row.cpu == "AML" && row.board_code == "C76" {
|
||||||
|
return Some("a113d".to_string());
|
||||||
|
}
|
||||||
if !row.brand.to_ascii_lowercase().contains("antminer") {
|
if !row.brand.to_ascii_lowercase().contains("antminer") {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -175,6 +250,15 @@ pub fn install_supported(row: &MinerRow) -> bool {
|
|||||||
board_family(row).is_some_and(|board| crate::stock_ops::is_supported_board(&board))
|
board_family(row).is_some_and(|board| crate::stock_ops::is_supported_board(&board))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Control boards that can boot from removable SD media, so the toolkit can
|
||||||
|
/// build an "Installation Media" card for them. Zynq-7010 is proven
|
||||||
|
/// (stock U-Boot card-detect side-load, confirmed on the bench S17 2026-11-17);
|
||||||
|
/// the Amlogic A113D is deliberately excluded -- it is eMMC-only with no SD slot
|
||||||
|
/// (USB recovery disabled), so it stays network-only.
|
||||||
|
pub fn media_supported(row: &MinerRow) -> bool {
|
||||||
|
matches!(board_family(row).as_deref(), Some("zynq-7010"))
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -243,7 +327,10 @@ mod tests {
|
|||||||
assert!(install_supported(&s17));
|
assert!(install_supported(&s17));
|
||||||
assert!(!is_alkane(&s17));
|
assert!(!is_alkane(&s17));
|
||||||
assert!(!install_supported(&stock("XIL", "C55"))); // S19-era Zynq
|
assert!(!install_supported(&stock("XIL", "C55"))); // S19-era Zynq
|
||||||
assert!(!install_supported(&stock("AML", "C76")));
|
// The Amlogic A113D control board is the "a113d" install target.
|
||||||
|
assert!(install_supported(&stock("AML", "C76")));
|
||||||
|
assert_eq!(board_family(&stock("AML", "C76")).as_deref(), Some("a113d"));
|
||||||
|
assert!(!install_supported(&stock("AML", "CBE"))); // 140mm S19k/S21-class, not a target
|
||||||
assert!(!install_supported(&stock("", "")));
|
assert!(!install_supported(&stock("", "")));
|
||||||
let whatsminer = MinerRow {
|
let whatsminer = MinerRow {
|
||||||
brand: "WhatsMiner".into(),
|
brand: "WhatsMiner".into(),
|
||||||
@@ -274,7 +361,9 @@ mod tests {
|
|||||||
assert!(!install_supported(&other("S19")));
|
assert!(!install_supported(&other("S19")));
|
||||||
assert!(!install_supported(&other("S17+")));
|
assert!(!install_supported(&other("S17+")));
|
||||||
assert!(!install_supported(&other("")));
|
assert!(!install_supported(&other("")));
|
||||||
// A reported control board overrides the model.
|
// A reported control board overrides the model: an "S17" model on an
|
||||||
|
// Amlogic A113D control board resolves to a113d (the control board),
|
||||||
|
// not zynq (the model).
|
||||||
let s17_on_aml = MinerRow {
|
let s17_on_aml = MinerRow {
|
||||||
brand: "Antminer".into(),
|
brand: "Antminer".into(),
|
||||||
model: "S17".into(),
|
model: "S17".into(),
|
||||||
@@ -282,7 +371,57 @@ mod tests {
|
|||||||
board_code: "C76".into(),
|
board_code: "C76".into(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
assert!(!install_supported(&s17_on_aml));
|
assert_eq!(board_family(&s17_on_aml).as_deref(), Some("a113d"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unidentified_stock_antminer_is_flaggable_for_manual_board_install() {
|
||||||
|
// As detect_stock_antminer builds it: brand Antminer, Stock, no control
|
||||||
|
// board (found only by its :80 web UI).
|
||||||
|
let row = MinerRow {
|
||||||
|
brand: "Antminer".into(),
|
||||||
|
model: "Stock (model unknown)".into(),
|
||||||
|
firmware: "Stock".into(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert!(is_unidentified_stock_antminer(&row));
|
||||||
|
assert!(board_family(&row).is_none());
|
||||||
|
assert!(!is_alkane(&row));
|
||||||
|
// A board with a known control board is NOT "unidentified".
|
||||||
|
let s17 = MinerRow {
|
||||||
|
brand: "Antminer".into(),
|
||||||
|
firmware: "Stock".into(),
|
||||||
|
cpu: "XIL".into(),
|
||||||
|
board_code: "C49".into(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert!(!is_unidentified_stock_antminer(&s17));
|
||||||
|
// A non-Antminer is never flagged.
|
||||||
|
let wm = MinerRow {
|
||||||
|
brand: "WhatsMiner".into(),
|
||||||
|
firmware: "Stock".into(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert!(!is_unidentified_stock_antminer(&wm));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stock_a113d_bhb42xxx_is_an_install_target_despite_unknown_brand() {
|
||||||
|
// Exactly as the live scan reports the bench A113D at 10.255.1.18:
|
||||||
|
// asic-rs cannot pin a make, so brand is "Unknown" and the model is
|
||||||
|
// "Unknown: ANTMINER BHB42XXX", but the control board classifies as
|
||||||
|
// "AML (C76)". Install must still be offered.
|
||||||
|
let bhb = MinerRow {
|
||||||
|
brand: "Unknown".into(),
|
||||||
|
model: "Unknown: ANTMINER BHB42XXX".into(),
|
||||||
|
firmware: "Stock".into(),
|
||||||
|
cpu: "AML".into(),
|
||||||
|
board_code: "C76".into(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(board_family(&bhb).as_deref(), Some("a113d"));
|
||||||
|
assert!(install_supported(&bhb));
|
||||||
|
assert!(!is_alkane(&bhb));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Live check against a real board:
|
/// Live check against a real board:
|
||||||
|
|||||||
@@ -0,0 +1,462 @@
|
|||||||
|
//! Headless bench automation (`ALKANE_BENCH_SEQUENCE`): drive the GUI's real
|
||||||
|
//! install/restore operation layer (`stock_ops`) through the A113D network-only
|
||||||
|
//! install <-> flag-restore cycle, with no window. This exercises the GUI
|
||||||
|
//! operator flow end-to-end against real hardware, for bench proofs, without the
|
||||||
|
//! wx event loop (the worker functions stream progress over a channel, exactly
|
||||||
|
//! as the UI drains them).
|
||||||
|
//!
|
||||||
|
//! Spec: `ALKANE_BENCH_SEQUENCE="<host> <local.afw> [iterations]"`.
|
||||||
|
//! The alkane root credential is read from the saved SSH credentials file.
|
||||||
|
//!
|
||||||
|
//! On the A113D, "restore to stock" is the one-byte flag flip (the install
|
||||||
|
//! overwrites no stock partition), so the cycle is: install (stock -> alkane) ->
|
||||||
|
//! verify alkane -> restore (flag flip -> stock) -> verify stock.
|
||||||
|
|
||||||
|
use std::io::Read;
|
||||||
|
use std::net::TcpStream;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::Command;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::credentials;
|
||||||
|
use crate::stock_ops::{self, AfwSource, StockHandle, StockMsg};
|
||||||
|
|
||||||
|
/// Drain a `StockHandle` to completion, printing progress; returns true iff
|
||||||
|
/// every board reported ok and at least one `Result` arrived.
|
||||||
|
fn drive(label: &str, handle: StockHandle) -> bool {
|
||||||
|
let mut ok = true;
|
||||||
|
let mut saw = false;
|
||||||
|
loop {
|
||||||
|
match handle.rx.recv() {
|
||||||
|
Ok(StockMsg::Started) => println!(" [{label}] started"),
|
||||||
|
Ok(StockMsg::Progress(s)) => println!(" [{label}] {s}"),
|
||||||
|
Ok(StockMsg::Result { ip, ok: r, detail }) => {
|
||||||
|
saw = true;
|
||||||
|
ok = ok && r;
|
||||||
|
println!(
|
||||||
|
" [{label}] {ip}: {} - {detail}",
|
||||||
|
if r { "OK" } else { "FAIL" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(StockMsg::Done) => break,
|
||||||
|
Err(_) => {
|
||||||
|
println!(" [{label}] channel closed early");
|
||||||
|
ok = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ok && saw
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read the SSH identification banner (no auth), e.g. `SSH-2.0-dropbear_2026.93`.
|
||||||
|
fn ssh_banner(host: &str) -> Option<String> {
|
||||||
|
let addr: std::net::SocketAddr = format!("{host}:22").parse().ok()?;
|
||||||
|
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(5)).ok()?;
|
||||||
|
stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?;
|
||||||
|
let mut buf = [0u8; 256];
|
||||||
|
let n = stream.read(&mut buf).ok()?;
|
||||||
|
if n == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(
|
||||||
|
String::from_utf8_lossy(&buf[..n])
|
||||||
|
.lines()
|
||||||
|
.next()
|
||||||
|
.unwrap_or("")
|
||||||
|
.trim()
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HTTP server header probe (stock serves lighttpd / an antMiner realm).
|
||||||
|
fn http_is_stock(host: &str) -> Option<bool> {
|
||||||
|
let out = Command::new("curl")
|
||||||
|
.args([
|
||||||
|
"-sS",
|
||||||
|
"-m",
|
||||||
|
"6",
|
||||||
|
"-o",
|
||||||
|
"/dev/null",
|
||||||
|
"-D",
|
||||||
|
"-",
|
||||||
|
&format!("http://{host}/"),
|
||||||
|
])
|
||||||
|
.output()
|
||||||
|
.ok()?;
|
||||||
|
let h = String::from_utf8_lossy(&out.stdout).to_lowercase();
|
||||||
|
if h.is_empty() {
|
||||||
|
None
|
||||||
|
} else if h.contains("lighttpd") || h.contains("antminer configuration") {
|
||||||
|
Some(true)
|
||||||
|
} else {
|
||||||
|
Some(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Classify the board: `Some(true)` = looks like genuine stock, `Some(false)` =
|
||||||
|
/// looks like alkane, `None` = no decisive answer (e.g. mid-reboot).
|
||||||
|
///
|
||||||
|
/// Primary signal is the SSH banner: stock A113D is `dropbear_2018.76`; alkane
|
||||||
|
/// ships a much newer dropbear. HTTP (lighttpd) is a stock fallback.
|
||||||
|
fn classify(host: &str) -> (String, Option<bool>) {
|
||||||
|
let banner = ssh_banner(host);
|
||||||
|
if let Some(b) = &banner {
|
||||||
|
let lb = b.to_lowercase();
|
||||||
|
if lb.contains("dropbear_2018") || lb.contains("dropbear_2019") {
|
||||||
|
return (format!("ssh \"{b}\" -> stock"), Some(true));
|
||||||
|
}
|
||||||
|
if lb.contains("dropbear") || lb.contains("openssh") {
|
||||||
|
return (format!("ssh \"{b}\" -> alkane"), Some(false));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match http_is_stock(host) {
|
||||||
|
Some(true) => ("http lighttpd/antMiner -> stock".to_string(), Some(true)),
|
||||||
|
Some(false) => ("http non-stock -> alkane".to_string(), Some(false)),
|
||||||
|
None => (
|
||||||
|
banner
|
||||||
|
.map(|b| format!("ssh \"{b}\" (unclassified), no http"))
|
||||||
|
.unwrap_or_else(|| "no ssh, no http (mid-reboot?)".to_string()),
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The MAC (lladdr) the kernel has cached for `host` (pings first to populate).
|
||||||
|
fn mac_of(host: &str) -> Option<String> {
|
||||||
|
let _ = Command::new("ping")
|
||||||
|
.args(["-c", "1", "-W", "1", host])
|
||||||
|
.output();
|
||||||
|
let out = Command::new("ip")
|
||||||
|
.args(["neigh", "show", host])
|
||||||
|
.output()
|
||||||
|
.ok()?;
|
||||||
|
let s = String::from_utf8_lossy(&out.stdout);
|
||||||
|
let mut it = s.split_whitespace();
|
||||||
|
while let Some(t) = it.next() {
|
||||||
|
if t == "lladdr" {
|
||||||
|
return it.next().map(|m| m.to_lowercase());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Populate the neighbour table by parallel-pinging the /24 of `sample` (a bench
|
||||||
|
/// board can take a different DHCP lease across a reboot, so we must re-find it).
|
||||||
|
fn sweep_subnet(sample: &str) {
|
||||||
|
let base = match sample.rsplit_once('.') {
|
||||||
|
Some((net, _)) => net.to_string(),
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
let mut kids = Vec::new();
|
||||||
|
for h in 2..=254 {
|
||||||
|
if let Ok(c) = Command::new("ping")
|
||||||
|
.args(["-c", "1", "-W", "1", &format!("{base}.{h}")])
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
{
|
||||||
|
kids.push(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for mut c in kids {
|
||||||
|
let _ = c.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Current IPv4 for `mac` from the neighbour table, if present.
|
||||||
|
fn ip_for_mac(mac: &str) -> Option<String> {
|
||||||
|
let out = Command::new("ip").args(["neigh"]).output().ok()?;
|
||||||
|
let s = String::from_utf8_lossy(&out.stdout);
|
||||||
|
let mac = mac.to_lowercase();
|
||||||
|
for line in s.lines() {
|
||||||
|
if line.to_lowercase().contains(&mac) {
|
||||||
|
if let Some(ip) = line.split_whitespace().next() {
|
||||||
|
if ip.contains('.') {
|
||||||
|
return Some(ip.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poll until the board (located by MAC, so a changed DHCP lease is followed)
|
||||||
|
/// reaches the wanted stock-ness, or `timeout` elapses. Returns the board's
|
||||||
|
/// current IP, a description, and whether the target state was reached.
|
||||||
|
fn wait_for(
|
||||||
|
mac: Option<&str>,
|
||||||
|
fallback: &str,
|
||||||
|
want_stock: bool,
|
||||||
|
timeout: Duration,
|
||||||
|
) -> (String, String, bool) {
|
||||||
|
let deadline = Instant::now() + timeout;
|
||||||
|
let mut ip = fallback.to_string();
|
||||||
|
let mut swept = Instant::now() - Duration::from_secs(60);
|
||||||
|
loop {
|
||||||
|
// Re-locate by MAC; sweep the subnet at most every ~25s to catch a new lease.
|
||||||
|
if let Some(m) = mac {
|
||||||
|
if ip_for_mac(m).is_none() && swept.elapsed() >= Duration::from_secs(25) {
|
||||||
|
sweep_subnet(fallback);
|
||||||
|
swept = Instant::now();
|
||||||
|
}
|
||||||
|
if let Some(found) = ip_for_mac(m) {
|
||||||
|
ip = found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (desc, is_stock) = classify(&ip);
|
||||||
|
let line = format!("[{ip}] {desc}");
|
||||||
|
if is_stock == Some(want_stock) {
|
||||||
|
return (ip, line, true);
|
||||||
|
}
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
return (ip, line, false);
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_secs(5));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the real fleet scan over `range` and report how each board classifies --
|
||||||
|
/// the scan step a user performs before acting. Returns the rows found.
|
||||||
|
fn scan_report(range: &str) -> Vec<crate::model::MinerRow> {
|
||||||
|
use crate::scan::{self, ScanMsg};
|
||||||
|
println!(" [scan] scanning {range} ...");
|
||||||
|
let handle = scan::start_scan(vec![range.to_string()], 10);
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
loop {
|
||||||
|
match handle.rx.recv() {
|
||||||
|
Ok(ScanMsg::Row(r)) => rows.push(r),
|
||||||
|
Ok(ScanMsg::Done(_)) | Ok(ScanMsg::Failed(_)) => break,
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rows.sort_by(|a, b| a.ip.cmp(&b.ip));
|
||||||
|
if rows.is_empty() {
|
||||||
|
println!(" [scan] no boards found");
|
||||||
|
}
|
||||||
|
for r in &rows {
|
||||||
|
let installable = crate::alkane_detect::install_supported(r)
|
||||||
|
|| crate::alkane_detect::is_unidentified_stock_antminer(r);
|
||||||
|
println!(
|
||||||
|
" [scan] {:<15} brand={:<10} model={:<22} fw={:<7} board={:<10} install={} alkane={}",
|
||||||
|
r.ip,
|
||||||
|
r.brand,
|
||||||
|
r.model,
|
||||||
|
r.firmware,
|
||||||
|
r.control_board,
|
||||||
|
installable,
|
||||||
|
crate::alkane_detect::is_alkane(r),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A full user-flow test driven headlessly through the GUI engine, including the
|
||||||
|
/// scan step a user performs: scan -> restore to stock -> scan -> install ->
|
||||||
|
/// scan -> verify the board serves the API and shows as alkane. Spec:
|
||||||
|
/// `<host> <afw> [scan-range]`.
|
||||||
|
pub fn run_flow(spec: &str) -> i32 {
|
||||||
|
let mut it = spec.split_whitespace();
|
||||||
|
let host = it.next().unwrap_or("").to_string();
|
||||||
|
let afw = PathBuf::from(it.next().unwrap_or(""));
|
||||||
|
let range = it.next().unwrap_or("10.255.1.0/24").to_string();
|
||||||
|
if host.is_empty() || afw.as_os_str().is_empty() {
|
||||||
|
eprintln!("ALKANE_BENCH_FLOW=\"<host> <afw> [scan-range]\"");
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
if !afw.exists() {
|
||||||
|
eprintln!("afw not found: {}", afw.display());
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
let stock_password = credentials::load_ssh_credentials().map(|(_, p)| p);
|
||||||
|
let alkane_password = std::env::var("ALKANE_ROOT_PASSWORD")
|
||||||
|
.ok()
|
||||||
|
.or_else(|| Some("alkane".to_string()));
|
||||||
|
let boot_timeout = Duration::from_secs(300);
|
||||||
|
|
||||||
|
println!("== A113D full GUI-flow test (scan -> restore -> scan -> install -> scan) ==");
|
||||||
|
let mac = mac_of(&host);
|
||||||
|
|
||||||
|
println!("\n[1/6] initial scan (as a user would)");
|
||||||
|
scan_report(&range);
|
||||||
|
|
||||||
|
let (desc, is_stock) = classify(&host);
|
||||||
|
println!("\n[2/6] target {host}: {desc}");
|
||||||
|
if is_stock != Some(true) {
|
||||||
|
println!("[3/6] restore {host} -> stock (flag flip)");
|
||||||
|
if !drive(
|
||||||
|
"restore",
|
||||||
|
stock_ops::start_restore_flag(vec![host.clone()], alkane_password.clone()),
|
||||||
|
) {
|
||||||
|
println!("[3/6] restore FAILED; aborting");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
let (_ip, d, ok) = wait_for(mac.as_deref(), &host, true, boot_timeout);
|
||||||
|
println!(
|
||||||
|
" {d} => {}",
|
||||||
|
if ok { "STOCK" } else { "NOT STOCK (fail)" }
|
||||||
|
);
|
||||||
|
if !ok {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
println!("[3/6] already stock; skipping restore");
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("\n[4/6] scan after restore (board should appear as a stock Antminer)");
|
||||||
|
scan_report(&range);
|
||||||
|
|
||||||
|
println!("\n[5/6] install alkane from stock");
|
||||||
|
let h = stock_ops::start_install(
|
||||||
|
vec![host.clone()],
|
||||||
|
"a113d".to_string(),
|
||||||
|
AfwSource::Local(afw.clone()),
|
||||||
|
true,
|
||||||
|
stock_password.clone(),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
if !drive("install", h) {
|
||||||
|
println!("[5/6] install FAILED");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
let (alkane_ip, d, ok) = wait_for(mac.as_deref(), &host, false, boot_timeout);
|
||||||
|
println!(
|
||||||
|
" {d} => {}",
|
||||||
|
if ok { "ALKANE" } else { "NOT ALKANE (fail)" }
|
||||||
|
);
|
||||||
|
|
||||||
|
println!("\n[6/6] scan after install (board should appear as ALKANE via the HTTP API)");
|
||||||
|
let rows = scan_report(&range);
|
||||||
|
let seen_alkane = rows
|
||||||
|
.iter()
|
||||||
|
.any(|r| crate::alkane_detect::is_alkane(r) && (r.ip == alkane_ip || r.ip == host));
|
||||||
|
println!(
|
||||||
|
"\n== FLOW RESULT: {} ==",
|
||||||
|
if ok && seen_alkane {
|
||||||
|
"PASS (installed, serves API, visible in scan)"
|
||||||
|
} else {
|
||||||
|
"INCOMPLETE (see the scan lines above)"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if ok && seen_alkane {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run(spec: &str) -> i32 {
|
||||||
|
let mut it = spec.split_whitespace();
|
||||||
|
let host = match it.next() {
|
||||||
|
Some(h) => h.to_string(),
|
||||||
|
None => {
|
||||||
|
eprintln!("ALKANE_BENCH_SEQUENCE=\"<host> <local.afw> [iterations]\"");
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let afw = match it.next() {
|
||||||
|
Some(a) => PathBuf::from(a),
|
||||||
|
None => {
|
||||||
|
eprintln!("missing local .afw path");
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let iterations: u32 = it.next().and_then(|s| s.parse().ok()).unwrap_or(1);
|
||||||
|
let board = "a113d".to_string();
|
||||||
|
// Install reaches STOCK via the compiled-in from-stock method; pass the saved
|
||||||
|
// board SSH credential through to it.
|
||||||
|
let stock_password = credentials::load_ssh_credentials().map(|(_, p)| p);
|
||||||
|
// The flag-restore reaches the running ALKANE board over SSH as `root` - a
|
||||||
|
// DIFFERENT credential from the stock login. Alkane bench images bake
|
||||||
|
// root/alkane; allow an override via ALKANE_ROOT_PASSWORD.
|
||||||
|
let alkane_password = std::env::var("ALKANE_ROOT_PASSWORD")
|
||||||
|
.ok()
|
||||||
|
.or_else(|| Some("alkane".to_string()));
|
||||||
|
|
||||||
|
println!("== A113D headless GUI bench sequence (network-only install <-> flag-restore) ==");
|
||||||
|
println!(
|
||||||
|
"host={host} afw={} board={board} iterations={iterations} stock_cred={} alkane_cred={}",
|
||||||
|
afw.display(),
|
||||||
|
if stock_password.is_some() { "loaded" } else { "none" },
|
||||||
|
if alkane_password.is_some() { "set" } else { "none" }
|
||||||
|
);
|
||||||
|
if !afw.exists() {
|
||||||
|
eprintln!("afw not found: {}", afw.display());
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve the board's MAC now (on stock) so we can re-find it after each
|
||||||
|
// reboot even if its DHCP lease changes under alkane.
|
||||||
|
let mac = mac_of(&host);
|
||||||
|
println!(
|
||||||
|
"board MAC: {}",
|
||||||
|
mac.as_deref()
|
||||||
|
.unwrap_or("unknown (will use the fixed host)")
|
||||||
|
);
|
||||||
|
|
||||||
|
let boot_timeout = Duration::from_secs(300);
|
||||||
|
let mut all_ok = true;
|
||||||
|
|
||||||
|
for i in 1..=iterations {
|
||||||
|
println!("\n-- iteration {i}/{iterations} --");
|
||||||
|
|
||||||
|
// 1. install (stock -> alkane) through the GUI operation layer
|
||||||
|
println!("[1/4] install: stock -> alkane");
|
||||||
|
let h = stock_ops::start_install(
|
||||||
|
vec![host.clone()],
|
||||||
|
board.clone(),
|
||||||
|
AfwSource::Local(afw.clone()),
|
||||||
|
true, // allow unsigned (bench image)
|
||||||
|
stock_password.clone(),
|
||||||
|
false, // not an in-place update
|
||||||
|
);
|
||||||
|
if !drive("install", h) {
|
||||||
|
all_ok = false;
|
||||||
|
println!("[1/4] install FAILED; aborting");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. verify alkane is live (board reboots into alkane)
|
||||||
|
println!(
|
||||||
|
"[2/4] verify alkane (awaiting reboot, up to {}s)...",
|
||||||
|
boot_timeout.as_secs()
|
||||||
|
);
|
||||||
|
let (alkane_ip, desc, ok) = wait_for(mac.as_deref(), &host, false, boot_timeout);
|
||||||
|
println!(
|
||||||
|
" {desc} => {}",
|
||||||
|
if ok { "ALKANE" } else { "NOT ALKANE (fail)" }
|
||||||
|
);
|
||||||
|
all_ok = all_ok && ok;
|
||||||
|
|
||||||
|
// 3. restore (alkane -> stock) flag-flip at the board's CURRENT address
|
||||||
|
println!("[3/4] restore: alkane -> stock (flag flip) at {alkane_ip}");
|
||||||
|
let h = stock_ops::start_restore_flag(vec![alkane_ip.clone()], alkane_password.clone());
|
||||||
|
if !drive("restore", h) {
|
||||||
|
all_ok = false;
|
||||||
|
println!("[3/4] restore FAILED");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. verify stock is back
|
||||||
|
println!(
|
||||||
|
"[4/4] verify stock (awaiting reboot, up to {}s)...",
|
||||||
|
boot_timeout.as_secs()
|
||||||
|
);
|
||||||
|
let (_stock_ip, desc, ok) = wait_for(mac.as_deref(), &host, true, boot_timeout);
|
||||||
|
println!(
|
||||||
|
" {desc} => {}",
|
||||||
|
if ok { "STOCK" } else { "NOT STOCK (fail)" }
|
||||||
|
);
|
||||||
|
all_ok = all_ok && ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"\n== BENCH RESULT: {} ==",
|
||||||
|
if all_ok { "PASS" } else { "FAIL" }
|
||||||
|
);
|
||||||
|
if all_ok {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -106,6 +106,9 @@ pub fn clear_credentials() -> std::io::Result<()> {
|
|||||||
/// duplicated here; a firmware absent from this table defaults to blank.
|
/// duplicated here; a firmware absent from this table defaults to blank.
|
||||||
pub fn firmware_default_creds() -> &'static [(&'static str, &'static str, &'static str)] {
|
pub fn firmware_default_creds() -> &'static [(&'static str, &'static str, &'static str)] {
|
||||||
&[
|
&[
|
||||||
|
// Alkane OS ships with this control-board login, so restore-to-stock on
|
||||||
|
// an alkane board authenticates with no operator setup (issue #51).
|
||||||
|
("Alkane", "root", "alkane"),
|
||||||
("AntMiner Stock", "root", "root"),
|
("AntMiner Stock", "root", "root"),
|
||||||
("WhatsMiner Stock", "admin", "admin"),
|
("WhatsMiner Stock", "admin", "admin"),
|
||||||
("Braiins", "root", "root"),
|
("Braiins", "root", "root"),
|
||||||
@@ -134,6 +137,18 @@ pub fn firmware_default_for(name: &str) -> (String, String) {
|
|||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The login to use for a board running `firmware`: the operator's saved
|
||||||
|
/// per-firmware override if any, else the shipped default. This is how install
|
||||||
|
/// (a stock target) and restore (an alkane target) each pick the right login
|
||||||
|
/// automatically, without a password field in the dialog (issues #46, #51).
|
||||||
|
pub fn cred_for(firmware: &str) -> (String, String) {
|
||||||
|
load_firmware_credentials()
|
||||||
|
.get(firmware)
|
||||||
|
.cloned()
|
||||||
|
.filter(|(_, p)| !p.is_empty())
|
||||||
|
.unwrap_or_else(|| firmware_default_for(firmware))
|
||||||
|
}
|
||||||
|
|
||||||
/// Load the operator's per-firmware credential overrides, keyed by firmware
|
/// Load the operator's per-firmware credential overrides, keyed by firmware
|
||||||
/// Display name. Malformed lines are skipped.
|
/// Display name. Malformed lines are skipped.
|
||||||
pub fn load_firmware_credentials() -> HashMap<String, (String, String)> {
|
pub fn load_firmware_credentials() -> HashMap<String, (String, String)> {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
mod access_probe;
|
mod access_probe;
|
||||||
mod alkane_detect;
|
mod alkane_detect;
|
||||||
mod askpass;
|
mod askpass;
|
||||||
|
mod bench_sequence;
|
||||||
mod bug_report;
|
mod bug_report;
|
||||||
mod credentials;
|
mod credentials;
|
||||||
mod export;
|
mod export;
|
||||||
@@ -15,6 +16,7 @@ mod fixtures;
|
|||||||
mod i18n;
|
mod i18n;
|
||||||
mod log_scan;
|
mod log_scan;
|
||||||
mod logs;
|
mod logs;
|
||||||
|
mod media_ops;
|
||||||
mod model;
|
mod model;
|
||||||
mod naming;
|
mod naming;
|
||||||
mod pool_prefs;
|
mod pool_prefs;
|
||||||
@@ -41,6 +43,19 @@ fn main() {
|
|||||||
std::process::exit(run_selftest());
|
std::process::exit(run_selftest());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Headless bench automation: drive the real install/restore operation layer
|
||||||
|
// (stock_ops) through the A113D network-only install <-> flag-restore cycle
|
||||||
|
// against real hardware, with no window. See bench_sequence.rs.
|
||||||
|
if let Some(spec) = std::env::var_os("ALKANE_BENCH_SEQUENCE") {
|
||||||
|
std::process::exit(bench_sequence::run(&spec.to_string_lossy()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Full GUI-flow test (scan -> restore -> scan -> install -> scan -> verify),
|
||||||
|
// exercising the scan step a user performs. See bench_sequence::run_flow.
|
||||||
|
if let Some(spec) = std::env::var_os("ALKANE_BENCH_FLOW") {
|
||||||
|
std::process::exit(bench_sequence::run_flow(&spec.to_string_lossy()));
|
||||||
|
}
|
||||||
|
|
||||||
// Headless access-probe check: `ALKANE_ACCESS_PROBE="<ip> <make>"` prints the
|
// Headless access-probe check: `ALKANE_ACCESS_PROBE="<ip> <make>"` prints the
|
||||||
// lock state the real access probe computes (no GUI, no wx), so the WhatsMiner
|
// lock state the real access probe computes (no GUI, no wx), so the WhatsMiner
|
||||||
// :4028 token check and the Antminer digest check can be verified directly.
|
// :4028 token check and the Antminer digest check can be verified directly.
|
||||||
@@ -123,9 +138,14 @@ fn run_selftest() -> i32 {
|
|||||||
|
|
||||||
/// True when the process runs one of the headless check modes instead of the GUI.
|
/// True when the process runs one of the headless check modes instead of the GUI.
|
||||||
fn headless_mode() -> bool {
|
fn headless_mode() -> bool {
|
||||||
["ALKANE_SELFTEST", "ALKANE_ACCESS_PROBE", "ALKANE_LOG_SCAN"]
|
[
|
||||||
.iter()
|
"ALKANE_SELFTEST",
|
||||||
.any(|v| std::env::var_os(v).is_some())
|
"ALKANE_ACCESS_PROBE",
|
||||||
|
"ALKANE_LOG_SCAN",
|
||||||
|
"ALKANE_BENCH_SEQUENCE",
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.any(|v| std::env::var_os(v).is_some())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A Windows GUI-subsystem process has no console, so output from the headless
|
/// A Windows GUI-subsystem process has no console, so output from the headless
|
||||||
|
|||||||
@@ -0,0 +1,306 @@
|
|||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
//! GUI-side orchestration for the "Installation Media" feature: enumerate
|
||||||
|
//! writable removable devices safely, and drive card creation + device write on
|
||||||
|
//! a background thread, streaming progress with the same [`StockMsg`] channel
|
||||||
|
//! the install/restore flows use.
|
||||||
|
//!
|
||||||
|
//! The card *image* is built with `alkane_flash::sd_media` (root-free); only the
|
||||||
|
//! final device write touches hardware, and the UI confirms the target first.
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::Command;
|
||||||
|
use std::sync::mpsc::channel;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use alkane_artifacts::afw::{verify_afw, VerifyOptions};
|
||||||
|
use alkane_flash::sd_media;
|
||||||
|
|
||||||
|
use crate::stock_ops::{StockHandle, StockMsg};
|
||||||
|
|
||||||
|
/// What kind of card to build.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum MediaKind {
|
||||||
|
/// Genuine vendor stock-recovery card (from a user-supplied vendor package).
|
||||||
|
StockRecovery,
|
||||||
|
/// Alkane that runs from the card each boot (nothing written to the board).
|
||||||
|
AlkaneSimpleBoot,
|
||||||
|
/// Alkane installer: boots, writes alkane to the board's storage, LED-signals.
|
||||||
|
AlkaneInstaller,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MediaKind {
|
||||||
|
pub fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
MediaKind::StockRecovery => "Stock recovery (restore the board to genuine stock)",
|
||||||
|
MediaKind::AlkaneSimpleBoot => {
|
||||||
|
"Alkane: run from SD card (nothing written to the board)"
|
||||||
|
}
|
||||||
|
MediaKind::AlkaneInstaller => {
|
||||||
|
"Alkane: installer (writes alkane to the board, then signals done)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A removable device that is a plausible SD/USB card target. Deliberately
|
||||||
|
/// conservative: only whole disks that are removable or hotplug, never a disk
|
||||||
|
/// that holds a mounted filesystem the host is using.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct RemovableDevice {
|
||||||
|
/// e.g. `/dev/sdc`.
|
||||||
|
pub path: String,
|
||||||
|
/// Human size, e.g. `14.6G`.
|
||||||
|
pub size: String,
|
||||||
|
/// Model string, e.g. `STORAGE DEVICE`.
|
||||||
|
pub model: String,
|
||||||
|
/// True if any partition of it is currently mounted (a caution flag the UI
|
||||||
|
/// surfaces; such a device is still selectable but clearly risky).
|
||||||
|
pub has_mounted_partition: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RemovableDevice {
|
||||||
|
pub fn describe(&self) -> String {
|
||||||
|
let mut s = format!("{} ({}", self.path, self.size.trim());
|
||||||
|
if !self.model.trim().is_empty() {
|
||||||
|
s.push_str(", ");
|
||||||
|
s.push_str(self.model.trim());
|
||||||
|
}
|
||||||
|
s.push(')');
|
||||||
|
if self.has_mounted_partition {
|
||||||
|
s.push_str(" [mounted]");
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enumerate removable whole-disk devices via `lsblk -J`. Returns an empty list
|
||||||
|
/// if `lsblk` is unavailable or parsing fails (the UI then offers a manual
|
||||||
|
/// device entry). The root/system disk is never included (it is not removable).
|
||||||
|
pub fn list_removable_devices() -> Vec<RemovableDevice> {
|
||||||
|
let out = match Command::new("lsblk")
|
||||||
|
.args([
|
||||||
|
"-J",
|
||||||
|
"-b",
|
||||||
|
"-o",
|
||||||
|
"NAME,SIZE,RM,HOTPLUG,TYPE,MODEL,TRAN,MOUNTPOINT",
|
||||||
|
])
|
||||||
|
.output()
|
||||||
|
{
|
||||||
|
Ok(o) if o.status.success() => o.stdout,
|
||||||
|
_ => return Vec::new(),
|
||||||
|
};
|
||||||
|
let json: serde_json::Value = match serde_json::from_slice(&out) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(_) => return Vec::new(),
|
||||||
|
};
|
||||||
|
let mut devices = Vec::new();
|
||||||
|
let blockdevices = json
|
||||||
|
.get("blockdevices")
|
||||||
|
.and_then(|v| v.as_array())
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default();
|
||||||
|
for dev in blockdevices {
|
||||||
|
let typ = dev.get("type").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
if typ != "disk" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let rm = dev.get("rm").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||||
|
let hotplug = dev
|
||||||
|
.get("hotplug")
|
||||||
|
.and_then(|v| v.as_bool())
|
||||||
|
.unwrap_or(false);
|
||||||
|
let tran = dev.get("tran").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
// Removable, or a hotplug USB disk. Never an internal nvme/sata system
|
||||||
|
// disk (those are rm=false, hotplug=false).
|
||||||
|
let removable = rm || (hotplug && (tran == "usb" || tran == "mmc"));
|
||||||
|
if !removable {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let name = dev.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
if name.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let size_bytes = dev.get("size").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||||
|
let model = dev
|
||||||
|
.get("model")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string();
|
||||||
|
let mounted = dev
|
||||||
|
.get("children")
|
||||||
|
.and_then(|v| v.as_array())
|
||||||
|
.map(|parts| {
|
||||||
|
parts.iter().any(|p| {
|
||||||
|
p.get("mountpoint")
|
||||||
|
.and_then(|m| m.as_str())
|
||||||
|
.map(|m| !m.is_empty())
|
||||||
|
.unwrap_or(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.unwrap_or(false)
|
||||||
|
|| dev
|
||||||
|
.get("mountpoint")
|
||||||
|
.and_then(|m| m.as_str())
|
||||||
|
.map(|m| !m.is_empty())
|
||||||
|
.unwrap_or(false);
|
||||||
|
devices.push(RemovableDevice {
|
||||||
|
path: format!("/dev/{name}"),
|
||||||
|
size: human_size(size_bytes),
|
||||||
|
model,
|
||||||
|
has_mounted_partition: mounted,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
devices
|
||||||
|
}
|
||||||
|
|
||||||
|
fn human_size(bytes: u64) -> String {
|
||||||
|
const UNITS: [&str; 5] = ["B", "K", "M", "G", "T"];
|
||||||
|
let mut v = bytes as f64;
|
||||||
|
let mut u = 0;
|
||||||
|
while v >= 1024.0 && u < UNITS.len() - 1 {
|
||||||
|
v /= 1024.0;
|
||||||
|
u += 1;
|
||||||
|
}
|
||||||
|
format!("{v:.1}{}", UNITS[u])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fully-specified media-creation request.
|
||||||
|
pub struct MediaRequest {
|
||||||
|
pub kind: MediaKind,
|
||||||
|
/// The source: an `.afw` file (alkane kinds) or a vendor stock package
|
||||||
|
/// (directory or `.zip`, stock kind).
|
||||||
|
pub source: PathBuf,
|
||||||
|
/// Target device, e.g. `/dev/sdc`. When `None`, only the image is built
|
||||||
|
/// (to `image_out`) and not written.
|
||||||
|
pub device: Option<PathBuf>,
|
||||||
|
/// Where the intermediate card image is written.
|
||||||
|
pub image_out: PathBuf,
|
||||||
|
/// Allow an unsigned `.afw` (bench).
|
||||||
|
pub allow_unsigned: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the requested card image (and write it to the device if one is set) on
|
||||||
|
/// a background thread, streaming [`StockMsg`] exactly like `start_install`.
|
||||||
|
pub fn start_make_media(req: MediaRequest) -> StockHandle {
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
let cancel = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||||
|
let cancel_worker = cancel.clone();
|
||||||
|
let err_tx = tx.clone();
|
||||||
|
|
||||||
|
let spawned = std::thread::Builder::new()
|
||||||
|
.name("alkane-make-media".into())
|
||||||
|
.spawn(move || {
|
||||||
|
let _ = tx.send(StockMsg::Started);
|
||||||
|
let now = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs() as u32)
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
let build = || -> Result<(), String> {
|
||||||
|
match req.kind {
|
||||||
|
MediaKind::StockRecovery => {
|
||||||
|
let _ = tx.send(StockMsg::Progress("preparing vendor package...".into()));
|
||||||
|
let dir = unpack_if_zip(&req.source).map_err(|e| e.to_string())?;
|
||||||
|
let _ = tx.send(StockMsg::Progress(
|
||||||
|
"assembling stock-recovery card...".into(),
|
||||||
|
));
|
||||||
|
sd_media::build_stock_recovery_card(&dir, &req.image_out)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
MediaKind::AlkaneSimpleBoot | MediaKind::AlkaneInstaller => {
|
||||||
|
let _ = tx.send(StockMsg::Progress("verifying .afw...".into()));
|
||||||
|
let verified = verify_afw(
|
||||||
|
&req.source,
|
||||||
|
&VerifyOptions {
|
||||||
|
allow_unsigned: req.allow_unsigned,
|
||||||
|
expect_board: Some("zynq-7010".into()),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(|e| format!(".afw: {e}"))?;
|
||||||
|
if req.kind == MediaKind::AlkaneSimpleBoot {
|
||||||
|
let _ = tx
|
||||||
|
.send(StockMsg::Progress("assembling simple-boot card...".into()));
|
||||||
|
sd_media::build_zynq_simpleboot_card(&verified, &req.image_out, now)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
} else {
|
||||||
|
let _ = tx.send(StockMsg::Progress(
|
||||||
|
"assembling installer card (injecting install hook)...".into(),
|
||||||
|
));
|
||||||
|
sd_media::build_zynq_installer_card(&verified, &req.image_out, now)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(dev) = &req.device {
|
||||||
|
if cancel_worker.load(std::sync::atomic::Ordering::Relaxed) {
|
||||||
|
return Err("cancelled before device write".into());
|
||||||
|
}
|
||||||
|
let _ = tx.send(StockMsg::Progress(format!(
|
||||||
|
"writing card to {} (do not remove)...",
|
||||||
|
dev.display()
|
||||||
|
)));
|
||||||
|
sd_media::write_image_to_device(&req.image_out, dev)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
|
|
||||||
|
let (ok, detail) = match build() {
|
||||||
|
Ok(()) => {
|
||||||
|
let where_ = req
|
||||||
|
.device
|
||||||
|
.as_ref()
|
||||||
|
.map(|d| format!("written to {}", d.display()))
|
||||||
|
.unwrap_or_else(|| format!("image at {}", req.image_out.display()));
|
||||||
|
(true, format!("card ready ({where_})"))
|
||||||
|
}
|
||||||
|
Err(e) => (false, format!("media build failed: {e}")),
|
||||||
|
};
|
||||||
|
let ip = req
|
||||||
|
.device
|
||||||
|
.as_ref()
|
||||||
|
.map(|d| d.display().to_string())
|
||||||
|
.unwrap_or_else(|| "card".into());
|
||||||
|
let _ = tx.send(StockMsg::Result { ip, ok, detail });
|
||||||
|
let _ = tx.send(StockMsg::Done);
|
||||||
|
});
|
||||||
|
|
||||||
|
if spawned.is_err() {
|
||||||
|
let _ = err_tx.send(StockMsg::Result {
|
||||||
|
ip: String::new(),
|
||||||
|
ok: false,
|
||||||
|
detail: "could not start the media worker thread".into(),
|
||||||
|
});
|
||||||
|
let _ = err_tx.send(StockMsg::Done);
|
||||||
|
}
|
||||||
|
StockHandle::new(rx, cancel)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// If `src` is a `.zip`, unpack it to an ephemeral directory and return that;
|
||||||
|
/// a directory is returned as-is.
|
||||||
|
fn unpack_if_zip(src: &std::path::Path) -> std::io::Result<PathBuf> {
|
||||||
|
if src.is_dir() {
|
||||||
|
return Ok(src.to_path_buf());
|
||||||
|
}
|
||||||
|
if src
|
||||||
|
.extension()
|
||||||
|
.is_some_and(|e| e.eq_ignore_ascii_case("zip"))
|
||||||
|
{
|
||||||
|
let staged = std::env::temp_dir().join(format!("alkane-media-pkg-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&staged);
|
||||||
|
std::fs::create_dir_all(&staged)?;
|
||||||
|
let status = Command::new("unzip")
|
||||||
|
.args(["-o", "-q"])
|
||||||
|
.arg(src)
|
||||||
|
.arg("-d")
|
||||||
|
.arg(&staged)
|
||||||
|
.status()?;
|
||||||
|
if !status.success() {
|
||||||
|
return Err(std::io::Error::other("unzip failed"));
|
||||||
|
}
|
||||||
|
return Ok(staged);
|
||||||
|
}
|
||||||
|
Err(std::io::Error::other(
|
||||||
|
"stock package must be a directory or a .zip",
|
||||||
|
))
|
||||||
|
}
|
||||||
@@ -692,9 +692,18 @@ impl MinerRow {
|
|||||||
/// live); grey (unknown) otherwise -- asic-rs has no direct PSU-fault flag, so
|
/// live); grey (unknown) otherwise -- asic-rs has no direct PSU-fault flag, so
|
||||||
/// a missing wattage reading is treated as unknown, never a false "down".
|
/// a missing wattage reading is treated as unknown, never a false "down".
|
||||||
pub fn power_health(&self) -> CompHealth {
|
pub fn power_health(&self) -> CompHealth {
|
||||||
// A miner drawing power / spinning its PSU fan / actively mining has a live
|
// A live PSU shows real evidence: measured draw, a spinning PSU fan, or
|
||||||
// PSU regardless of any warning flag.
|
// reported PSU output. A stock control board can assert a cgminer "mining"
|
||||||
let delivering = self.power_w > 0.0 || self.psu_fan_rpm > 0.0 || self.is_mining;
|
// status with no PSU and no hashboards attached (issue #39: a bare S17
|
||||||
|
// control board showed a green PSU), so is_mining counts only when the
|
||||||
|
// miner is actually hashing (hashrate, or at least one healthy board).
|
||||||
|
let actually_hashing =
|
||||||
|
self.hashrate_ths > 0.0 || self.board_status.contains(&BoardHealth::Ok);
|
||||||
|
let delivering = self.power_w > 0.0
|
||||||
|
|| self.psu_fan_rpm > 0.0
|
||||||
|
|| self.psu_out_voltage_v.is_some()
|
||||||
|
|| self.psu_out_current_a.is_some()
|
||||||
|
|| (self.is_mining && actually_hashing);
|
||||||
// A reported PSU fault while the miner is actually mining is a warning, not
|
// A reported PSU fault while the miner is actually mining is a warning, not
|
||||||
// a failure -- yellow, not red (round 18 #2: some WhatsMiners flag a PSU
|
// a failure -- yellow, not red (round 18 #2: some WhatsMiners flag a PSU
|
||||||
// error while running fine). A fault on a miner that is not mining is a real
|
// error while running fine). A fault on a miner that is not mining is a real
|
||||||
@@ -2476,6 +2485,52 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stock_board_with_nothing_attached_shows_grey_psu() {
|
||||||
|
// Issue #39: a stock S17 control board with no PSU and no hashboards
|
||||||
|
// attached asserts a cgminer "mining" status (is_mining = true) while
|
||||||
|
// reporting zero watts, no PSU fan, and no PSU output. That is not
|
||||||
|
// evidence of a live PSU, so the bolt must read grey (Unreachable).
|
||||||
|
let bare = MinerRow {
|
||||||
|
is_mining: true,
|
||||||
|
power_w: 0.0,
|
||||||
|
psu_fan_rpm: 0.0,
|
||||||
|
hashrate_ths: 0.0,
|
||||||
|
board_status: vec![BoardHealth::Missing, BoardHealth::Missing],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(bare.power_health(), CompHealth::Unreachable);
|
||||||
|
|
||||||
|
// A genuinely-running miner still greens: is_mining with real hashing is
|
||||||
|
// evidence enough even when the firmware reports no watts.
|
||||||
|
let hashing = MinerRow {
|
||||||
|
is_mining: true,
|
||||||
|
power_w: 0.0,
|
||||||
|
psu_fan_rpm: 0.0,
|
||||||
|
hashrate_ths: 90.0,
|
||||||
|
board_status: vec![BoardHealth::Ok, BoardHealth::Ok],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(hashing.power_health(), CompHealth::Ok);
|
||||||
|
|
||||||
|
// Measured draw alone is always enough.
|
||||||
|
let drawing = MinerRow {
|
||||||
|
is_mining: false,
|
||||||
|
power_w: 19.0,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(drawing.power_health(), CompHealth::Ok);
|
||||||
|
|
||||||
|
// Reported PSU output alone is enough even with zero measured watts.
|
||||||
|
let psu_out = MinerRow {
|
||||||
|
is_mining: false,
|
||||||
|
power_w: 0.0,
|
||||||
|
psu_out_voltage_v: Some(12.0),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(psu_out.power_health(), CompHealth::Ok);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn warning_fault_degrades_board_to_yellow_not_red() {
|
fn warning_fault_degrades_board_to_yellow_not_red() {
|
||||||
// Round 21 #1: a board still mining near full hashrate with some failed/
|
// Round 21 #1: a board still mining near full hashrate with some failed/
|
||||||
|
|||||||
@@ -533,8 +533,18 @@ pub fn start_scan(lines: Vec<String>, timeout_secs: u64) -> ScanHandle {
|
|||||||
}
|
}
|
||||||
// asic-rs does not recognise a board running Alkane
|
// asic-rs does not recognise a board running Alkane
|
||||||
// OS (no cgminer socket or vendor web UI exposed);
|
// OS (no cgminer socket or vendor web UI exposed);
|
||||||
// the toolkit's own probe finds it.
|
// the toolkit's own probe finds it. Failing that,
|
||||||
None => (ip, crate::alkane_detect::detect(ip).await),
|
// a stock Antminer whose miner API is down is still
|
||||||
|
// found by its :80 vendor web UI.
|
||||||
|
None => {
|
||||||
|
let row = match crate::alkane_detect::detect(ip).await {
|
||||||
|
Some(r) => Some(r),
|
||||||
|
None => {
|
||||||
|
crate::alkane_detect::detect_stock_antminer(ip).await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
(ip, row)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -674,6 +684,62 @@ fn messages_to_faults(
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A hashboard's health dot from its reported activity. `active` is the firmware's
|
||||||
|
/// active flag; `working_chips` its working-chip count. Green needs positive
|
||||||
|
/// evidence (active, or a nonzero chip count); a board with neither flag nor count
|
||||||
|
/// reads grey ("not detected") rather than green (issue #39: an S17 control board
|
||||||
|
/// with no hashboards attached showed its boards green). A board that is present
|
||||||
|
/// but idle or has zero working chips reads as a fault (red).
|
||||||
|
fn board_health(
|
||||||
|
active: Option<bool>,
|
||||||
|
working_chips: Option<u16>,
|
||||||
|
miner_active: bool,
|
||||||
|
) -> crate::model::BoardHealth {
|
||||||
|
use crate::model::BoardHealth;
|
||||||
|
match (active, working_chips) {
|
||||||
|
(Some(true), _) => BoardHealth::Ok,
|
||||||
|
(Some(false), _) => BoardHealth::Fault,
|
||||||
|
(None, Some(c)) if c > 0 => BoardHealth::Ok,
|
||||||
|
(None, Some(_)) => BoardHealth::Fault,
|
||||||
|
// No per-board evidence. If the miner shows overall activity (hashing),
|
||||||
|
// the board is clearly present and working -> green; only an idle miner
|
||||||
|
// with no board telemetry reads grey (issue #39: bare S17; review #3: do
|
||||||
|
// not grey a genuinely-mining miner whose backend omits per-board fields).
|
||||||
|
(None, None) => {
|
||||||
|
if miner_active {
|
||||||
|
BoardHealth::Ok
|
||||||
|
} else {
|
||||||
|
BoardHealth::Missing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod board_health_tests {
|
||||||
|
use super::board_health;
|
||||||
|
use crate::model::BoardHealth;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_activity_evidence_reads_grey_not_green() {
|
||||||
|
// Issue #39: the firmware lists a board but reports no active flag and no
|
||||||
|
// working-chip count -> not detected (grey), not green.
|
||||||
|
// Idle miner, no per-board evidence -> not detected (grey).
|
||||||
|
assert_eq!(board_health(None, None, false), BoardHealth::Missing);
|
||||||
|
// Mining miner, no per-board evidence -> still green (review #3).
|
||||||
|
assert_eq!(board_health(None, None, true), BoardHealth::Ok);
|
||||||
|
// Positive evidence still greens regardless of miner activity.
|
||||||
|
assert_eq!(board_health(Some(true), None, false), BoardHealth::Ok);
|
||||||
|
assert_eq!(board_health(None, Some(63), false), BoardHealth::Ok);
|
||||||
|
// Present but idle / zero working chips -> fault (red).
|
||||||
|
assert_eq!(
|
||||||
|
board_health(Some(false), Some(63), false),
|
||||||
|
BoardHealth::Fault
|
||||||
|
);
|
||||||
|
assert_eq!(board_health(None, Some(0), false), BoardHealth::Fault);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod board_index_tests {
|
mod board_index_tests {
|
||||||
use super::board_index_from_text;
|
use super::board_index_from_text;
|
||||||
@@ -1189,18 +1255,7 @@ async fn to_row(miner: &dyn Miner) -> MinerRow {
|
|||||||
let mut board_status: Vec<crate::model::BoardHealth> = data
|
let mut board_status: Vec<crate::model::BoardHealth> = data
|
||||||
.hashboards
|
.hashboards
|
||||||
.iter()
|
.iter()
|
||||||
.map(|b| {
|
.map(|b| board_health(b.active, b.working_chips, is_mining || hashrate_ths > 0.0))
|
||||||
let ok = match (b.active, b.working_chips) {
|
|
||||||
(Some(a), _) => a,
|
|
||||||
(None, Some(c)) => c > 0,
|
|
||||||
(None, None) => true,
|
|
||||||
};
|
|
||||||
if ok {
|
|
||||||
crate::model::BoardHealth::Ok
|
|
||||||
} else {
|
|
||||||
crate::model::BoardHealth::Fault
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect();
|
.collect();
|
||||||
if let Some(exp) = data.expected_hashboards {
|
if let Some(exp) = data.expected_hashboards {
|
||||||
while board_status.len() < exp as usize {
|
while board_status.len() < exp as usize {
|
||||||
|
|||||||
@@ -10,22 +10,88 @@
|
|||||||
//! Results stream back over a channel, drained by the UI timer tick exactly like
|
//! Results stream back over a channel, drained by the UI timer tick exactly like
|
||||||
//! restore.rs. The UI gates each behind a typed-FLASH confirmation.
|
//! restore.rs. The UI gates each behind a typed-FLASH confirmation.
|
||||||
|
|
||||||
|
use std::io::Read as _;
|
||||||
|
use std::net::TcpStream;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::mpsc::{channel, Receiver};
|
use std::sync::mpsc::{channel, Receiver, Sender};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use alkane_artifacts::afw::{verify_afw, VerifyOptions};
|
use alkane_artifacts::afw::{verify_afw, VerifyOptions};
|
||||||
use alkane_artifacts::fetch::{self, ReleaseSource};
|
use alkane_artifacts::fetch::{self, ReleaseSource};
|
||||||
use alkane_flash::stock::{self, RestoreImages};
|
use alkane_flash::stock::{self, RestoreImages};
|
||||||
|
|
||||||
|
/// Read the SSH identification banner (no auth) from `host:22`, e.g.
|
||||||
|
/// `SSH-2.0-dropbear_2026.93`.
|
||||||
|
fn ssh_banner(host: &str) -> Option<String> {
|
||||||
|
let addr: std::net::SocketAddr = format!("{host}:22").parse().ok()?;
|
||||||
|
let mut s = TcpStream::connect_timeout(&addr, Duration::from_secs(4)).ok()?;
|
||||||
|
s.set_read_timeout(Some(Duration::from_secs(4))).ok()?;
|
||||||
|
let mut buf = [0u8; 128];
|
||||||
|
let n = s.read(&mut buf).ok()?;
|
||||||
|
if n == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(
|
||||||
|
String::from_utf8_lossy(&buf[..n])
|
||||||
|
.lines()
|
||||||
|
.next()
|
||||||
|
.unwrap_or("")
|
||||||
|
.trim()
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a just-installed board's SSH banner looks like alkane. We installed
|
||||||
|
/// alkane to this specific board, so any SSH banner that is NOT the stock
|
||||||
|
/// Antminer dropbear (2018/2019) means our image booted. Alkane images ship a
|
||||||
|
/// current dropbear regardless of whether the image also serves the HTTP API, so
|
||||||
|
/// this verify works even for minimal images that do not serve `:80` (the
|
||||||
|
/// HTTP-only scan probe cannot see those).
|
||||||
|
fn banner_is_alkane(banner: &str) -> bool {
|
||||||
|
let b = banner.to_ascii_lowercase();
|
||||||
|
if b.contains("dropbear_2018") || b.contains("dropbear_2019") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
b.contains("dropbear") || b.contains("openssh")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poll a just-installed board until it comes up as alkane over SSH (not the
|
||||||
|
/// stock dropbear) or the deadline passes. Streams a progress line on success.
|
||||||
|
fn verify_alkane_live(ip: &str, tx: &Sender<StockMsg>, cancel: &AtomicBool) -> bool {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(150);
|
||||||
|
loop {
|
||||||
|
if cancel.load(Ordering::Relaxed) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if let Some(b) = ssh_banner(ip) {
|
||||||
|
if banner_is_alkane(&b) {
|
||||||
|
let _ = tx.send(StockMsg::Progress(format!(
|
||||||
|
"{ip}: alkane is live (ssh \"{b}\")"
|
||||||
|
)));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_secs(5));
|
||||||
|
}
|
||||||
|
}
|
||||||
use alkane_flash::stock_firmware;
|
use alkane_flash::stock_firmware;
|
||||||
|
|
||||||
use crate::scan::fake_scan_enabled;
|
use crate::scan::fake_scan_enabled;
|
||||||
|
|
||||||
/// Control boards alkane-os can be installed onto from stock (mirrors the CLI's
|
/// Control boards alkane-os can be installed onto from stock (mirrors the CLI's
|
||||||
/// `SUPPORTED`). Only these are offered as install targets.
|
/// `SUPPORTED`). Only these are offered as install targets.
|
||||||
pub const SUPPORTED_BOARDS: &[(&str, &str)] =
|
pub const SUPPORTED_BOARDS: &[(&str, &str)] = &[
|
||||||
&[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")];
|
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
|
||||||
|
(
|
||||||
|
"a113d",
|
||||||
|
"Antminer S19j Pro (Amlogic A113D/AXG control board)",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
/// The default install board when the user has not chosen another.
|
/// The default install board when the user has not chosen another.
|
||||||
pub const DEFAULT_BOARD: &str = "zynq-7010";
|
pub const DEFAULT_BOARD: &str = "zynq-7010";
|
||||||
@@ -34,12 +100,26 @@ pub fn is_supported_board(board: &str) -> bool {
|
|||||||
SUPPORTED_BOARDS.iter().any(|(b, _)| *b == board)
|
SUPPORTED_BOARDS.iter().any(|(b, _)| *b == board)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The release asset to install: its filename and download URL, resolved to a
|
/// Where the `.afw` to install comes from. `Release` is a scanned Gitea asset
|
||||||
/// local path on the worker thread so the download never blocks the UI. (Local-
|
/// (its filename and download URL), fetched on the worker thread so the download
|
||||||
/// file install is a CLI feature; the GUI installs from scanned releases.)
|
/// never blocks the UI. `Local` is a file the operator picked with the Browse
|
||||||
pub struct AfwChoice {
|
/// button -- the same local-file install the CLI offers, now in the GUI too.
|
||||||
pub name: String,
|
pub enum AfwSource {
|
||||||
pub url: String,
|
Release { name: String, url: String },
|
||||||
|
Local(PathBuf),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AfwSource {
|
||||||
|
/// A short human label for the status line (the filename in both cases).
|
||||||
|
fn label(&self) -> String {
|
||||||
|
match self {
|
||||||
|
AfwSource::Release { name, .. } => name.clone(),
|
||||||
|
AfwSource::Local(p) => p
|
||||||
|
.file_name()
|
||||||
|
.map(|n| n.to_string_lossy().into_owned())
|
||||||
|
.unwrap_or_else(|| p.to_string_lossy().into_owned()),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Progress + results streamed from the background worker to the UI.
|
/// Progress + results streamed from the background worker to the UI.
|
||||||
@@ -64,6 +144,12 @@ pub struct StockHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl StockHandle {
|
impl StockHandle {
|
||||||
|
/// Construct a handle around a worker's receiver and cancel flag. Used by
|
||||||
|
/// other op modules (e.g. `media_ops`) that reuse this streaming channel.
|
||||||
|
pub fn new(rx: Receiver<StockMsg>, cancel: Arc<AtomicBool>) -> StockHandle {
|
||||||
|
StockHandle { rx, cancel }
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn stop(&self) {
|
pub fn stop(&self) {
|
||||||
self.cancel.store(true, Ordering::Relaxed);
|
self.cancel.store(true, Ordering::Relaxed);
|
||||||
@@ -81,9 +167,10 @@ fn download_dir() -> PathBuf {
|
|||||||
pub fn start_install(
|
pub fn start_install(
|
||||||
ips: Vec<String>,
|
ips: Vec<String>,
|
||||||
board: String,
|
board: String,
|
||||||
source: AfwChoice,
|
source: AfwSource,
|
||||||
allow_unsigned: bool,
|
allow_unsigned: bool,
|
||||||
password: Option<String>,
|
password: Option<String>,
|
||||||
|
is_update: bool,
|
||||||
) -> StockHandle {
|
) -> StockHandle {
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
let cancel = Arc::new(AtomicBool::new(false));
|
let cancel = Arc::new(AtomicBool::new(false));
|
||||||
@@ -111,26 +198,51 @@ pub fn start_install(
|
|||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
let _ = tx.send(StockMsg::Started);
|
let _ = tx.send(StockMsg::Started);
|
||||||
|
|
||||||
// 1. Download the chosen release asset (on this worker thread).
|
// 1. Acquire the .afw: a local file is used in place; a release asset
|
||||||
let _ = tx.send(StockMsg::Progress("acquiring .afw...".into()));
|
// is downloaded on this worker thread (never blocking the UI).
|
||||||
let afw_path = match fetch::fetch_afw_url(
|
let afw_path = match source {
|
||||||
&ReleaseSource::alkane_os(),
|
AfwSource::Local(path) => {
|
||||||
&source.name,
|
let _ = tx.send(StockMsg::Progress(format!(
|
||||||
&source.url,
|
"using local {}...",
|
||||||
&download_dir(),
|
AfwSource::Local(path.clone()).label()
|
||||||
) {
|
)));
|
||||||
Ok(p) => p,
|
if !path.is_file() {
|
||||||
Err(e) => {
|
for ip in &ips {
|
||||||
// One failure line per target so the UI clears its op-status.
|
let _ = tx.send(StockMsg::Result {
|
||||||
for ip in &ips {
|
ip: ip.clone(),
|
||||||
let _ = tx.send(StockMsg::Result {
|
ok: false,
|
||||||
ip: ip.clone(),
|
detail: format!("local .afw not found: {}", path.display()),
|
||||||
ok: false,
|
});
|
||||||
detail: format!("could not fetch .afw: {e}"),
|
}
|
||||||
});
|
let _ = tx.send(StockMsg::Done);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
path
|
||||||
|
}
|
||||||
|
AfwSource::Release { name, url } => {
|
||||||
|
let _ = tx.send(StockMsg::Progress("acquiring .afw...".into()));
|
||||||
|
// Token attaches only for the trusted gitea host (see
|
||||||
|
// for_asset_url); never sent to a GitHub/other fork host.
|
||||||
|
match fetch::fetch_afw_url(
|
||||||
|
&ReleaseSource::for_asset_url(&url),
|
||||||
|
&name,
|
||||||
|
&url,
|
||||||
|
&download_dir(),
|
||||||
|
) {
|
||||||
|
Ok(p) => p,
|
||||||
|
Err(e) => {
|
||||||
|
// One failure line per target so the UI clears its op-status.
|
||||||
|
for ip in &ips {
|
||||||
|
let _ = tx.send(StockMsg::Result {
|
||||||
|
ip: ip.clone(),
|
||||||
|
ok: false,
|
||||||
|
detail: format!("could not fetch .afw: {e}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let _ = tx.send(StockMsg::Done);
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let _ = tx.send(StockMsg::Done);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -170,6 +282,22 @@ pub fn start_install(
|
|||||||
let _ = tx.send(StockMsg::Done);
|
let _ = tx.send(StockMsg::Done);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// An in-place Update must never rewrite the bootloader (review #1):
|
||||||
|
// refuse a tier-3 (bootloader-writing) bundle so the "BOOT.bin is
|
||||||
|
// never written" guarantee holds for an already-alkane board.
|
||||||
|
if is_update && verified.manifest.flash_plan().writes_uboot {
|
||||||
|
for ip in &ips {
|
||||||
|
let _ = tx.send(StockMsg::Result {
|
||||||
|
ip: ip.clone(),
|
||||||
|
ok: false,
|
||||||
|
detail: "update refused: this release reflashes the bootloader (tier 3); \
|
||||||
|
pick a tier-1/2 release or use Install"
|
||||||
|
.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let _ = tx.send(StockMsg::Done);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// 3. Install onto each board via the network-only from-stock method.
|
// 3. Install onto each board via the network-only from-stock method.
|
||||||
for ip in ips {
|
for ip in ips {
|
||||||
@@ -183,10 +311,26 @@ pub fn start_install(
|
|||||||
let (ok, detail) =
|
let (ok, detail) =
|
||||||
match stock::install_from_stock(&ip, &afw_path, &verified, password.as_deref())
|
match stock::install_from_stock(&ip, &afw_path, &verified, password.as_deref())
|
||||||
{
|
{
|
||||||
Ok(()) => (
|
Ok(()) => {
|
||||||
true,
|
// The write succeeded; now confirm the board rebooted
|
||||||
"installed alkane-os (verify liveness over the network)".to_string(),
|
// into alkane. Use the SSH banner (works even for
|
||||||
),
|
// images that do not serve the HTTP API) rather than
|
||||||
|
// only the HTTP scan probe.
|
||||||
|
let _ = tx.send(StockMsg::Progress(format!(
|
||||||
|
"{ip}: installed; awaiting reboot into alkane (up to 150s)..."
|
||||||
|
)));
|
||||||
|
if verify_alkane_live(&ip, &tx, &tc) {
|
||||||
|
(true, "installed; alkane is live (SSH-verified)".to_string())
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
true,
|
||||||
|
"installed; alkane not confirmed over SSH within the window -- \
|
||||||
|
check the board (a minimal image without the HTTP API still \
|
||||||
|
installs and boots; it just will not show in the scan)"
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
Err(e) => (false, format!("install failed: {e}")),
|
Err(e) => (false, format!("install failed: {e}")),
|
||||||
};
|
};
|
||||||
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
|
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
|
||||||
@@ -220,6 +364,7 @@ fn restore_one(ip: &str, firmware: &Path, password: Option<&str>) -> (bool, Stri
|
|||||||
let images = RestoreImages {
|
let images = RestoreImages {
|
||||||
kernel: &fw.kernel,
|
kernel: &fw.kernel,
|
||||||
rootfs: &fw.rootfs,
|
rootfs: &fw.rootfs,
|
||||||
|
dtb: fw.dtb.as_deref(),
|
||||||
};
|
};
|
||||||
match stock::restore_to_stock(ip, &images, password) {
|
match stock::restore_to_stock(ip, &images, password) {
|
||||||
Ok(()) => (
|
Ok(()) => (
|
||||||
@@ -282,3 +427,136 @@ pub fn start_restore(ips: Vec<String>, firmware: PathBuf, password: Option<Strin
|
|||||||
}
|
}
|
||||||
StockHandle { rx, cancel }
|
StockHandle { rx, cancel }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a board holds a restorable on-board stock backup (network probe). A
|
||||||
|
/// quick, synchronous check the restore dialog uses to grey out the on-board
|
||||||
|
/// option when no backup is present. Any error reads as "not present".
|
||||||
|
pub fn onboard_backup_present(ip: &str, password: Option<&str>) -> bool {
|
||||||
|
if fake_scan_enabled() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
stock::onboard_stock_backup_present(ip, password).unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restore the given alkane boards to genuine stock, over the network, from each
|
||||||
|
/// board's own on-board stock backup (no vendor firmware file). `password`, if
|
||||||
|
/// set, is the board's alkane root credential.
|
||||||
|
pub fn start_restore_onboard(ips: Vec<String>, password: Option<String>) -> StockHandle {
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
let cancel = Arc::new(AtomicBool::new(false));
|
||||||
|
|
||||||
|
if fake_scan_enabled() {
|
||||||
|
let _ = tx.send(StockMsg::Started);
|
||||||
|
for ip in ips {
|
||||||
|
let _ = tx.send(StockMsg::Result {
|
||||||
|
ip,
|
||||||
|
ok: true,
|
||||||
|
detail: "restored to stock from on-board backup (demo)".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let _ = tx.send(StockMsg::Done);
|
||||||
|
return StockHandle { rx, cancel };
|
||||||
|
}
|
||||||
|
|
||||||
|
let tc = cancel.clone();
|
||||||
|
let err_tx = tx.clone();
|
||||||
|
let spawned = std::thread::Builder::new()
|
||||||
|
.name("restore-onboard".into())
|
||||||
|
.spawn(move || {
|
||||||
|
let _ = tx.send(StockMsg::Started);
|
||||||
|
let timeout = std::time::Duration::from_secs(300);
|
||||||
|
for ip in ips {
|
||||||
|
if tc.load(Ordering::Relaxed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let _ = tx.send(StockMsg::Progress(format!(
|
||||||
|
"restoring {ip} to stock from its on-board backup..."
|
||||||
|
)));
|
||||||
|
let (ok, detail) =
|
||||||
|
match stock::restore_from_onboard_backup(&ip, password.as_deref(), timeout) {
|
||||||
|
Ok(()) => (
|
||||||
|
true,
|
||||||
|
"restored to stock from on-board backup (verify over the network)"
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
Err(e) => (false, format!("restore failed: {e}")),
|
||||||
|
};
|
||||||
|
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = tx.send(StockMsg::Done);
|
||||||
|
});
|
||||||
|
|
||||||
|
if spawned.is_err() {
|
||||||
|
let _ = err_tx.send(StockMsg::Result {
|
||||||
|
ip: String::new(),
|
||||||
|
ok: false,
|
||||||
|
detail: "could not start the restore worker thread".into(),
|
||||||
|
});
|
||||||
|
let _ = err_tx.send(StockMsg::Done);
|
||||||
|
}
|
||||||
|
StockHandle { rx, cancel }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Restore the given alkane A113D boards to genuine Bitmain stock, over the
|
||||||
|
/// network, by clearing the one-byte boot flag in-band from the running alkane
|
||||||
|
/// OS. The A113D install overwrites no stock partition, so this flag flip is the
|
||||||
|
/// complete restore: clear `ALAN`, reboot, and stock boots via `storeboot` from
|
||||||
|
/// the untouched `boot` MTD. No vendor firmware file or on-board backup needed.
|
||||||
|
/// `password`, if set, is the board's alkane root credential.
|
||||||
|
pub fn start_restore_flag(ips: Vec<String>, password: Option<String>) -> StockHandle {
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
let cancel = Arc::new(AtomicBool::new(false));
|
||||||
|
|
||||||
|
if fake_scan_enabled() {
|
||||||
|
let _ = tx.send(StockMsg::Started);
|
||||||
|
for ip in ips {
|
||||||
|
let _ = tx.send(StockMsg::Result {
|
||||||
|
ip,
|
||||||
|
ok: true,
|
||||||
|
detail: "restored to stock (flag flip, demo)".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let _ = tx.send(StockMsg::Done);
|
||||||
|
return StockHandle { rx, cancel };
|
||||||
|
}
|
||||||
|
|
||||||
|
let tc = cancel.clone();
|
||||||
|
let err_tx = tx.clone();
|
||||||
|
let spawned = std::thread::Builder::new()
|
||||||
|
.name("restore-flag".into())
|
||||||
|
.spawn(move || {
|
||||||
|
let _ = tx.send(StockMsg::Started);
|
||||||
|
for ip in ips {
|
||||||
|
if tc.load(Ordering::Relaxed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let _ = tx.send(StockMsg::Progress(format!(
|
||||||
|
"restoring {ip} to stock (clearing the alkane boot flag)..."
|
||||||
|
)));
|
||||||
|
let (ok, detail) = match stock::restore_aml_flag(&ip, password.as_deref()) {
|
||||||
|
Ok(()) => (
|
||||||
|
true,
|
||||||
|
"restored to stock (flag cleared, rebooting; verify over the network)"
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
Err(e) => (false, format!("restore failed: {e}")),
|
||||||
|
};
|
||||||
|
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = tx.send(StockMsg::Done);
|
||||||
|
});
|
||||||
|
|
||||||
|
if spawned.is_err() {
|
||||||
|
let _ = err_tx.send(StockMsg::Result {
|
||||||
|
ip: String::new(),
|
||||||
|
ok: false,
|
||||||
|
detail: "could not start the restore worker thread".into(),
|
||||||
|
});
|
||||||
|
let _ = err_tx.send(StockMsg::Done);
|
||||||
|
}
|
||||||
|
StockHandle { rx, cancel }
|
||||||
|
}
|
||||||
|
|||||||
+1048
-226
File diff suppressed because it is too large
Load Diff
+10
-5
@@ -1,5 +1,10 @@
|
|||||||
# Installing and removing alkane-os
|
# Installing and removing alkane-os
|
||||||
|
|
||||||
|
> For building bootable **SD installation media** (stock-recovery cards and
|
||||||
|
> alkane boot/installer cards) for card-bootable boards, see
|
||||||
|
> [installation-media.md](installation-media.md). That is a separate, physical
|
||||||
|
> path alongside the network-only install described here.
|
||||||
|
|
||||||
Two front-ends drive the same self-contained engine:
|
Two front-ends drive the same self-contained engine:
|
||||||
|
|
||||||
- The CLI (`alkane-cli afw ...`), documented below, is the scriptable path.
|
- The CLI (`alkane-cli afw ...`), documented below, is the scriptable path.
|
||||||
@@ -142,15 +147,15 @@ selected board:
|
|||||||
for; today the Zynq-7010 Antminer S17/S17 Pro/T17) that is not running Alkane
|
for; today the Zynq-7010 Antminer S17/S17 Pro/T17) that is not running Alkane
|
||||||
OS yet. Scans the alkane-os releases on Gitea, lets you pick one (newest first;
|
OS yet. Scans the alkane-os releases on Gitea, lets you pick one (newest first;
|
||||||
pre-releases are marked), optionally takes a board password and an "allow
|
pre-releases are marked), optionally takes a board password and an "allow
|
||||||
unsigned .afw (bench)" toggle, and - after you type FLASH to confirm -
|
unsigned .afw (bench)" toggle, then - when you click Install - downloads and
|
||||||
downloads/verifies the `.afw` and installs it onto each selected board over the
|
verifies the `.afw` and installs it onto each selected board over the network,
|
||||||
network, via the same compiled-in engine the CLI uses.
|
via the same compiled-in engine the CLI uses.
|
||||||
- "Update alkane OS..." - for a supported board already running Alkane OS: the
|
- "Update alkane OS..." - for a supported board already running Alkane OS: the
|
||||||
same release picker and confirmation; the board is updated in place (BOOT.bin
|
same release picker and confirmation; the board is updated in place (BOOT.bin
|
||||||
is never written).
|
is never written).
|
||||||
- "Uninstall alkane OS (restore to stock)..." - for a board running Alkane OS:
|
- "Uninstall alkane OS (restore to stock)..." - for a board running Alkane OS:
|
||||||
takes the board's alkane root password, a genuine Bitmain firmware package and
|
takes the board's alkane root password and a genuine Bitmain firmware package,
|
||||||
a typed FLASH confirmation, then restores each selected board to genuine stock
|
then - when you click Restore - restores each selected board to genuine stock
|
||||||
over the network.
|
over the network.
|
||||||
|
|
||||||
A stock board the scan identifies but cannot place on a supported control board
|
A stock board the scan identifies but cannot place on a supported control board
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# Installation Media (bootable SD cards)
|
||||||
|
|
||||||
|
The toolkit can build a **bootable SD/removable-media card** for control boards
|
||||||
|
that boot from a card. This is a separate, sanctioned path alongside the
|
||||||
|
network-only `.afw` install: the ordinary alkane install still runs over the
|
||||||
|
network from whatever OS the board has, and SD media exists for
|
||||||
|
|
||||||
|
- recovering a board to genuine stock, and
|
||||||
|
- bootstrapping or installing alkane onto a board through a card.
|
||||||
|
|
||||||
|
It is a **physical** path (insert a card, boot, remove), by design -- unlike the
|
||||||
|
network install, which needs no physical access.
|
||||||
|
|
||||||
|
## Which boards
|
||||||
|
|
||||||
|
SD media is offered only for boards whose bootrom / stock bootloader boots from a
|
||||||
|
card. Today that is the **Antminer S17 / Zynq-7010** control board, where the
|
||||||
|
stock U-Boot card-detects a plain FAT32 card and side-loads the card's boot trio
|
||||||
|
(confirmed on hardware: no boot-mode strap and no `uEnv.txt` needed, with the
|
||||||
|
stock bootloader intact). The Amlogic **A113D is excluded** -- it is eMMC-only
|
||||||
|
with no SD slot (USB recovery disabled), so it stays network-only.
|
||||||
|
|
||||||
|
## What you can build
|
||||||
|
|
||||||
|
| Kind | What it does |
|
||||||
|
|------|--------------|
|
||||||
|
| **Stock recovery** | Replicates a genuine Bitmain vendor SD-recovery package onto a card: boot it to write genuine stock back into NAND. You supply the vendor package. |
|
||||||
|
| **Alkane: run from SD** | Boots alkane from the card each power-on; nothing is written to the board. Good for a non-destructive try-out. |
|
||||||
|
| **Alkane: installer** | Boots an installer OS from the card that writes alkane into the board's own storage, verifies, and signals the red/green LEDs when done -- then you power off, remove the card, and boot internal alkane. |
|
||||||
|
|
||||||
|
The card is always built as an **image file first** (root-free), then written to
|
||||||
|
the device. The image is identical to what lands on the card, so it can be
|
||||||
|
inspected or kept.
|
||||||
|
|
||||||
|
## GUI
|
||||||
|
|
||||||
|
Scan the fleet, right-click a card-bootable board, and choose **Installation
|
||||||
|
Media (SD card)...**. Pick the kind, Browse to the source (an `.afw` for alkane,
|
||||||
|
or a genuine vendor package `.zip` for stock recovery), choose the target SD card
|
||||||
|
(or "build an image file only"), and click **Create**. Writing to a card erases
|
||||||
|
it entirely -- confirm the target device first.
|
||||||
|
|
||||||
|
## CLI
|
||||||
|
|
||||||
|
```
|
||||||
|
# Stock recovery card from a genuine vendor package:
|
||||||
|
alkane-cli afw make-media --kind stock \
|
||||||
|
--stock-package SD_S17.zip --out card.img \
|
||||||
|
[--write /dev/sdX --confirm WRITE]
|
||||||
|
|
||||||
|
# Alkane card from an .afw (simpleboot = run from SD, installer = flash to board):
|
||||||
|
alkane-cli afw make-media --kind alkane --mode installer \
|
||||||
|
--afw alkane-os-<ver>-zynq-7010.afw --allow-unsigned --out card.img \
|
||||||
|
[--write /dev/sdX --confirm WRITE]
|
||||||
|
```
|
||||||
|
|
||||||
|
Omit `--write` to build only the image file. Writing to a real device requires
|
||||||
|
`--confirm WRITE`. `--board` defaults to `zynq-7010` (the only supported board
|
||||||
|
for now).
|
||||||
|
|
||||||
|
## Safety notes
|
||||||
|
|
||||||
|
- **Writing a card erases the whole device.** The GUI device list shows only
|
||||||
|
removable disks and never a system disk, but always confirm the target.
|
||||||
|
- Stock recovery relies on the board's **existing stock bootloader** being
|
||||||
|
intact (it recovers broken userspace/kernel). If the bootloader itself were
|
||||||
|
wiped, a full card-boot path is needed instead -- a separate case.
|
||||||
|
- The alkane installer preserves the board's boot-critical regions (on Zynq,
|
||||||
|
`BOOT.bin` at `0x0..0x1a00000` is never written), mirroring the network
|
||||||
|
installer's guarantees.
|
||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
Subject: [PATCH 0010] svg_button: clickable SVG icon button for the toolbar
|
||||||
|
|
||||||
|
--- a/cpp_src/widgets_bridge.cpp
|
||||||
|
+++ b/cpp_src/widgets_bridge.cpp
|
||||||
|
@@ -2140,6 +2140,18 @@
|
||||||
|
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
|
||||||
|
}
|
||||||
|
|
||||||
|
+// Like wxbr_svg_icon, but a clickable button: render the (already-recoloured)
|
||||||
|
+// SVG into a w x h DIP bitmap bundle and wrap it in a wxBitmapButton that emits
|
||||||
|
+// WxEV_BUTTON_CLICKED with `id`. Used for the toolbar's icon buttons.
|
||||||
|
+void* wxbr_svg_button(void* parent, const char* svg, int id, int w, int h) {
|
||||||
|
+ wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
|
||||||
|
+ wxBitmapButton* btn = new wxBitmapButton((wxWindow*)parent, id, bundle);
|
||||||
|
+ btn->Bind(wxEVT_BUTTON, [id](wxCommandEvent&) {
|
||||||
|
+ if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
|
||||||
|
+ });
|
||||||
|
+ return (void*)btn;
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
|
||||||
|
// shape sentinel, so the SegmentRenderer can draw it recoloured to the cell's
|
||||||
|
// segment colour (round 12 #9 access padlocks, #11 status KPI icons). Replaces
|
||||||
|
--- a/src/widgets.rs
|
||||||
|
+++ b/src/widgets.rs
|
||||||
|
@@ -121,6 +121,13 @@
|
||||||
|
pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int);
|
||||||
|
pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
|
||||||
|
pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void;
|
||||||
|
+ pub fn wxbr_svg_button(
|
||||||
|
+ parent: *mut c_void,
|
||||||
|
+ svg: *const c_char,
|
||||||
|
+ id: c_int,
|
||||||
|
+ w: c_int,
|
||||||
|
+ h: c_int,
|
||||||
|
+ ) -> *mut c_void;
|
||||||
|
pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int);
|
||||||
|
pub fn wxbr_set_light_pulse(on: c_int);
|
||||||
|
pub fn wxbr_bind_sys_colour(win: *mut c_void);
|
||||||
|
@@ -949,6 +956,16 @@
|
||||||
|
Widget(unsafe { notsafe::wxbr_svg_icon(parent.0, c.as_ptr(), w as c_int, h as c_int) })
|
||||||
|
}
|
||||||
|
|
||||||
|
+ /// A clickable icon button: render the (already-recoloured) SVG into a
|
||||||
|
+ /// `w`x`h` DIP bitmap button that emits a button click with `id`. Recolour
|
||||||
|
+ /// the SVG first (explicit fill, not `currentColor`).
|
||||||
|
+ pub fn svg_button(parent: Widget, svg: &str, id: i32, w: i32, h: i32) -> Widget {
|
||||||
|
+ let c = CString::new(svg).unwrap_or_default();
|
||||||
|
+ Widget(unsafe {
|
||||||
|
+ notsafe::wxbr_svg_button(parent.0, c.as_ptr(), id as c_int, w as c_int, h as c_int)
|
||||||
|
+ })
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
/// Listen for OS light/dark theme changes on this window (emits `SysColour`).
|
||||||
|
pub fn bind_sys_colour(&self) {
|
||||||
|
unsafe { notsafe::wxbr_bind_sys_colour(self.0) }
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
Subject: [PATCH 0012] linux: word-wrapping multiline text control
|
||||||
|
|
||||||
|
--- a/cpp_src/widgets_bridge.cpp
|
||||||
|
+++ b/cpp_src/widgets_bridge.cpp
|
||||||
|
@@ -890,6 +890,15 @@
|
||||||
|
wxDefaultPosition, wxSize(-1, -1), style);
|
||||||
|
}
|
||||||
|
|
||||||
|
+// A multiline text control that word-wraps at the control's width instead of
|
||||||
|
+// scrolling horizontally (no wxTE_DONTWRAP). For prose entry such as the bug
|
||||||
|
+// report box, where long lines should wrap rather than run off the edge.
|
||||||
|
+void* wxbr_text_ctrl_wrap(void* parent) {
|
||||||
|
+ return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
|
||||||
|
+ wxDefaultPosition, wxSize(-1, -1),
|
||||||
|
+ wxTE_MULTILINE | wxTE_BESTWRAP);
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
// A single-line text control that masks its content (wxTE_PASSWORD), for secret
|
||||||
|
// entry so a saved password is never rendered in the clear (round 18 #12).
|
||||||
|
void* wxbr_text_ctrl_password(void* parent) {
|
||||||
|
--- a/src/widgets.rs
|
||||||
|
+++ b/src/widgets.rs
|
||||||
|
@@ -41,6 +41,7 @@
|
||||||
|
pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
|
||||||
|
pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
|
||||||
|
pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
|
||||||
|
+ pub fn wxbr_text_ctrl_wrap(parent: *mut c_void) -> *mut c_void;
|
||||||
|
pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void;
|
||||||
|
pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
|
||||||
|
pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
|
||||||
|
@@ -463,6 +464,12 @@
|
||||||
|
Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
|
||||||
|
}
|
||||||
|
|
||||||
|
+ /// A multiline text control that word-wraps at its width (no horizontal
|
||||||
|
+ /// scroll), for prose entry such as the bug-report box.
|
||||||
|
+ pub fn text_ctrl_wrapped(parent: Widget) -> Widget {
|
||||||
|
+ Widget(unsafe { notsafe::wxbr_text_ctrl_wrap(parent.0) })
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
/// A single-line text control that masks its content (for password entry).
|
||||||
|
pub fn password_ctrl(parent: Widget) -> Widget {
|
||||||
|
Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) })
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
Subject: [PATCH 0013] linux: Enable/disable (grey out) a control
|
||||||
|
|
||||||
|
--- a/cpp_src/widgets_bridge.cpp
|
||||||
|
+++ b/cpp_src/widgets_bridge.cpp
|
||||||
|
@@ -945,6 +945,11 @@
|
||||||
|
((wxCheckBox*)win)->SetValue(v != 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
+// Enable or disable (grey out) any window/control.
|
||||||
|
+void wxbr_enable(void* win, int on) {
|
||||||
|
+ ((wxWindow*)win)->Enable(on != 0);
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
// ---- check list box ---------------------------------------------------------
|
||||||
|
|
||||||
|
void* wxbr_check_list_box(void* parent) {
|
||||||
|
--- a/src/widgets.rs
|
||||||
|
+++ b/src/widgets.rs
|
||||||
|
@@ -49,6 +49,7 @@
|
||||||
|
pub fn wxbr_check_box(parent: *mut c_void, label: *const c_char) -> *mut c_void;
|
||||||
|
pub fn wxbr_check_box_get(win: *mut c_void) -> c_int;
|
||||||
|
pub fn wxbr_check_box_set(win: *mut c_void, v: c_int);
|
||||||
|
+ pub fn wxbr_enable(win: *mut c_void, on: c_int);
|
||||||
|
pub fn wxbr_check_list_box(parent: *mut c_void) -> *mut c_void;
|
||||||
|
pub fn wxbr_clb_append(win: *mut c_void, label: *const c_char);
|
||||||
|
pub fn wxbr_clb_clear(win: *mut c_void);
|
||||||
|
@@ -508,6 +509,11 @@
|
||||||
|
unsafe { notsafe::wxbr_check_box_set(self.0, v as c_int) }
|
||||||
|
}
|
||||||
|
|
||||||
|
+ /// Enable or disable (grey out) this control.
|
||||||
|
+ pub fn set_enabled(&self, on: bool) {
|
||||||
|
+ unsafe { notsafe::wxbr_enable(self.0, on as c_int) }
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
pub fn check_list_box(parent: Widget) -> Widget {
|
||||||
|
Widget(unsafe { notsafe::wxbr_check_list_box(parent.0) })
|
||||||
|
}
|
||||||
@@ -890,6 +890,15 @@ void* wxbr_text_ctrl(void* parent, int multiline) {
|
|||||||
wxDefaultPosition, wxSize(-1, -1), style);
|
wxDefaultPosition, wxSize(-1, -1), style);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A multiline text control that word-wraps at the control's width instead of
|
||||||
|
// scrolling horizontally (no wxTE_DONTWRAP). For prose entry such as the bug
|
||||||
|
// report box, where long lines should wrap rather than run off the edge.
|
||||||
|
void* wxbr_text_ctrl_wrap(void* parent) {
|
||||||
|
return (void*)new wxTextCtrl((wxWindow*)parent, wxID_ANY, wxT(""),
|
||||||
|
wxDefaultPosition, wxSize(-1, -1),
|
||||||
|
wxTE_MULTILINE | wxTE_BESTWRAP);
|
||||||
|
}
|
||||||
|
|
||||||
// A single-line text control that masks its content (wxTE_PASSWORD), for secret
|
// A single-line text control that masks its content (wxTE_PASSWORD), for secret
|
||||||
// entry so a saved password is never rendered in the clear (round 18 #12).
|
// entry so a saved password is never rendered in the clear (round 18 #12).
|
||||||
void* wxbr_text_ctrl_password(void* parent) {
|
void* wxbr_text_ctrl_password(void* parent) {
|
||||||
@@ -936,6 +945,11 @@ void wxbr_check_box_set(void* win, int v) {
|
|||||||
((wxCheckBox*)win)->SetValue(v != 0);
|
((wxCheckBox*)win)->SetValue(v != 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Enable or disable (grey out) any window/control.
|
||||||
|
void wxbr_enable(void* win, int on) {
|
||||||
|
((wxWindow*)win)->Enable(on != 0);
|
||||||
|
}
|
||||||
|
|
||||||
// ---- check list box ---------------------------------------------------------
|
// ---- check list box ---------------------------------------------------------
|
||||||
|
|
||||||
void* wxbr_check_list_box(void* parent) {
|
void* wxbr_check_list_box(void* parent) {
|
||||||
@@ -2126,6 +2140,18 @@ void* wxbr_svg_icon(void* parent, const char* svg, int w, int h) {
|
|||||||
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
|
return (void*)new wxStaticBitmap((wxWindow*)parent, wxID_ANY, bundle);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Like wxbr_svg_icon, but a clickable button: render the (already-recoloured)
|
||||||
|
// SVG into a w x h DIP bitmap bundle and wrap it in a wxBitmapButton that emits
|
||||||
|
// WxEV_BUTTON_CLICKED with `id`. Used for the toolbar's icon buttons.
|
||||||
|
void* wxbr_svg_button(void* parent, const char* svg, int id, int w, int h) {
|
||||||
|
wxBitmapBundle bundle = wxBitmapBundle::FromSVG(svg, wxSize(w, h));
|
||||||
|
wxBitmapButton* btn = new wxBitmapButton((wxWindow*)parent, id, bundle);
|
||||||
|
btn->Bind(wxEVT_BUTTON, [id](wxCommandEvent&) {
|
||||||
|
if (g_widget_event) g_widget_event(WxEV_BUTTON_CLICKED, id, 0);
|
||||||
|
});
|
||||||
|
return (void*)btn;
|
||||||
|
}
|
||||||
|
|
||||||
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
|
// Register a raw SVG (with its viewBox width/height for aspect) for a table-cell
|
||||||
// shape sentinel, so the SegmentRenderer can draw it recoloured to the cell's
|
// shape sentinel, so the SegmentRenderer can draw it recoloured to the cell's
|
||||||
// segment colour (round 12 #9 access padlocks, #11 status KPI icons). Replaces
|
// segment colour (round 12 #9 access padlocks, #11 status KPI icons). Replaces
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ mod notsafe {
|
|||||||
pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
|
pub fn wxbr_button(parent: *mut c_void, label: *const c_char, id: c_int) -> *mut c_void;
|
||||||
pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
|
pub fn wxbr_bind_click(win: *mut c_void, id: c_int);
|
||||||
pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
|
pub fn wxbr_text_ctrl(parent: *mut c_void, multiline: c_int) -> *mut c_void;
|
||||||
|
pub fn wxbr_text_ctrl_wrap(parent: *mut c_void) -> *mut c_void;
|
||||||
pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void;
|
pub fn wxbr_text_ctrl_password(parent: *mut c_void) -> *mut c_void;
|
||||||
pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
|
pub fn wxbr_text_ctrl_get(win: *mut c_void, buf: *mut c_char, cap: c_int) -> c_int;
|
||||||
pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
|
pub fn wxbr_text_ctrl_set(win: *mut c_void, value: *const c_char);
|
||||||
@@ -48,6 +49,7 @@ mod notsafe {
|
|||||||
pub fn wxbr_check_box(parent: *mut c_void, label: *const c_char) -> *mut c_void;
|
pub fn wxbr_check_box(parent: *mut c_void, label: *const c_char) -> *mut c_void;
|
||||||
pub fn wxbr_check_box_get(win: *mut c_void) -> c_int;
|
pub fn wxbr_check_box_get(win: *mut c_void) -> c_int;
|
||||||
pub fn wxbr_check_box_set(win: *mut c_void, v: c_int);
|
pub fn wxbr_check_box_set(win: *mut c_void, v: c_int);
|
||||||
|
pub fn wxbr_enable(win: *mut c_void, on: c_int);
|
||||||
pub fn wxbr_check_list_box(parent: *mut c_void) -> *mut c_void;
|
pub fn wxbr_check_list_box(parent: *mut c_void) -> *mut c_void;
|
||||||
pub fn wxbr_clb_append(win: *mut c_void, label: *const c_char);
|
pub fn wxbr_clb_append(win: *mut c_void, label: *const c_char);
|
||||||
pub fn wxbr_clb_clear(win: *mut c_void);
|
pub fn wxbr_clb_clear(win: *mut c_void);
|
||||||
@@ -119,6 +121,13 @@ mod notsafe {
|
|||||||
pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int);
|
pub fn wxbr_choice_set_selection(win: *mut c_void, i: c_int);
|
||||||
pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
|
pub fn wxbr_media_button(parent: *mut c_void, id: c_int, kind: c_int, r: c_int, g: c_int, b: c_int) -> *mut c_void;
|
||||||
pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void;
|
pub fn wxbr_svg_icon(parent: *mut c_void, svg: *const c_char, w: c_int, h: c_int) -> *mut c_void;
|
||||||
|
pub fn wxbr_svg_button(
|
||||||
|
parent: *mut c_void,
|
||||||
|
svg: *const c_char,
|
||||||
|
id: c_int,
|
||||||
|
w: c_int,
|
||||||
|
h: c_int,
|
||||||
|
) -> *mut c_void;
|
||||||
pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int);
|
pub fn wxbr_register_shape_svg(sentinel: c_int, svg: *const c_char, vbw: c_int, vbh: c_int);
|
||||||
pub fn wxbr_set_light_pulse(on: c_int);
|
pub fn wxbr_set_light_pulse(on: c_int);
|
||||||
pub fn wxbr_bind_sys_colour(win: *mut c_void);
|
pub fn wxbr_bind_sys_colour(win: *mut c_void);
|
||||||
@@ -463,6 +472,12 @@ impl Widget {
|
|||||||
Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
|
Widget(unsafe { notsafe::wxbr_text_ctrl(parent.0, multiline as c_int) })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A multiline text control that word-wraps at its width (no horizontal
|
||||||
|
/// scroll), for prose entry such as the bug-report box.
|
||||||
|
pub fn text_ctrl_wrapped(parent: Widget) -> Widget {
|
||||||
|
Widget(unsafe { notsafe::wxbr_text_ctrl_wrap(parent.0) })
|
||||||
|
}
|
||||||
|
|
||||||
/// A single-line text control that masks its content (for password entry).
|
/// A single-line text control that masks its content (for password entry).
|
||||||
pub fn password_ctrl(parent: Widget) -> Widget {
|
pub fn password_ctrl(parent: Widget) -> Widget {
|
||||||
Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) })
|
Widget(unsafe { notsafe::wxbr_text_ctrl_password(parent.0) })
|
||||||
@@ -501,6 +516,11 @@ impl Widget {
|
|||||||
unsafe { notsafe::wxbr_check_box_set(self.0, v as c_int) }
|
unsafe { notsafe::wxbr_check_box_set(self.0, v as c_int) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Enable or disable (grey out) this control.
|
||||||
|
pub fn set_enabled(&self, on: bool) {
|
||||||
|
unsafe { notsafe::wxbr_enable(self.0, on as c_int) }
|
||||||
|
}
|
||||||
|
|
||||||
pub fn check_list_box(parent: Widget) -> Widget {
|
pub fn check_list_box(parent: Widget) -> Widget {
|
||||||
Widget(unsafe { notsafe::wxbr_check_list_box(parent.0) })
|
Widget(unsafe { notsafe::wxbr_check_list_box(parent.0) })
|
||||||
}
|
}
|
||||||
@@ -936,6 +956,16 @@ impl Widget {
|
|||||||
Widget(unsafe { notsafe::wxbr_svg_icon(parent.0, c.as_ptr(), w as c_int, h as c_int) })
|
Widget(unsafe { notsafe::wxbr_svg_icon(parent.0, c.as_ptr(), w as c_int, h as c_int) })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A clickable icon button: render the (already-recoloured) SVG into a
|
||||||
|
/// `w`x`h` DIP bitmap button that emits a button click with `id`. Recolour
|
||||||
|
/// the SVG first (explicit fill, not `currentColor`).
|
||||||
|
pub fn svg_button(parent: Widget, svg: &str, id: i32, w: i32, h: i32) -> Widget {
|
||||||
|
let c = CString::new(svg).unwrap_or_default();
|
||||||
|
Widget(unsafe {
|
||||||
|
notsafe::wxbr_svg_button(parent.0, c.as_ptr(), id as c_int, w as c_int, h as c_int)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Listen for OS light/dark theme changes on this window (emits `SysColour`).
|
/// Listen for OS light/dark theme changes on this window (emits `SysColour`).
|
||||||
pub fn bind_sys_colour(&self) {
|
pub fn bind_sys_colour(&self) {
|
||||||
unsafe { notsafe::wxbr_bind_sys_colour(self.0) }
|
unsafe { notsafe::wxbr_bind_sys_colour(self.0) }
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ services:
|
|||||||
GITEA_URL: http://gitea:3000
|
GITEA_URL: http://gitea:3000
|
||||||
GITEA_REPO: blueflare/alkane-toolkit
|
GITEA_REPO: blueflare/alkane-toolkit
|
||||||
GITEA_TOKEN_FILE: /run/secrets/gitea_token
|
GITEA_TOKEN_FILE: /run/secrets/gitea_token
|
||||||
RATE_PER_IP: "5"
|
RATE_PER_IP: "100"
|
||||||
RATE_GLOBAL: "60"
|
RATE_GLOBAL: "300"
|
||||||
volumes:
|
volumes:
|
||||||
- ./secrets/gitea_token:/run/secrets/gitea_token:ro
|
- ./secrets/gitea_token:/run/secrets/gitea_token:ro
|
||||||
networks: [proxy]
|
networks: [proxy]
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import json
|
|||||||
import pathlib
|
import pathlib
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
import urllib.error
|
import urllib.error
|
||||||
import urllib.request
|
import urllib.request
|
||||||
@@ -16,6 +17,12 @@ import relay # noqa: E402
|
|||||||
|
|
||||||
TOKEN = "test-token-123"
|
TOKEN = "test-token-123"
|
||||||
|
|
||||||
|
# The repository's labels, as the real Gitea /labels endpoint would return them.
|
||||||
|
# The mock serves these, and setUp seeds the relay client's label cache from the
|
||||||
|
# same list so label resolution is deterministic (see RelayTests.setUp).
|
||||||
|
REPO_LABELS = [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
|
||||||
|
{"name": "feature", "id": 3}, {"name": "from-app", "id": 9}]
|
||||||
|
|
||||||
|
|
||||||
class FakeGitea:
|
class FakeGitea:
|
||||||
"""Records issue creations; serves the repository's labels."""
|
"""Records issue creations; serves the repository's labels."""
|
||||||
@@ -40,9 +47,7 @@ class FakeGitea:
|
|||||||
def do_GET(self):
|
def do_GET(self):
|
||||||
assert self.headers["Authorization"] == f"token {TOKEN}"
|
assert self.headers["Authorization"] == f"token {TOKEN}"
|
||||||
if self.path.startswith("/api/v1/repos/blueflare/alkane-toolkit/labels"):
|
if self.path.startswith("/api/v1/repos/blueflare/alkane-toolkit/labels"):
|
||||||
return self._json(200, [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
|
return self._json(200, REPO_LABELS)
|
||||||
{"name": "feature", "id": 3},
|
|
||||||
{"name": "from-app", "id": 9}])
|
|
||||||
self._json(404, {})
|
self._json(404, {})
|
||||||
|
|
||||||
def do_POST(self):
|
def do_POST(self):
|
||||||
@@ -58,6 +63,23 @@ class FakeGitea:
|
|||||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||||
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||||
|
# Block until the serve_forever thread is actually handling requests, so
|
||||||
|
# the relay's first label fetch cannot race server startup. The socket
|
||||||
|
# listens from __init__, but under load the daemon thread can be starved
|
||||||
|
# past the relay's HTTP timeout, which silently drops labels to [] and
|
||||||
|
# made the first test flaky in CI.
|
||||||
|
probe = urllib.request.Request(
|
||||||
|
self.url + "/api/v1/repos/blueflare/alkane-toolkit/labels",
|
||||||
|
headers={"Authorization": f"token {TOKEN}"})
|
||||||
|
deadline = time.monotonic() + 5
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
urllib.request.urlopen(probe, timeout=1).read()
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
if time.monotonic() >= deadline:
|
||||||
|
raise
|
||||||
|
time.sleep(0.02)
|
||||||
|
|
||||||
def close(self):
|
def close(self):
|
||||||
self.server.shutdown()
|
self.server.shutdown()
|
||||||
@@ -70,8 +92,18 @@ class RelayTests(unittest.TestCase):
|
|||||||
self.now = [1000.0]
|
self.now = [1000.0]
|
||||||
self.limiter = relay.RateLimiter(2, 3, clock=lambda: self.now[0])
|
self.limiter = relay.RateLimiter(2, 3, clock=lambda: self.now[0])
|
||||||
self.logs = []
|
self.logs = []
|
||||||
r = relay.Relay(relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN),
|
client = relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN)
|
||||||
self.limiter, log=self.logs.append)
|
# Seed the relay client's label cache directly from REPO_LABELS instead
|
||||||
|
# of letting a request handler fetch it live. Gitea.label_ids() caches
|
||||||
|
# for 10 minutes and silently falls back to [] on any fetch error; in CI
|
||||||
|
# that first live GET -- a second server-to-server hop made from inside
|
||||||
|
# the relay's own request thread -- failed reliably and dropped the
|
||||||
|
# labels to [], while the issue-filing POST on the same path still
|
||||||
|
# worked. Seeding the cache keeps label resolution deterministic (the
|
||||||
|
# name->id mapping is still exercised) and leaves the issue POST live.
|
||||||
|
client.labels = {label["name"]: label["id"] for label in REPO_LABELS}
|
||||||
|
client.labels_at = time.monotonic()
|
||||||
|
r = relay.Relay(client, self.limiter, log=self.logs.append)
|
||||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), relay.make_handler(r))
|
self.server = ThreadingHTTPServer(("127.0.0.1", 0), relay.make_handler(r))
|
||||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||||
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||||
|
|||||||
Reference in New Issue
Block a user