//! WARP devices: each one's WireGuard profile, given in the configuration or registered with //! Cloudflare as wgcf registers (ps_core::warp), kept below the protected state root (it holds //! the device's private key). The renderer makes each a sing-box WireGuard endpoint. use std::collections::BTreeMap; use std::path::PathBuf; use anyhow::{Result, anyhow}; use base64::Engine; use ps_core::config::Config; use ps_core::derived::{self, WarpDeviceSpec}; use crate::fetch::{self, Route}; use crate::paths::Paths; fn profile_file(paths: &Paths, device: &WarpDeviceSpec) -> PathBuf { paths.root.join(&device.state_subdir).join("wgcf-profile.conf") } /// Each device's profile there is without the network: given, or registered before. pub fn profiles(cfg: &Config, paths: &Paths) -> BTreeMap { derived::warp_devices(cfg) .into_iter() .filter_map(|d| { let text = match (&d.config, &d.config_file) { (Some(t), _) => Some(t.clone()), (None, Some(f)) => std::fs::read_to_string(f).ok(), (None, None) => std::fs::read_to_string(profile_file(paths, &d)).ok(), }; text.map(|t| (d.tag, t)) }) .collect() } /// The devices to register, and where each one's profile goes: none given, none registered. pub fn unregistered(cfg: &Config, paths: &Paths) -> Vec<(String, PathBuf)> { derived::warp_devices(cfg) .into_iter() .filter(|d| d.auto_register()) .map(|d| { let file = profile_file(paths, &d); (d.tag, file) }) .filter(|(_, file)| !file.is_file()) .collect() } /// Now as RFC 3339, the terms' acceptance time the API wants. fn now() -> String { let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400)); // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm). let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z - era * 146_097; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let y = yoe + era * 400 + i64::from(m <= 2); format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}.000Z", rem / 3600, rem % 3600 / 60, rem % 60) } /// A new device: a key made here, its public half registered through each route in turn /// (the local proxy first: the API is blocked in some countries), then `generator` if given. pub async fn register(routes: &[Route], generator: Option<&str>) -> Result { let mut seed = [0u8; 32]; rand::fill(&mut seed); let secret = x25519_dalek::StaticSecret::from(seed); let public = x25519_dalek::PublicKey::from(&secret); let b64 = |b: &[u8]| base64::engine::general_purpose::STANDARD.encode(b); let body = ps_core::warp::registration(&b64(public.as_bytes()), &now()); let mut last = None; for route in routes { match fetch::post_json(ps_core::warp::API, &body, &ps_core::warp::HEADERS, route).await { Ok(answer) => return ps_core::warp::profile(&answer, &b64(&secret.to_bytes())).map_err(anyhow::Error::msg), Err(e) => last = Some(e), } } if let Some(url) = generator { for route in routes { if let Ok(body) = fetch::get(url, route, 64 * 1024).await { return ps_core::warp::generated(&String::from_utf8_lossy(&body)).map_err(anyhow::Error::msg); } } } Err(last.unwrap_or_else(|| anyhow!("no way to reach it")).context("registering with Cloudflare")) } #[cfg(test)] mod tests { #[test] fn now_is_rfc3339() { let n = super::now(); assert_eq!(n.len(), 24, "{n}"); assert!(n.starts_with("20") && n.ends_with(".000Z") && &n[10..11] == "T", "{n}"); } }