Compare commits

...
2 Commits
Author SHA1 Message Date
noahandClaude Opus 4.8 408b7d12b4 GUI: real access/lock-state detection via credentialed digest probe
asic-rs has no lock-state signal (a wrong-password miner just silently returns
fewer fields, because the collector drops the 401). This builds the real check
ON TOP of asic-rs:

- access_probe.rs: a NON-mutating, digest-authenticated GET to a privileged
  endpoint (Antminer get_miner_conf.cgi, read-only). The HTTP status is decisive
  -- 200 = credentials authenticate (writable -> unlocked), 401/403 = rejected
  (view-only -> locked); anything else -> indeterminate. Pure classifier +
  unit tests; shells out to curl --digest (no HTTP crate) so the offline build
  is unaffected.
- Right-click "Check access (auth)" on the selected miners runs start_access_probe
  on a background thread using the saved scan (web) credentials (default root/root),
  updating write_locked in the rows as results arrive. Fake-scan mode returns
  deterministic demo results. Guarded against a flash / concurrent probe.

Replaces the previous capability-based inference for the miners the user
explicitly checks. cargo check --release --tests clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-18 10:32:44 -06:00
noahandClaude Opus 4.8 50cd463bee GUI fix: guard out-of-range dvlc GetItem (crash selecting rows after refresh)
Round-9 #10: selecting miners could trip
`datavcmn.cpp: assert "row < m_hash.GetCount()" failed in GetItem(): invalid
index` and crash. wxDataViewIndexListModel::GetItem() asserts on an out-of-range
row, and three bridge helpers called it with an index that can go stale when the
row set shrinks (a filter, or a scan that returns fewer rows): wxbr_dvlc_
ensure_visible (the round-8 scroll-hold, unguarded), wxbr_dvlc_select_rows and
wxbr_dvlc_select_row (only lower-bounded). All three now bound the row against
the store's item count before calling GetItem, so a stale/empty index is a
no-op instead of a crash.

