//! The few places the toolkit's behaviour depends on the operating system, //! kept together so the rest of the code stays platform-neutral. //! //! - where per-user settings live ([`config_dir`]), //! - how a secret file is written so only its owner can read it //! ([`write_private`]), //! - the null device for tools that insist on an output path ([`NULL_DEVICE`]), //! - how helper programs (`ssh`, `curl`) are started from the GUI without a //! console window popping up on Windows ([`quiet_command`]). use std::path::{Path, PathBuf}; use std::process::Command; /// Directory name of the toolkit's settings under the per-user config root. pub const APP_DIR: &str = "alkane-toolkit"; /// Environment variable whose value is the per-user config root on this /// platform: `HOME` (settings in `$HOME/.config/alkane-toolkit`) on Unix, /// `APPDATA` (settings in `%APPDATA%\alkane-toolkit`) on Windows. Tests point it /// at a scratch directory. #[cfg(not(windows))] pub const CONFIG_ROOT_VAR: &str = "HOME"; #[cfg(windows)] pub const CONFIG_ROOT_VAR: &str = "APPDATA"; /// The per-user settings directory (not created here). /// /// Unix keeps the long-standing `$HOME/.config/alkane-toolkit`. Windows uses /// the roaming application-data folder, `%APPDATA%\alkane-toolkit`, which is /// where Windows applications keep per-user settings and which the user /// profile's ACL already restricts to its owner. A missing variable falls back /// to the working directory, as before. pub fn config_dir() -> PathBuf { let root = std::env::var_os(CONFIG_ROOT_VAR).unwrap_or_else(|| ".".into()); if cfg!(windows) { PathBuf::from(root).join(APP_DIR) } else { PathBuf::from(root).join(".config").join(APP_DIR) } } /// `config_dir()/file`. pub fn config_path(file: &str) -> PathBuf { config_dir().join(file) } /// The null device, for tools that want an output path (`curl -o`, /// `ssh -o UserKnownHostsFile=`). #[cfg(not(windows))] pub const NULL_DEVICE: &str = "/dev/null"; #[cfg(windows)] pub const NULL_DEVICE: &str = "NUL"; /// Write `data` to `path` so only the owner can read it. /// /// On Unix the file is created 0600 (so a secret is never momentarily /// world-readable between write and chmod), and a pre-existing file is /// re-tightened while it is still empty, before the plaintext is written. On /// Windows the settings directory inherits the user profile's owner-only ACL, /// so a plain write already has the equivalent protection. pub fn write_private(path: &Path, data: &[u8]) -> std::io::Result<()> { #[cfg(unix)] { use std::io::Write; use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; let mut f = std::fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .mode(0o600) .open(path)?; f.set_permissions(std::fs::Permissions::from_mode(0o600))?; f.write_all(data) } #[cfg(not(unix))] { std::fs::write(path, data) } } /// A [`Command`] for a helper program run in the background of the GUI. /// /// On Windows a console program (`ssh.exe`, `curl.exe`) started from a GUI /// process gets a new console window by default, so every probe would flash a /// black window; `CREATE_NO_WINDOW` suppresses that while keeping its piped /// stdin/stdout/stderr. Elsewhere this is `Command::new`. pub fn quiet_command(program: &str) -> Command { #[allow(unused_mut)] let mut command = Command::new(program); #[cfg(windows)] { use std::os::windows::process::CommandExt; const CREATE_NO_WINDOW: u32 = 0x0800_0000; command.creation_flags(CREATE_NO_WINDOW); } command } #[cfg(test)] mod tests { use super::*; #[test] fn config_dir_is_under_the_platform_root() { let dir = config_dir(); assert!(dir.ends_with(APP_DIR), "{dir:?}"); if cfg!(windows) { assert!(!dir.to_string_lossy().contains(".config"), "{dir:?}"); } else { assert!(dir.parent().unwrap().ends_with(".config"), "{dir:?}"); } assert_eq!(config_path("x.txt"), dir.join("x.txt")); } #[test] fn write_private_round_trips_and_restricts() { let dir = std::env::temp_dir().join(format!("alkane-private-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("secret.txt"); write_private(&path, b"one").unwrap(); write_private(&path, b"two").unwrap(); assert_eq!(std::fs::read(&path).unwrap(), b"two"); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; assert_eq!(mode, 0o600); } std::fs::remove_dir_all(&dir).unwrap(); } #[test] fn quiet_command_runs_with_piped_output() { // `cmd /C echo` and `sh -c echo` are the platform's own shells. let mut command = if cfg!(windows) { let mut c = quiet_command("cmd"); c.args(["/C", "echo alkane"]); c } else { let mut c = quiet_command("sh"); c.args(["-c", "echo alkane"]); c }; let out = command.output().unwrap(); assert!(out.status.success()); assert!(String::from_utf8_lossy(&out.stdout).contains("alkane")); } }