//! Where the backend programs are. //! //! The service installs each into `bin\\` (the component manager); a program //! found there wins. Elsewhere (development on Linux) the one on PATH is taken. use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::time::SystemTime; pub struct Components { bin: PathBuf, /// Programs verified, by path, with the size and time they had then. verified: Mutex>, } impl Components { pub fn new(bin: PathBuf) -> Self { Self { bin, verified: Mutex::new(HashMap::new()) } } /// `find`, and for an installed one, the check that it is what was installed. pub fn program(&self, component: &str, name: &str) -> anyhow::Result { let path = self .find(component, name) .ok_or_else(|| anyhow::anyhow!("{component} is not installed (proxy-ctl components install {component})"))?; let dir = self.bin.join(component); if path.starts_with(&dir) { let meta = std::fs::metadata(&path)?; let stamp = (meta.len(), meta.modified()?); if self.verified.lock().unwrap().get(&path) != Some(&stamp) { crate::install::verify(&dir, &path)?; self.verified.lock().unwrap().insert(path.clone(), stamp); } } Ok(path) } /// The program `name` (without `.exe`) of `component`. On Windows only the protected /// `bin\` counts: what the service runs, it runs as SYSTEM, and PATH may hold a directory /// any user can write. pub fn find(&self, component: &str, name: &str) -> Option { let file = if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }; let installed = self.bin.join(component).join(&file); if installed.is_file() { return Some(installed); } if cfg!(windows) { return None; } // Development: the system's program of that name (a bundle's "tor/tor" is "tor"). let bare = std::path::Path::new(&file).file_name()?.to_owned(); let path = std::env::var_os("PATH")?; std::env::split_paths(&path).map(|dir| dir.join(&bare)).find(|p| p.is_file()) } pub fn sing_box(&self) -> anyhow::Result { self.program("sing-box", "sing-box") } pub fn xray(&self) -> anyhow::Result { self.program("xray", "xray") } #[allow(dead_code)] pub fn bin_dir(&self) -> &Path { &self.bin } }