hashglass 0.1.0

Fast pentester-focused hash identifier — mode + cost + ready hashcat command. Handles secretsdump / containers / mixed dumps. Identification only.
Documentation
//! Slice 13 — GPU auto-detect for cost calibration.
//!
//! Cost annotation was baseline-4090 in slice 6; the senior review flagged
//! that as ageing poorly on real rigs (3060 laptops crack ~4× slower; 8×A100
//! boxes crack much faster). This module probes `nvidia-smi` once per process,
//! classifies whatever it finds into a coarse tier, and returns a multiplier
//! that `cost.rs` applies to its published hashcat-benchmark numbers.
//!
//! Silent fail everywhere: no nvidia-smi, no CUDA, no GPU → we return
//! [`Tier::Baseline`] and cost output is unchanged. `HASHGLASS_GPU=off`
//! disables detection entirely (for pentester rigs that hate spawning
//! nvidia-smi on every run, and for deterministic tests / CI).
//!
//! This is a triage aid, not a benchmark. The tiers are 2× granular — anyone
//! wanting exact numbers should still run `hashcat -b`.

use std::process::Command;
use std::sync::OnceLock;
use std::time::Duration;

/// Coarse GPU class. `Baseline` matches slice 6's 4090-class numbers exactly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tier {
    /// A100/H100 datacenter or multi-4090 rig. ~2× the baseline.
    Datacenter,
    /// 4090 / 4080 / 3090 Ti — the class we originally calibrated for.
    Baseline,
    /// 3080 / 3070 / 4070 — mid-range consumer.
    Mid,
    /// 3060 / 2080 / 4060 laptop — entry-level or mobile.
    Low,
    /// No CUDA GPU (or `HASHGLASS_GPU=off`). Treat cost claims as "on a 4090";
    /// we don't downgrade because the user might be using a rented rig.
    Unknown,
}

impl Tier {
    /// Multiplier applied to slice-6 baseline hashes-per-second numbers.
    /// > 1.0 = faster than baseline; < 1.0 = slower.
    pub fn multiplier(self) -> f64 {
        match self {
            Tier::Datacenter => 2.0,
            Tier::Baseline => 1.0,
            Tier::Mid => 0.5,
            Tier::Low => 0.25,
            Tier::Unknown => 1.0,
        }
    }

    /// Human label for the cost oneliner suffix. Empty for `Unknown` — we
    /// don't print "on a 4090" when we don't know.
    pub fn label(self) -> &'static str {
        match self {
            Tier::Datacenter => "on a datacenter GPU",
            Tier::Baseline => "on a 4090-class GPU",
            Tier::Mid => "on a mid-range GPU (3080/4070)",
            Tier::Low => "on an entry GPU (3060/laptop)",
            Tier::Unknown => "on a 4090-class GPU (no local GPU detected)",
        }
    }
}

/// Classify a GPU name string. Case-insensitive substring match on the tail
/// end so "NVIDIA GeForce RTX 4090" and "GeForce RTX 4090 Laptop GPU" both
/// resolve. Order matters — longest / most-specific first.
pub fn classify(name: &str) -> Tier {
    let n = name.to_ascii_lowercase();
    // Laptop check FIRST — the "laptop" suffix on any Ada/Ampere part means
    // ~50% of the desktop card. "RTX 4090 Laptop GPU" is not a 4090.
    if n.contains("laptop") {
        return Tier::Low;
    }
    // Datacenter GPUs next (some contain "A100" as substring anywhere).
    if n.contains("a100") || n.contains("h100") || n.contains("h200") || n.contains("l40") {
        return Tier::Datacenter;
    }
    // Baseline — the 4090/4080/3090 line we calibrated slice-6 numbers on.
    if n.contains("4090") || n.contains("4080") || n.contains("3090") {
        return Tier::Baseline;
    }
    // Mid — 3080/3070/4070.
    if n.contains("3080") || n.contains("3070") || n.contains("4070") {
        return Tier::Mid;
    }
    // Low — desktop entry cards. Laptop was handled up top.
    if n.contains("3060")
        || n.contains("3050")
        || n.contains("2080")
        || n.contains("2070")
        || n.contains("2060")
        || n.contains("4060")
        || n.contains("4050")
    {
        return Tier::Low;
    }
    Tier::Unknown
}

fn probe_nvidia_smi() -> Option<String> {
    // 500ms hard cap — a slow nvidia-smi (driver bug, CUDA init hang) must
    // never delay hashglass output.
    let mut child = Command::new("nvidia-smi")
        .args(["--query-gpu=name", "--format=csv,noheader"])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .stdin(std::process::Stdio::null())
        .spawn()
        .ok()?;

    let start = std::time::Instant::now();
    loop {
        if let Some(status) = child.try_wait().ok().flatten() {
            if !status.success() {
                return None;
            }
            let output = child.wait_with_output().ok()?;
            let s = String::from_utf8_lossy(&output.stdout).trim().to_string();
            return if s.is_empty() { None } else { Some(s) };
        }
        if start.elapsed() > Duration::from_millis(500) {
            let _ = child.kill();
            return None;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
}

/// Path for the on-disk GPU probe cache. `~/.cache/hashglass/gpu` on Unix,
/// `%LOCALAPPDATA%\hashglass\gpu` on Windows. `None` if we can't figure out
/// a per-user writable directory.
fn cache_path() -> Option<std::path::PathBuf> {
    let base = if cfg!(windows) {
        std::env::var_os("LOCALAPPDATA").map(std::path::PathBuf::from)
    } else {
        std::env::var_os("XDG_CACHE_HOME")
            .map(std::path::PathBuf::from)
            .or_else(|| {
                std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".cache"))
            })
    }?;
    Some(base.join("hashglass").join("gpu"))
}

