//! Config file: TOML parsing, validation, and reading the forge token. use crate::{Res, migrate}; use serde::Deserialize; use std::collections::HashSet; use std::env; use std::ffi::OsString; use std::fs::{self, OpenOptions}; use std::io::{self, Write}; use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; /// Top-level keys; must match the `Raw` fields. const KNOWN_TOP_KEYS: &[&str] = &["forge", "token_file", "state_dir", "app"]; /// Keys in each `[[app]]` table; must match the `App` fields. const KNOWN_APP_KEYS: &[&str] = &[ "name", "repo", "asset", "path", "unit", "prerelease", "unpack", "check", "health_url", "health_timeout_secs", ]; /// Raw TOML shape; `apps` comes from the `[[app]]` tables. #[derive(Deserialize)] struct Raw { forge: String, token_file: Option, state_dir: Option, #[serde(default, rename = "app")] apps: Vec, } /// One `[[app]]` table. #[derive(Deserialize)] pub struct App { pub name: String, pub repo: String, pub asset: String, pub path: PathBuf, pub unit: Option, #[serde(default)] pub prerelease: bool, #[serde(default)] pub unpack: bool, pub check: Option>, pub health_url: Option, #[serde(default = "default_health_timeout")] pub health_timeout_secs: u64, } fn default_health_timeout() -> u64 { 30 } /// Validated configuration. pub struct Config { /// Forge base URL without a trailing slash. pub forge: String, /// Forge token, trimmed; sent only to forge URLs. pub token: Option, pub state_dir: PathBuf, pub apps: Vec, /// Non-fatal notices, such as unknown keys. pub warnings: Vec, /// One message per key renamed by `migrate::RENAMES`. pub migrated: Vec, } impl App { /// Asset file name for this host, with `{arch}` expanded. pub fn asset_name(&self) -> String { self.asset.replace("{arch}", std::env::consts::ARCH) } /// `path` with `suffix` appended, in the same directory (e.g. `.kur-new`, `.prev`). pub fn sibling(&self, suffix: &str) -> PathBuf { let mut name = self.path.clone().into_os_string(); name.push(suffix); PathBuf::from(name) } } /// Value of environment variable `name`, or None if it is unset or empty. fn env_value(name: &str) -> Option { env::var_os(name).filter(|value| !value.is_empty()) } /// `$HOME`, if set and not empty. pub(crate) fn home_dir() -> Option { env_value("HOME").map(PathBuf::from) } /// Config path for a run: `cli` (from `--config`), else `KUR_CONFIG`, else `default_path()`. pub fn config_path(cli: Option) -> Res { match cli.or_else(|| env_value("KUR_CONFIG").map(PathBuf::from)) { Some(path) => Ok(path), None => default_path(), } } /// Config file used when neither `--config` nor `KUR_CONFIG` is set: /// `$XDG_CONFIG_HOME/kur/kur.toml`, else `$HOME/.config/kur/kur.toml`. pub fn default_path() -> Res { Ok(config_base()?.join("kur").join("kur.toml")) } /// `$XDG_CONFIG_HOME`, else `$HOME/.config`. Base for kur's config and the systemd user units. pub(crate) fn config_base() -> Res { match env_value("XDG_CONFIG_HOME") { Some(dir) => Ok(PathBuf::from(dir)), None => home_dir().map(|home| home.join(".config")).ok_or_else(|| { "neither XDG_CONFIG_HOME nor HOME is set; use --config or KUR_CONFIG".to_string() }), } } /// Default `state_dir`: `$XDG_STATE_HOME/kur`, else `$HOME/.local/state/kur`. fn default_state_dir() -> Res { let base = match env_value("XDG_STATE_HOME") { Some(dir) => PathBuf::from(dir), None => home_dir() .ok_or_else(|| { "neither XDG_STATE_HOME nor HOME is set; set state_dir in the config".to_string() })? .join(".local") .join("state"), }; let dir = base.join("kur"); if !dir.is_absolute() { return Err("state_dir must be absolute".into()); } Ok(dir) } /// Expands a leading `~/` to `$HOME/` (and nothing else), then requires an absolute path. /// `what` names the setting in error messages. fn absolute_path(path: &Path, what: &str) -> Res { let expanded = match path.to_str().and_then(|s| s.strip_prefix("~/")) { Some(rest) => home_dir() .ok_or_else(|| format!("{what}: cannot expand ~/ because HOME is not set"))? .join(rest.trim_start_matches('/')), None => path.to_path_buf(), }; if !expanded.is_absolute() { return Err(format!("{what} must be absolute")); } Ok(expanded) } /// Reads and validates the config file at `path`, renaming keys listed in `migrate::RENAMES`. /// If anything was renamed and `write` is set, the file is rewritten once the config is valid. pub fn load(path: &Path, write: bool) -> Res { let mut text = fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; // If the text does not parse, skip migration; the toml::from_str below reports the error. let mut migrated = Vec::new(); if let Ok(mut doc) = text.parse::() { migrated = migrate::apply(&mut doc, migrate::RENAMES); if !migrated.is_empty() { text = doc.to_string(); } } let table: toml::Table = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; let mut warnings = unknown_key_warnings(&table); let mut raw: Raw = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; let forge = raw.forge.trim_end_matches('/').to_string(); if !forge.starts_with("https://") && !forge.starts_with("http://") { return Err("forge must start with https:// or http://".into()); } if raw.apps.is_empty() { return Err("no [[app]] entries in config".into()); } let mut names = HashSet::new(); for app in &raw.apps { if !valid_name(&app.name) { return Err(format!("invalid app name {:?}", app.name)); } if !names.insert(app.name.as_str()) { return Err(format!("duplicate app name {}", app.name)); } let parts: Vec<&str> = app.repo.split('/').collect(); if parts.len() != 2 || parts.iter().any(|p| p.is_empty()) { return Err(format!("{}: repo must be owner/name", app.name)); } if app.unpack && app.check.is_some() { return Err(format!("{}: check cannot be used with unpack", app.name)); } } for app in &mut raw.apps { app.path = absolute_path(&app.path, &format!("{}: path", app.name))?; } let token_file = raw .token_file .as_deref() .map(|file| absolute_path(file, "token_file")) .transpose()?; let token = token_file.as_deref().map(read_token).transpose()?; let state_dir = match raw.state_dir.as_deref() { Some(dir) => absolute_path(dir, "state_dir")?, None => default_state_dir()?, }; if !migrated.is_empty() && write && let Err(e) = rewrite_config(path, &text) { warnings.push(format!("could not rewrite config: {e}")); } Ok(Config { forge, token, state_dir, apps: raw.apps, warnings, migrated, }) } /// Replaces the config at `path` with `text`, keeping the original as `.bak`. /// The temp file is removed if anything fails, and the original is left in place. fn rewrite_config(path: &Path, text: &str) -> io::Result<()> { let tmp = with_suffix(path, ".kur-tmp"); let result = write_and_swap(path, &tmp, text); if result.is_err() { let _ = fs::remove_file(&tmp); } result } fn write_and_swap(path: &Path, tmp: &Path, text: &str) -> io::Result<()> { // fs::copy keeps the original's permission bits on the backup. fs::copy(path, with_suffix(path, ".bak"))?; let perms = fs::metadata(path)?.permissions(); // 0600 from creation, so the config is never readable by others before the final mode is set. let mut file = OpenOptions::new() .write(true) .create(true) .truncate(true) .mode(0o600) .open(tmp)?; file.write_all(text.as_bytes())?; file.set_permissions(perms)?; file.sync_all()?; drop(file); fs::rename(tmp, path)?; let parent = match path.parent() { Some(dir) if !dir.as_os_str().is_empty() => dir, _ => Path::new("."), }; fs::File::open(parent)?.sync_all() } /// `path` with `suffix` appended to its file name. fn with_suffix(path: &Path, suffix: &str) -> PathBuf { let mut name = path.as_os_str().to_owned(); name.push(suffix); PathBuf::from(name) } /// One warning per key that is not in the known lists, at the top level and in each `[[app]]`. fn unknown_key_warnings(table: &toml::Table) -> Vec { let mut warnings = Vec::new(); for key in table.keys() { if !KNOWN_TOP_KEYS.contains(&key.as_str()) { warnings.push(format!("unknown key {key:?}")); } } if let Some(toml::Value::Array(apps)) = table.get("app") { for (index, app) in apps.iter().enumerate() { let Some(app) = app.as_table() else { continue; }; let label = match app.get("name").and_then(toml::Value::as_str) { Some(name) => name.to_string(), None => format!("#{}", index + 1), }; for key in app.keys() { if !KNOWN_APP_KEYS.contains(&key.as_str()) { warnings.push(format!("unknown key {key:?} in [[app]] {label}")); } } } } warnings } /// Matches `^[a-z0-9][a-z0-9_-]{0,39}$`. fn valid_name(name: &str) -> bool { let bytes = name.as_bytes(); !bytes.is_empty() && bytes.len() <= 40 && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit()) && bytes .iter() .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-') } /// Reads the token file, trimmed. The token is never included in error messages. fn read_token(path: &Path) -> Res { let text = fs::read_to_string(path).map_err(|e| format!("token_file {}: {e}", path.display()))?; let token = text.trim(); if token.is_empty() { return Err(format!("token_file {} is empty", path.display())); } Ok(token.to_string()) }