Skip to main content

blyte_cli/
surface_version.rs

1use std::fmt::Write as _;
2use std::path::{Path, PathBuf};
3use std::time::UNIX_EPOCH;
4
5use serde::{Deserialize, Serialize};
6
7pub const CURRENT_VERSION: &str =
8    concat!(env!("CARGO_PKG_VERSION"), " (", env!("BLYTE_BUILD"), ")");
9
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
11pub struct BinaryFingerprint {
12    pub path: PathBuf,
13    pub size: u64,
14    pub modified_secs: u64,
15    pub modified_nanos: u32,
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub inode: Option<u64>,
18}
19
20impl BinaryFingerprint {
21    pub fn current() -> Result<Self, String> {
22        let exe = std::env::current_exe()
23            .map_err(|e| format!("cannot locate running blyte binary: {e}"))?;
24        Self::from_path(&exe)
25    }
26
27    pub fn from_path(path: &Path) -> Result<Self, String> {
28        let meta = std::fs::metadata(path)
29            .map_err(|e| format!("cannot inspect blyte binary {}: {e}", path.display()))?;
30        if !meta.is_file() {
31            return Err(format!(
32                "blyte binary {} is not a regular file",
33                path.display()
34            ));
35        }
36        let modified = meta
37            .modified()
38            .map_err(|e| format!("cannot read mtime of blyte binary {}: {e}", path.display()))?;
39        let since_epoch = modified.duration_since(UNIX_EPOCH).map_err(|e| {
40            format!(
41                "mtime of blyte binary {} precedes Unix epoch: {e}",
42                path.display()
43            )
44        })?;
45        Ok(Self {
46            path: path.to_path_buf(),
47            size: meta.len(),
48            modified_secs: since_epoch.as_secs(),
49            modified_nanos: since_epoch.subsec_nanos(),
50            inode: file_inode(&meta),
51        })
52    }
53
54    pub fn is_stale(&self) -> Result<bool, String> {
55        let on_disk = Self::from_path(&self.path)?;
56        Ok(on_disk != *self)
57    }
58}
59
60#[cfg(unix)]
61fn file_inode(meta: &std::fs::Metadata) -> Option<u64> {
62    use std::os::unix::fs::MetadataExt;
63    Some(meta.ino())
64}
65
66#[cfg(not(unix))]
67fn file_inode(_meta: &std::fs::Metadata) -> Option<u64> {
68    None
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72pub struct SurfaceRuntimeInfo {
73    pub version: String,
74    pub binary_fingerprint: BinaryFingerprint,
75    pub boot_id: String,
76}
77
78impl SurfaceRuntimeInfo {
79    pub fn current() -> Result<Self, String> {
80        Ok(Self {
81            version: CURRENT_VERSION.to_string(),
82            binary_fingerprint: BinaryFingerprint::current()?,
83            boot_id: generate_boot_id()?,
84        })
85    }
86
87    pub fn from_binary(
88        version: impl Into<String>,
89        binary_path: &Path,
90        boot_id: impl Into<String>,
91    ) -> Result<Self, String> {
92        let version = version.into();
93        let boot_id = boot_id.into();
94        if version.trim().is_empty() {
95            return Err("surface version cannot be empty".to_string());
96        }
97        if boot_id.trim().is_empty() {
98            return Err("surface boot_id cannot be empty".to_string());
99        }
100        Ok(Self {
101            version,
102            binary_fingerprint: BinaryFingerprint::from_path(binary_path)?,
103            boot_id,
104        })
105    }
106
107    pub fn is_stale(&self) -> Result<bool, String> {
108        self.binary_fingerprint.is_stale()
109    }
110
111    pub fn verify_executable(&self) -> Result<(), String> {
112        verify_executable(&self.binary_fingerprint.path)
113    }
114
115    pub fn validate(&self) -> Result<(), String> {
116        if self.version.trim().is_empty() {
117            return Err("surface version cannot be empty".to_string());
118        }
119        if self.boot_id.trim().is_empty() {
120            return Err("surface boot_id cannot be empty".to_string());
121        }
122        if self.binary_fingerprint.path.as_os_str().is_empty() {
123            return Err("binary_fingerprint path cannot be empty".to_string());
124        }
125        Ok(())
126    }
127}
128
129#[cfg(unix)]
130pub fn generate_boot_id() -> Result<String, String> {
131    use std::io::Read;
132    let mut file = std::fs::File::open("/dev/urandom")
133        .map_err(|e| format!("cannot open /dev/urandom to generate boot_id: {e}"))?;
134    let mut bytes = [0u8; 16];
135    file.read_exact(&mut bytes)
136        .map_err(|e| format!("cannot read /dev/urandom to generate boot_id: {e}"))?;
137    Ok(hex_encode(&bytes))
138}
139
140#[cfg(not(unix))]
141pub fn generate_boot_id() -> Result<String, String> {
142    use sha2::{Digest, Sha256};
143    use std::sync::atomic::{AtomicU64, Ordering};
144    static COUNTER: AtomicU64 = AtomicU64::new(0);
145    let now = std::time::SystemTime::now()
146        .duration_since(UNIX_EPOCH)
147        .map_err(|e| format!("system clock error generating boot_id: {e}"))?;
148    let mut hasher = Sha256::new();
149    hasher.update(std::process::id().to_le_bytes());
150    hasher.update(now.as_nanos().to_le_bytes());
151    hasher.update(COUNTER.fetch_add(1, Ordering::Relaxed).to_le_bytes());
152    let digest = hasher.finalize();
153    Ok(hex_encode(&digest[..16]))
154}
155
156fn hex_encode(bytes: &[u8]) -> String {
157    let mut out = String::with_capacity(bytes.len() * 2);
158    for b in bytes {
159        let _ = write!(out, "{b:02x}");
160    }
161    out
162}
163
164pub fn verify_executable(path: &Path) -> Result<(), String> {
165    if path.as_os_str().is_empty() {
166        return Err("blyte binary path is empty".to_string());
167    }
168    let meta = std::fs::metadata(path).map_err(|e| match e.kind() {
169        std::io::ErrorKind::NotFound => format!("blyte binary not found at {}", path.display()),
170        _ => format!("cannot inspect blyte binary at {}: {e}", path.display()),
171    })?;
172    if !meta.is_file() {
173        return Err(format!(
174            "blyte binary at {} is not a regular file",
175            path.display()
176        ));
177    }
178    #[cfg(unix)]
179    {
180        use std::ffi::CString;
181        use std::os::unix::ffi::OsStrExt;
182        use std::os::unix::fs::PermissionsExt;
183        if meta.permissions().mode() & 0o111 == 0 {
184            return Err(format!(
185                "blyte binary at {} is not executable",
186                path.display()
187            ));
188        }
189        let cpath = CString::new(path.as_os_str().as_bytes())
190            .map_err(|_| format!("blyte binary path {} contains a NUL byte", path.display()))?;
191        if unsafe { libc::access(cpath.as_ptr(), libc::X_OK) } != 0 {
192            let err = std::io::Error::last_os_error();
193            return Err(format!(
194                "blyte binary at {} is not executable: {err}",
195                path.display()
196            ));
197        }
198    }
199    Ok(())
200}