//! Configuration file (`~/.config/percival/config.toml`) and data directories. use std::path::PathBuf; use anyhow::{Context, Result}; use directories::ProjectDirs; use serde::{Deserialize, Serialize}; use crate::util; #[derive(Clone, Debug, Default, Serialize, Deserialize)] #[serde(default)] pub struct FileConfig { pub timeout: Option, pub concurrency: Option, pub per_host: Option, pub retries: Option, pub proxy: Option, pub user_agent: Option, pub random_ua: Option, pub headers: Option>, pub cookie: Option, pub formats: Option>, pub output_dir: Option, pub nsfw: Option, pub verify: Option, pub extract: Option, pub all_sites: Option, pub sources: Option>, pub theme: Option, pub hibp_api_key: Option, pub max_body_kb: Option, pub insecure: Option, } pub const TEMPLATE: &str = r#"# Percival configuration. Every key is optional; command-line flags win. # Request timeout in seconds. #timeout = 10 # Concurrent requests overall / per host. #concurrency = 60 #per_host = 4 # Retries for transient network failures. #retries = 1 # Route everything through a proxy (socks5h:// resolves DNS remotely). #proxy = "socks5h://127.0.0.1:9050" #user_agent = "Mozilla/5.0 ..." #random_ua = false # Extra headers sent with every request. #headers = ["Accept-Language: en-GB,en;q=0.9"] #cookie = "session=..." # Report formats written by --output (html, json, csv, md, txt, dot). #formats = ["html", "json", "csv"] # Where reports go when --output is given without a directory. #output_dir = "~/percival-reports" # Include NSFW sites (default true). #nsfw = true # Verify hits against a canary username (default true). #verify = true # Extract profile metadata from found pages (default true). #extract = true # Scan the long tail of unranked Maigret sites too (default false). #all_sites = false # Built-in databases to load. #sources = ["wmn", "sherlock", "maigret", "percival"] # Terminal / report theme: rose-pine, rose-pine-moon, rose-pine-dawn or none. #theme = "rose-pine" # Have I Been Pwned API key for `percival email`. #hibp_api_key = "" "#; fn project_dirs() -> Option { ProjectDirs::from("", "", crate::NAME) } /// `~/.config/percival/config.toml` (respects XDG). pub fn config_path() -> PathBuf { if let Ok(p) = std::env::var("PERCIVAL_CONFIG") { return util::expand_tilde(&p); } project_dirs() .map(|d| d.config_dir().join("config.toml")) .unwrap_or_else(|| PathBuf::from("percival.toml")) } /// `~/.local/share/percival` (respects XDG). Holds updated databases and the /// self-check overlay. pub fn data_dir() -> PathBuf { if let Ok(p) = std::env::var("PERCIVAL_DATA_DIR") { return util::expand_tilde(&p); } project_dirs() .map(|d| d.data_dir().to_path_buf()) .unwrap_or_else(|| PathBuf::from(".percival")) } /// Load the config file if present. A missing file is not an error. pub fn load(path: Option<&PathBuf>) -> Result { let path = path.cloned().unwrap_or_else(config_path); if !path.is_file() { return Ok(FileConfig::default()); } let text = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?; toml::from_str(&text).with_context(|| format!("parsing {}", path.display())) } /// Write the commented template (never overwrites an existing file). pub fn write_template(path: &PathBuf) -> Result { if path.exists() { return Ok(false); } if let Some(parent) = path.parent() { std::fs::create_dir_all(parent) .with_context(|| format!("creating {}", parent.display()))?; } std::fs::write(path, TEMPLATE).with_context(|| format!("writing {}", path.display()))?; Ok(true) } #[cfg(test)] mod tests { use super::*; #[test] fn template_parses() { let c: FileConfig = toml::from_str(TEMPLATE).unwrap(); assert!(c.timeout.is_none()); let c: FileConfig = toml::from_str( "timeout = 5\nformats = [\"json\"]\nproxy = \"socks5h://127.0.0.1:9050\"", ) .unwrap(); assert_eq!(c.timeout, Some(5.0)); assert_eq!(c.formats.as_deref(), Some(&["json".to_string()][..])); } }