//! The configuration, runtime state and generated secrets, as files. use std::collections::BTreeMap; use anyhow::{Context, Result}; use ps_core::config::Config; use ps_core::render::{RuleSetFile, State}; use rand::Rng; use serde::{Deserialize, Serialize}; use crate::paths::{Paths, write_atomic}; /// What the service generated once and keeps. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Secrets { pub clash_secret: String, pub hop_user: String, pub hop_password: String, } pub fn random_token(len: usize) -> String { const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; let mut rng = rand::rng(); (0..len).map(|_| CHARS[rng.random_range(0..CHARS.len())] as char).collect() } pub fn random_uuid() -> String { let mut rng = rand::rng(); let b: [u8; 16] = rng.random(); format!( "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}", u32::from_be_bytes([b[0], b[1], b[2], b[3]]), u16::from_be_bytes([b[4], b[5]]), u16::from_be_bytes([b[6], b[7]]) & 0x0fff, (u16::from_be_bytes([b[8], b[9]]) & 0x3fff) | 0x8000, u64::from_be_bytes([0, 0, b[10], b[11], b[12], b[13], b[14], b[15]]) ) } pub struct Store { pub paths: Paths, pub config: Config, /// Bumped by every change of `config`: a client edits against a revision. pub revision: u64, pub state: State, pub secrets: Secrets, /// Each subscription's links as fetched last. pub subscriptions: BTreeMap>, } impl Store { pub fn open(paths: Paths) -> Result { paths.create_all().with_context(|| format!("creating {}", paths.root.display()))?; let config = match std::fs::read_to_string(paths.config()) { Ok(text) => Config::from_json(&text).with_context(|| format!("reading {}", paths.config().display()))?, Err(e) if e.kind() == std::io::ErrorKind::NotFound => Config::default(), Err(e) => return Err(e).with_context(|| format!("reading {}", paths.config().display())), }; let state = std::fs::read_to_string(paths.state()) .ok() .and_then(|t| serde_json::from_str(&t).ok()) .unwrap_or_default(); let secrets = match std::fs::read_to_string(paths.secrets()).ok().and_then(|t| serde_json::from_str(&t).ok()) { Some(s) => s, None => { let s = Secrets { clash_secret: random_token(32), hop_user: "hop".into(), hop_password: random_token(32) }; write_atomic(&paths.secrets(), serde_json::to_string_pretty(&s)?.as_bytes())?; s } }; let mut store = Self { paths, config, revision: 1, state, secrets, subscriptions: BTreeMap::new() }; store.load_subscriptions(); Ok(store) } pub fn save_config(&mut self, config: Config) -> Result<()> { write_atomic(&self.paths.config(), config.to_json_pretty().as_bytes())?; self.config = config; self.revision += 1; Ok(()) } pub fn save_state(&self) -> Result<()> { write_atomic(&self.paths.state(), serde_json::to_string_pretty(&self.state)?.as_bytes())?; Ok(()) } fn sub_path(&self, tag: &str) -> std::path::PathBuf { self.paths.subscriptions().join(format!("{tag}.txt")) } fn load_subscriptions(&mut self) { for sub in &self.config.proxy.subscriptions { if let Ok(text) = std::fs::read_to_string(self.sub_path(&sub.tag)) { self.subscriptions.insert(sub.tag.clone(), text.lines().map(str::to_owned).collect()); } } } pub fn save_subscription(&mut self, tag: &str, lines: Vec) -> Result<()> { write_atomic(&self.sub_path(tag), lines.join("\n").as_bytes())?; self.subscriptions.insert(tag.to_owned(), lines); Ok(()) } /// The downloaded rule sets, by tag. pub fn rule_set_files(&self) -> BTreeMap { let mut out = BTreeMap::new(); let Ok(dir) = std::fs::read_dir(self.paths.rule_sets()) else { return out }; for entry in dir.flatten() { let path = entry.path(); let (Some(stem), Some(ext)) = (path.file_stem().and_then(|s| s.to_str()), path.extension().and_then(|s| s.to_str())) else { continue; }; let format = match ext { "srs" => ps_core::config::RuleSetFormat::Binary, "json" => ps_core::config::RuleSetFormat::Source, _ => continue, }; out.insert(stem.to_owned(), RuleSetFile { path: path.to_string_lossy().into_owned(), format }); } out } }