Local wx-rs bridge compile clean; patch 0003 regenerated + validated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y8h447BPyJR4fioYZvQ9bh
2026-09-18 10:29:14 -06:00
6 changed files with 296 additions and 7 deletions
+115
View File
@@ -0,0 +1,115 @@
//! Real access / lock-state detection: whether this miner accepts privileged
//! (credentialed) command writes, or is view-only.
//!
//! asic-rs has no lock-state signal (a wrong-password miner just silently
//! returns fewer fields, because the collector drops the 401). We build the real
//! check ON TOP of asic-rs: a NON-mutating, digest-authenticated GET to a
//! privileged endpoint. On Antminer every `/cgi-bin/*.cgi` requires digest auth,
//! so the HTTP status is decisive -- 200 means our credentials authenticate
//! (we can write -> unlocked), 401/403 means they are rejected (view-only ->
//! locked). We probe `get_miner_conf.cgi`, which is read-only (never the
//! mutating `set_miner_conf.cgi`).
//!
//! We shell out to `curl --digest` (already present, supports digest auth)
//! rather than add an HTTP+digest crate, so the offline/vendored build is
//! unaffected. `Some(true)` = locked, `Some(false)` = unlocked, `None` =
//! indeterminate (unreachable, or an endpoint/vendor this probe doesn't cover).
use std::process::Command;
use std::time::Duration;
/// Classify a miner's access state from an HTTP status code string (curl's
/// `%{http_code}` output). Conservative: anything other than a clear
/// authenticated/unauthorized answer is `None`.
pub fn classify_http_code(code: &str) -> Option<bool> {
match code.trim() {
"200" | "204" => Some(false), // authenticated -> unlocked/writable
"401" | "403" => Some(true), // rejected -> locked/view-only
_ => None, // 000 (no connect), 404, 5xx, ... -> unknown
}
}
/// The privileged, read-only endpoint we probe per firmware family. Antminer
/// stock/aftermarket all gate `get_miner_conf.cgi` behind digest auth.
fn endpoint(_firmware: &str) -> &'static str {
"/cgi-bin/get_miner_conf.cgi"
}
/// Probe one miner's access state over its web API with the given credentials.
/// Returns `Ok(Some(true/false))` on a decisive lock/unlock answer, `Ok(None)`
/// if reachable-but-indeterminate or a vendor this probe doesn't cover, or
/// `Err` only on a failure to run curl at all.
pub fn probe_access(ip: &str, firmware: &str, user: &str, pass: &str) -> Result<Option<bool>, String> {
let url = format!("http://{ip}{}", endpoint(firmware));
let userpass = format!("{user}:{pass}");
let mut cmd = Command::new("curl");
cmd.args([
"-s",
"-o",
"/dev/null",
"-w",
"%{http_code}",
"--digest",
"-u",
&userpass,
"--connect-timeout",
"5",
"--max-time",
"9",
&url,
]);
let out = wait_with_timeout(cmd, Duration::from_secs(12))?;
// curl prints the status code to stdout regardless of exit status (000 on a
// connection failure), so classify the code rather than the exit status.
let code = String::from_utf8_lossy(&out.stdout);
Ok(classify_http_code(&code))
}
/// Run a command with a wall-clock timeout (curl can hang past --max-time on a
/// black-holed host).
fn wait_with_timeout(mut cmd: Command, timeout: Duration) -> Result<std::process::Output, String> {
use std::io::Read;
cmd.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
let mut child = cmd.spawn().map_err(|e| format!("spawn curl: {e}"))?;
let start = std::time::Instant::now();
loop {
match child.try_wait().map_err(|e| e.to_string())? {
Some(status) => {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
if let Some(mut o) = child.stdout.take() {
let _ = o.read_to_end(&mut stdout);
}
if let Some(mut e) = child.stderr.take() {
let _ = e.read_to_end(&mut stderr);
}
return Ok(std::process::Output { status, stdout, stderr });
}
None => {
if start.elapsed() >= timeout {
let _ = child.kill();
return Err("curl timed out".into());
}
std::thread::sleep(Duration::from_millis(100));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classify_codes() {
assert_eq!(classify_http_code("200"), Some(false), "authenticated -> unlocked");
assert_eq!(classify_http_code("204"), Some(false));
assert_eq!(classify_http_code("401"), Some(true), "unauthorized -> locked");
assert_eq!(classify_http_code("403"), Some(true));
assert_eq!(classify_http_code("000"), None, "no connection -> unknown");
assert_eq!(classify_http_code("404"), None, "endpoint absent -> unknown");
assert_eq!(classify_http_code("500"), None);
assert_eq!(classify_http_code(" 200 "), Some(false), "whitespace tolerated");
assert_eq!(classify_http_code(""), None);
}
}
+1
View File
@@ -1,6 +1,7 @@
//! alkane-toolkit — primary view (docs/UI-SPEC.md).
//! Pure-Rust wxWidgets app on the vendored, patched wx-rs.
mod access_probe;
mod credentials;
mod fixtures;
mod model;
+78
View File
@@ -988,6 +988,84 @@ pub fn start_pic_probe(
PicProbeHandle { rx, cancel }
}
/// Progress/results from a background access (lock-state) probe.
pub enum AccessProbeMsg {
Started { total: usize },
/// `locked` = Some(true) locked/view-only, Some(false) unlocked/writable,
/// None indeterminate; `error` set only when the probe couldn't run.
Result { ip: String, locked: Option<bool>, error: Option<String> },
Done { total: usize },
}
/// A running access probe; `stop` cancels the remaining miners.
pub struct AccessProbeHandle {
pub rx: Receiver<AccessProbeMsg>,
cancel: Arc<AtomicBool>,
}
impl AccessProbeHandle {
pub fn stop(&self) {
self.cancel.store(true, Ordering::Relaxed);
}
}
/// Probe the access/lock state of `targets` (ip + firmware string) over the web
/// API with `creds` (user, pass), on a background thread. A digest-auth GET is
/// fast, but we still run one miner at a time with cancel-between. Fake-scan mode
/// returns deterministic demo results.
pub fn start_access_probe(
targets: Vec<(String, String)>,
creds: (String, String),
) -> AccessProbeHandle {
let (tx, rx) = channel();
let cancel = Arc::new(AtomicBool::new(false));
let total = targets.len();
let _ = tx.send(AccessProbeMsg::Started { total });
let (user, pass) = creds;
if fake_scan_enabled() {
let err_tx = tx.clone();
let thread_cancel = cancel.clone();
let res = std::thread::Builder::new().name("fake-access-probe".into()).spawn(move || {
for (ip, _fw) in targets {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
// Demo: the WardenOS-dev unit (.115) is locked, others unlocked.
let locked = Some(ip.ends_with(".115"));
let _ = tx.send(AccessProbeMsg::Result { ip, locked, error: None });
}
let _ = tx.send(AccessProbeMsg::Done { total });
});
if res.is_err() {
let _ = err_tx.send(AccessProbeMsg::Done { total });
}
return AccessProbeHandle { rx, cancel };
}
let thread_cancel = cancel.clone();
let err_tx = tx.clone();
let res = std::thread::Builder::new().name("access-probe".into()).spawn(move || {
for (ip, fw) in targets {
if thread_cancel.load(Ordering::Relaxed) {
break;
}
let (locked, error) = match crate::access_probe::probe_access(&ip, &fw, &user, &pass) {
Ok(v) => (v, None),
Err(e) => (None, Some(e)),
};
if tx.send(AccessProbeMsg::Result { ip, locked, error }).is_err() {
return; // UI gone
}
}
let _ = tx.send(AccessProbeMsg::Done { total });
});
if res.is_err() {
let _ = err_tx.send(AccessProbeMsg::Done { total });
}
AccessProbeHandle { rx, cancel }
}
#[cfg(test)]
mod tests {
use super::*;
+87 -2
View File
@@ -53,6 +53,7 @@ const ID_CTX_TUNING: i32 = 727;
const ID_CTX_POWER: i32 = 728;
const ID_CTX_RESTART: i32 = 729;
const ID_CTX_PIC_PROBE: i32 = 730;
const ID_CTX_ACCESS_PROBE: i32 = 731;
// SSH PIC-probe credentials dialog.
const ID_PICSSH_OK: i32 = 780;
const ID_PICSSH_CANCEL: i32 = 781;
@@ -348,6 +349,8 @@ pub struct App {
creds_dialog: Widget,
creds_user_input: Widget,
creds_pass_input: Widget,
// Background access (lock-state) probe.
access_probe: Option<scan::AccessProbeHandle>,
// Background SSH PIC probe + its credentials dialog.
pic_probe: Option<scan::PicProbeHandle>,
pending_pic_targets: Vec<(String, String)>,
@@ -546,6 +549,7 @@ pub fn build(frame: Widget) -> App {
creds_dialog: frame,
creds_user_input: frame,
creds_pass_input: frame,
access_probe: None,
pic_probe: None,
pending_pic_targets: Vec::new(),
picssh_dialog: frame,
@@ -833,6 +837,9 @@ impl App {
// Real PIC-vs-noPIC detection via an on-board SSH i2c probe (asic-rs
// cannot report it over the network); offered for any selection.
menu.menu_append(ID_CTX_PIC_PROBE, "Detect PIC (SSH)...");
// Real access/lock-state check (credentialed digest GET; uses the saved
// scan credentials).
menu.menu_append(ID_CTX_ACCESS_PROBE, "Check access (auth)");
// Config actions common to the whole selection (capability
// intersection): an action is offered only if every selected miner
// supports it.
@@ -1018,6 +1025,82 @@ impl App {
wx_rs::set_status_text(&format!("probing PIC on {n} miner(s) via SSH..."));
}
/// Start the access (lock-state) probe on the selected miners, using the
/// saved scan (web) credentials (defaulting to root/root if none are set).
fn start_access_probe(&mut self) {
if self.flashing {
wx_rs::set_status_text("firmware flash in progress -- wait for it to finish");
return;
}
if self.access_probe.is_some() {
wx_rs::set_status_text("an access check is already running");
return;
}
let targets: Vec<(String, String)> = self
.selected_rows()
.iter()
.map(|r| (r.ip.clone(), r.firmware.clone()))
.collect();
if targets.is_empty() {
return;
}
let creds = credentials::load_credentials().unwrap_or_else(|| ("root".into(), "root".into()));
let n = targets.len();
self.access_probe = Some(scan::start_access_probe(targets, creds));
wx_rs::set_status_text(&format!("checking access on {n} miner(s)..."));
}
/// Drain the running access probe: update each miner's write_locked as its
/// result arrives, and refresh the table + status when done.
fn drain_access_probe(&mut self) {
let Some(h) = &self.access_probe else { return };
let mut status: Option<String> = None;
let mut done = false;
let mut changed = false;
loop {
match h.rx.try_recv() {
Ok(scan::AccessProbeMsg::Started { total }) => {
status = Some(format!("access check: 0/{total}..."));
}
Ok(scan::AccessProbeMsg::Result { ip, locked, error }) => {
if let Some(r) = self.rows.iter_mut().find(|r| r.ip == ip) {
if error.is_none() {
r.write_locked = locked;
changed = true;
}
}
status = Some(match (&locked, &error) {
(_, Some(e)) => format!("access {ip}: {e}"),
(Some(true), _) => format!("access {ip}: locked"),
(Some(false), _) => format!("access {ip}: unlocked"),
(None, _) => format!("access {ip}: indeterminate"),
});
}
Ok(scan::AccessProbeMsg::Done { total }) => {
status = Some(format!("access check done ({total} miner(s))"));
done = true;
break;
}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
done = true;
break;
}
}
}
if changed {
self.fill_rows();
}
if done {
self.access_probe = None;
self.action_result = status.clone();
self.action_result_ticks = ACTION_RESULT_TICKS;
}
if let Some(s) = status {
wx_rs::set_status_text(&s);
}
}
/// Drain the running PIC probe: update each miner's pic_present as its result
/// arrives, and refresh the table + status when done.
fn drain_pic_probe(&mut self) {
@@ -1083,6 +1166,7 @@ impl App {
}
ID_CTX_REFRESH => self.start_refresh(self.selected_ip_list()),
ID_CTX_PIC_PROBE => return self.build_pic_probe_dialog(),
ID_CTX_ACCESS_PROBE => self.start_access_probe(),
ID_CTX_FLASH => {
// A flash needs exclusive hardware access; don't even prompt if
// any scan / refresh / action is running (re-checked at confirm).
@@ -1563,11 +1647,12 @@ impl App {
self.drain_action();
self.drain_refresh();
self.drain_pic_probe();
self.drain_access_probe();
if self.scanning {
return; // status already shows scan progress
}
if self.pic_probe.is_some() {
return; // a PIC probe is in flight; keep its status
if self.pic_probe.is_some() || self.access_probe.is_some() {
return; // a probe is in flight; keep its status
}
if self.action.is_some() {
return; // a config action is in flight; keep its status
+8 -3
View File
@@ -1,6 +1,6 @@
--- a/cpp_src/widgets_bridge.cpp
+++ b/cpp_src/widgets_bridge.cpp
@@ -0,0 +1,1059 @@
@@ -0,0 +1,1064 @@
+// widgets_bridge.cpp — alkane-toolkit extension to wx-rs
+// Adds the widget/event surface the toolkit UI needs on top of the upstream
+// render-callback bridge (which is kept untouched).
@@ -701,9 +701,11 @@
+}
+
+// Scroll so `row` is visible (used with wxbr_dvlc_get_top_row to restore the
+// scroll position after a refill). Out-of-range rows are ignored.
+// scroll position after a refill). Out-of-range rows are ignored -- GetItem()
+// itself asserts on row >= count, so the bound MUST be checked before calling.
+void wxbr_dvlc_ensure_visible(void* win, unsigned row) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ if (row >= (unsigned)dvlc_store(win)->GetItemCount()) return;
+ wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
+ if (item.IsOk()) dv->EnsureVisible(item);
+}
@@ -806,9 +808,11 @@
+void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
+ int count = (int)dvlc_store(win)->GetItemCount();
+ dv->UnselectAll();
+ for (int i = 0; i < n; i++) {
+ if (rows[i] >= 0) dv->Select(m->GetItem((unsigned)rows[i]));
+ // GetItem() asserts on an out-of-range row, so bound both ends.
+ if (rows[i] >= 0 && rows[i] < count) dv->Select(m->GetItem((unsigned)rows[i]));
+ }
+}
+
@@ -827,6 +831,7 @@
+ if (row < 0) return;
+ wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
+ wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
+ if (row >= (long)dvlc_store(win)->GetItemCount()) return;
+ dv->Select(m->GetItem((unsigned)row));
+}
+
@@ -698,9 +698,11 @@ int wxbr_dvlc_get_top_row(void* win) {
}
// Scroll so `row` is visible (used with wxbr_dvlc_get_top_row to restore the
// scroll position after a refill). Out-of-range rows are ignored.
// scroll position after a refill). Out-of-range rows are ignored -- GetItem()
// itself asserts on row >= count, so the bound MUST be checked before calling.
void wxbr_dvlc_ensure_visible(void* win, unsigned row) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
if (row >= (unsigned)dvlc_store(win)->GetItemCount()) return;
wxDataViewItem item = ((wxDataViewIndexListModel*)dv->GetModel())->GetItem(row);
if (item.IsOk()) dv->EnsureVisible(item);
}
@@ -803,9 +805,11 @@ int wxbr_dvlc_get_selections(void* win, int* buf, int cap) {
void wxbr_dvlc_select_rows(void* win, const int* rows, int n) {
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
int count = (int)dvlc_store(win)->GetItemCount();
dv->UnselectAll();
for (int i = 0; i < n; i++) {
if (rows[i] >= 0) dv->Select(m->GetItem((unsigned)rows[i]));
// GetItem() asserts on an out-of-range row, so bound both ends.
if (rows[i] >= 0 && rows[i] < count) dv->Select(m->GetItem((unsigned)rows[i]));
}
}
@@ -824,6 +828,7 @@ void wxbr_dvlc_select_row(void* win, long row) {
if (row < 0) return;
wxDataViewCtrl* dv = (wxDataViewCtrl*)win;
wxDataViewIndexListModel* m = (wxDataViewIndexListModel*)dv->GetModel();
if (row >= (long)dvlc_store(win)->GetItemCount()) return;
dv->Select(m->GetItem((unsigned)row));
}