//! Daemon configuration. //! //! Precedence: CLI flags > environment > config file > defaults. //! The daemon must run with an empty (or absent) config file. use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use serde::Deserialize; /// Fully resolved runtime configuration. #[derive(Debug, Clone)] pub struct Config { /// Directory holding the blob store, metadata and secret key. pub store_dir: PathBuf, /// Path of the unix socket to serve the API on. pub socket_path: PathBuf, /// Upload rate cap in bytes/sec. 0 disables serving entirely. pub max_upload_bytes_per_sec: u64, /// Download rate cap in bytes/sec. 0 means unlimited. pub max_download_bytes_per_sec: u64, /// Whether LAN discovery (mDNS-style) is enabled. pub discovery: bool, /// Whether any WAN (non-link-local) upload is permitted. Default off: /// LAN-only posture with zero WAN upload. pub wan_upload: bool, /// Interval of the store's built-in garbage collector in seconds. /// Since iroh-blobs 0.103 there is no on-demand gc; unpinned blobs /// are swept by this loop. pub gc_interval_secs: u64, } /// Serde image of the TOML config file. Everything optional so an empty /// file (or none at all) is valid. #[derive(Debug, Default, Deserialize)] #[serde(deny_unknown_fields)] struct FileConfig { store_dir: Option, socket_path: Option, max_upload_bytes_per_sec: Option, max_download_bytes_per_sec: Option, discovery: Option, wan_upload: Option, gc_interval_secs: Option, } /// Values collected from CLI flags; `None` means "not given". #[derive(Debug, Default)] pub struct Overrides { pub config_path: Option, pub store_dir: Option, pub socket_path: Option, } /// Whether the daemon runs as a system service or a per-user service. /// Decides default paths only; everything can be overridden. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Mode { System, User, } impl Mode { /// System mode when running as root, user mode otherwise. pub fn detect() -> Mode { // SAFETY: geteuid has no preconditions and cannot fail. if unsafe { libc_geteuid() } == 0 { Mode::System } else { Mode::User } } fn default_store_dir(self) -> PathBuf { match self { Mode::System => PathBuf::from("/var/lib/varde"), Mode::User => xdg_dir("XDG_DATA_HOME", ".local/share").join("varde"), } } fn default_socket_path(self) -> PathBuf { match self { Mode::System => PathBuf::from("/run/varde/varde.sock"), Mode::User => match std::env::var_os("XDG_RUNTIME_DIR") { Some(dir) => PathBuf::from(dir).join("varde.sock"), // No XDG_RUNTIME_DIR (rare outside a session): fall back // next to the store so the daemon still starts. None => Mode::User.default_store_dir().join("varde.sock"), }, } } fn default_config_path(self) -> PathBuf { match self { Mode::System => PathBuf::from("/etc/varde/config.toml"), Mode::User => xdg_dir("XDG_CONFIG_HOME", ".config").join("varde/config.toml"), } } } fn xdg_dir(var: &str, home_rel: &str) -> PathBuf { if let Some(dir) = std::env::var_os(var) { return PathBuf::from(dir); } let home = std::env::var_os("HOME").unwrap_or_else(|| "/".into()); PathBuf::from(home).join(home_rel) } // Minimal FFI shim instead of pulling in the libc crate for one call. extern "C" { #[link_name = "geteuid"] fn libc_geteuid() -> u32; } impl Config { /// Resolve configuration with full precedence: /// `overrides` (flags) > environment > config file > mode defaults. pub fn load(mode: Mode, overrides: &Overrides) -> Result { let config_path = overrides .config_path .clone() .or_else(|| std::env::var_os("VARDE_CONFIG").map(PathBuf::from)) .unwrap_or_else(|| mode.default_config_path()); // An explicitly named config file must exist; the default one is // allowed to be absent. let explicit = overrides.config_path.is_some() || std::env::var_os("VARDE_CONFIG").is_some(); let file = Self::read_file(&config_path, explicit)?; let env_path = |var: &str| std::env::var_os(var).map(PathBuf::from); let env_u64 = |var: &str| -> Result> { match std::env::var(var) { Ok(v) => { Ok(Some(v.parse().with_context(|| { format!("{var} must be an integer, got {v:?}") })?)) } Err(_) => Ok(None), } }; let env_bool = |var: &str| -> Result> { match std::env::var(var) { Ok(v) => { Ok(Some(v.parse().with_context(|| { format!("{var} must be true/false, got {v:?}") })?)) } Err(_) => Ok(None), } }; Ok(Config { store_dir: overrides .store_dir .clone() .or_else(|| env_path("VARDE_STORE")) .or(file.store_dir) .unwrap_or_else(|| mode.default_store_dir()), socket_path: overrides .socket_path .clone() .or_else(|| env_path("VARDE_SOCKET")) .or(file.socket_path) .unwrap_or_else(|| mode.default_socket_path()), max_upload_bytes_per_sec: env_u64("VARDE_MAX_UPLOAD")? .or(file.max_upload_bytes_per_sec) // Conservative default: 10 MB/s on LAN. .unwrap_or(10 * 1024 * 1024), max_download_bytes_per_sec: env_u64("VARDE_MAX_DOWNLOAD")? .or(file.max_download_bytes_per_sec) .unwrap_or(0), discovery: env_bool("VARDE_DISCOVERY")? .or(file.discovery) .unwrap_or(true), wan_upload: env_bool("VARDE_WAN_UPLOAD")? .or(file.wan_upload) .unwrap_or(false), gc_interval_secs: env_u64("VARDE_GC_INTERVAL")? .or(file.gc_interval_secs) .unwrap_or(300), }) } fn read_file(path: &Path, must_exist: bool) -> Result { match std::fs::read_to_string(path) { Ok(text) => toml::from_str(&text) .with_context(|| format!("parsing config file {}", path.display())), Err(e) if e.kind() == std::io::ErrorKind::NotFound && !must_exist => { Ok(FileConfig::default()) } Err(e) => Err(e).with_context(|| format!("reading config file {}", path.display())), } } } #[cfg(test)] mod tests { use super::*; // Env-var manipulation is process-global, so these tests only use // overrides and files, never set_var. #[test] fn empty_config_file_is_valid() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("config.toml"); std::fs::write(&path, "").unwrap(); let overrides = Overrides { config_path: Some(path), ..Default::default() }; let cfg = Config::load(Mode::User, &overrides).unwrap(); assert!(!cfg.wan_upload, "WAN upload must default off"); assert!(cfg.discovery, "discovery defaults on"); assert_eq!(cfg.max_upload_bytes_per_sec, 10 * 1024 * 1024); } #[test] fn missing_default_config_is_fine() { let cfg = Config::load(Mode::User, &Overrides::default()).unwrap(); assert!(cfg.socket_path.to_string_lossy().ends_with("varde.sock")); } #[test] fn missing_explicit_config_errors() { let overrides = Overrides { config_path: Some(PathBuf::from("/nonexistent/varde.toml")), ..Default::default() }; assert!(Config::load(Mode::User, &overrides).is_err()); } #[test] fn flags_beat_file() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("config.toml"); std::fs::write(&path, "store_dir = \"/from/file\"\n").unwrap(); let overrides = Overrides { config_path: Some(path), store_dir: Some(PathBuf::from("/from/flag")), ..Default::default() }; let cfg = Config::load(Mode::User, &overrides).unwrap(); assert_eq!(cfg.store_dir, PathBuf::from("/from/flag")); } #[test] fn unknown_keys_rejected() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("config.toml"); std::fs::write(&path, "no_such_key = 1\n").unwrap(); let overrides = Overrides { config_path: Some(path), ..Default::default() }; assert!(Config::load(Mode::User, &overrides).is_err()); } }