/// Read a cached GPU tier if the cache is fresh (<24h). Cache file format is
/// `<unix-epoch-secs>\n<tier-name>\n`. Any parse error or stale timestamp →
/// `None` (fall through to re-probe).
fn read_cache() -> Option<Tier> {
    let path = cache_path()?;
    let content = std::fs::read_to_string(&path).ok()?;
    let mut lines = content.lines();
    let ts: u64 = lines.next()?.parse().ok()?;
    let name = lines.next()?;
    let age = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .ok()?
        .as_secs()
        .saturating_sub(ts);
    if age > 86_400 {
        return None; // stale
    }
    Some(match name {
        "Datacenter" => Tier::Datacenter,
        "Baseline" => Tier::Baseline,
        "Mid" => Tier::Mid,
        "Low" => Tier::Low,
        "Unknown" => Tier::Unknown,
        _ => return None,
    })
}

/// Best-effort write to the cache. Silent-fail — a broken cache never affects
/// correctness, only causes a re-probe next run.
fn write_cache(tier: Tier) {
    let Some(path) = cache_path() else {
        return;
    };
    let Some(parent) = path.parent() else {
        return;
    };
    let _ = std::fs::create_dir_all(parent);
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let name = match tier {
        Tier::Datacenter => "Datacenter",
        Tier::Baseline => "Baseline",
        Tier::Mid => "Mid",
        Tier::Low => "Low",
        Tier::Unknown => "Unknown",
    };
    let _ = std::fs::write(&path, format!("{now}\n{name}\n"));
}

/// Detected tier, cached for the process AND persisted to disk with a 24h TTL.
/// First run of the day probes nvidia-smi (~50ms). All subsequent runs read a
/// tiny cache file (~0.1ms). This was the real cold-start bottleneck — probing
/// nvidia-smi on every single-hash CLI invocation cost 55ms out of 85ms total.
pub fn tier() -> Tier {
    static CACHED: OnceLock<Tier> = OnceLock::new();
    *CACHED.get_or_init(|| {
        if std::env::var_os("HASHGLASS_GPU").as_deref() == Some(std::ffi::OsStr::new("off")) {
            return Tier::Unknown;
        }
        // Fresh cache hit — skip the spawn entirely.
        if let Some(t) = read_cache() {
            return t;
        }
        // Multi-GPU: nvidia-smi prints one line per GPU. Pick the FIRST — most
        // rigs are homogeneous, and if they aren't the first is the most likely
        // primary. A pentester with mixed cards can set HASHGLASS_GPU=off.
        let t = match probe_nvidia_smi() {
            Some(out) => classify(out.lines().next().unwrap_or("")),
            None => Tier::Unknown,
        };
        write_cache(t);
        t
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classify_baseline_gpus() {
        assert_eq!(classify("NVIDIA GeForce RTX 4090"), Tier::Baseline);
        assert_eq!(classify("GeForce RTX 3090 Ti"), Tier::Baseline);
        assert_eq!(classify("NVIDIA GeForce RTX 4080 SUPER"), Tier::Baseline);
    }

    #[test]
    fn classify_datacenter_gpus() {
        assert_eq!(classify("NVIDIA A100-SXM4-80GB"), Tier::Datacenter);
        assert_eq!(classify("NVIDIA H100 PCIe"), Tier::Datacenter);
    }

    #[test]
    fn classify_mid_gpus() {
        assert_eq!(classify("NVIDIA GeForce RTX 3080"), Tier::Mid);
        assert_eq!(classify("NVIDIA GeForce RTX 4070"), Tier::Mid);
    }

    #[test]
    fn classify_low_and_laptop_gpus() {
        assert_eq!(classify("NVIDIA GeForce RTX 3060"), Tier::Low);
        // Laptop suffix downgrades everything — a "4090 Laptop GPU" is ~50%
        // of the desktop card.
        assert_eq!(classify("NVIDIA GeForce RTX 4090 Laptop GPU"), Tier::Low);
        assert_eq!(classify("NVIDIA GeForce RTX 2080"), Tier::Low);
    }

    #[test]
    fn classify_unknown_gpus() {
        assert_eq!(classify(""), Tier::Unknown);
        assert_eq!(classify("Intel Iris Xe"), Tier::Unknown);
        assert_eq!(classify("some future card"), Tier::Unknown);
    }

    #[test]
    fn multipliers_are_ordered() {
        assert!(Tier::Datacenter.multiplier() > Tier::Baseline.multiplier());
        assert!(Tier::Baseline.multiplier() > Tier::Mid.multiplier());
        assert!(Tier::Mid.multiplier() > Tier::Low.multiplier());
        assert_eq!(Tier::Unknown.multiplier(), Tier::Baseline.multiplier());
    }
}