1use std::path::{Path, PathBuf};
18
19mod backends;
20pub mod config;
21#[cfg(not(target_os = "linux"))]
29pub mod exec;
30#[cfg(target_os = "linux")]
32pub mod helper;
33pub mod keys;
34pub mod proto;
35#[cfg(target_os = "linux")]
39pub mod netlink;
40
41pub use config::{WgConfig, interface_name};
42pub use keys::Keypair;
43
44#[derive(Debug, thiserror::Error)]
45pub enum Error {
46 #[error("{0}")]
47 Config(String),
48
49 #[error("{what} failed{}: {message}", .status.map(|s| format!(" (exit {s})")).unwrap_or_default())]
50 Command {
51 what: String,
52 status: Option<i32>,
53 message: String,
54 },
55
56 #[error("{0} is not installed")]
57 ToolMissing(String),
58
59 #[error("{what}: {cause}")]
63 Helper { what: String, cause: String },
64
65 #[error("could not run {program}: {source}")]
66 Spawn {
67 program: String,
68 #[source]
69 source: std::io::Error,
70 },
71
72 #[error("no system WireGuard found")]
73 NoBackend,
74
75 #[error("{what}: {cause}")]
80 Netlink { what: String, cause: String },
81
82 #[error("{path}: {source}")]
83 Io {
84 path: PathBuf,
85 #[source]
86 source: std::io::Error,
87 },
88}
89
90pub type Result<T> = std::result::Result<T, Error>;
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum BackendKind {
95 Helper,
97 WgQuick,
99 WindowsService,
101}
102
103#[derive(Debug, Clone)]
105pub struct Availability {
106 pub usable: bool,
107 pub detail: String,
109}
110
111impl Availability {
112 pub fn usable(detail: impl Into<String>) -> Availability {
113 Availability {
114 usable: true,
115 detail: detail.into(),
116 }
117 }
118
119 pub fn missing(detail: impl Into<String>) -> Availability {
120 Availability {
121 usable: false,
122 detail: detail.into(),
123 }
124 }
125}
126
127#[derive(Debug, Clone)]
129pub struct Tunnel {
130 pub network: String,
132 pub interface: String,
134 pub config_path: PathBuf,
136}
137
138#[async_trait::async_trait]
151pub trait Backend: Send + Sync {
152 fn kind(&self) -> BackendKind;
153
154 fn label(&self) -> &'static str;
156
157 fn elevation(&self) -> &'static str;
159
160 async fn probe(&self) -> Availability;
167
168 async fn up(&self, tunnel: &Tunnel) -> Result<()>;
170
171 async fn down(&self, tunnel: &Tunnel) -> Result<()>;
173
174 async fn is_up(&self, tunnel: &Tunnel) -> Result<bool>;
179}
180
181pub struct TunnelManager {
183 state_dir: PathBuf,
184 backends: Vec<Box<dyn Backend>>,
185}
186
187impl TunnelManager {
188 pub fn new(state_dir: impl Into<PathBuf>) -> TunnelManager {
192 TunnelManager {
193 state_dir: state_dir.into(),
194 backends: backends::for_platform(),
195 }
196 }
197
198 pub fn backends(&self) -> &[Box<dyn Backend>] {
201 &self.backends
202 }
203
204 pub async fn backend(&self) -> Option<&dyn Backend> {
210 for backend in &self.backends {
211 if backend.probe().await.usable {
212 return Some(backend.as_ref());
213 }
214 }
215 None
216 }
217
218 pub fn backend_of_kind(&self, kind: BackendKind) -> Option<&dyn Backend> {
226 self.backends
227 .iter()
228 .find(|b| b.kind() == kind)
229 .map(|b| b.as_ref())
230 }
231
232 pub async fn availability(&self) -> Vec<(&'static str, Availability)> {
237 let mut out = Vec::with_capacity(self.backends.len());
238 for backend in &self.backends {
239 out.push((backend.label(), backend.probe().await));
240 }
241 out
242 }
243
244 pub fn config_path(&self, network: &str) -> PathBuf {
246 self.state_dir.join(format!("{}.conf", interface_name(network)))
247 }
248
249 pub fn tunnel(&self, network: &str) -> Tunnel {
251 Tunnel {
252 network: network.to_owned(),
253 interface: interface_name(network),
254 config_path: self.config_path(network),
255 }
256 }
257
258 pub async fn install(&self, network: &str, config: &WgConfig) -> Result<Tunnel> {
270 config.validate()?;
271
272 tokio::fs::create_dir_all(&self.state_dir)
273 .await
274 .map_err(|source| Error::Io {
275 path: self.state_dir.clone(),
276 source,
277 })?;
278 restrict_dir(&self.state_dir).await;
279
280 let tunnel = self.tunnel(network);
281 write_private(&tunnel.config_path, config.render().as_bytes()).await?;
282 Ok(tunnel)
283 }
284
285 pub async fn installed(&self, network: &str) -> Option<WgConfig> {
287 let text = tokio::fs::read_to_string(self.config_path(network)).await.ok()?;
288 WgConfig::parse(&text).ok()
289 }
290
291 pub async fn uninstall(&self, network: &str) -> Result<()> {
294 let path = self.config_path(network);
295 match tokio::fs::remove_file(&path).await {
296 Ok(()) => Ok(()),
297 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
298 Err(source) => Err(Error::Io { path, source }),
299 }
300 }
301}
302
303async fn write_private(path: &Path, contents: &[u8]) -> Result<()> {
309 use tokio::io::AsyncWriteExt as _;
310
311 let mut options = tokio::fs::OpenOptions::new();
312 options.write(true).create(true).truncate(true);
313 #[cfg(unix)]
314 options.mode(0o600);
315
316 let mut file = options.open(path).await.map_err(|source| Error::Io {
317 path: path.to_owned(),
318 source,
319 })?;
320 file.write_all(contents).await.map_err(|source| Error::Io {
321 path: path.to_owned(),
322 source,
323 })?;
324 file.flush().await.map_err(|source| Error::Io {
325 path: path.to_owned(),
326 source,
327 })
328}
329
330async fn restrict_dir(path: &Path) {
332 #[cfg(unix)]
333 {
334 use std::os::unix::fs::PermissionsExt as _;
335 let _ = tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).await;
336 }
337 #[cfg(not(unix))]
338 let _ = path;
339}
340
341#[cfg(test)]
342mod tests {
343 use super::*;
344
345 fn sample_config() -> WgConfig {
346 let mut cfg = WgConfig::parse(
347 "[Interface]\nPrivateKey = REPLACE_WITH_YOUR_PRIVATE_KEY\nAddress = 10.9.0.2/32\nDNS = 10.9.0.1\n\n[Peer]\nPublicKey = pk\nAllowedIPs = 10.9.0.0/24\n",
348 )
349 .unwrap();
350 cfg.set_private_key(Keypair::generate().private_key());
351 cfg
352 }
353
354 fn temp_dir(name: &str) -> PathBuf {
355 let dir = std::env::temp_dir().join(format!("townos-tunnel-test-{name}-{}", std::process::id()));
356 let _ = std::fs::remove_dir_all(&dir);
357 dir
358 }
359
360 #[test]
361 fn config_path_follows_the_interface_name() {
362 let mgr = TunnelManager::new("/tmp/state");
363 assert_eq!(mgr.config_path("office"), Path::new("/tmp/state/townos-office.conf"));
364 assert_eq!(mgr.tunnel("office").interface, "townos-office");
365 }
366
367 #[tokio::test]
368 async fn install_writes_a_config_only_this_user_can_read() {
369 let dir = temp_dir("install");
370 let mgr = TunnelManager::new(&dir);
371 let tunnel = mgr.install("office", &sample_config()).await.unwrap();
372
373 assert!(tunnel.config_path.exists());
374 #[cfg(unix)]
375 {
376 use std::os::unix::fs::PermissionsExt as _;
377 let mode = std::fs::metadata(&tunnel.config_path).unwrap().permissions().mode();
378 assert_eq!(mode & 0o777, 0o600, "config holds a private key");
379 }
380
381 let read_back = mgr.installed("office").await.unwrap();
382 assert_eq!(read_back.address(), Some("10.9.0.2/32"));
383
384 let _ = std::fs::remove_dir_all(&dir);
385 }
386
387 #[tokio::test]
388 async fn install_refuses_a_config_that_would_run_commands_as_root() {
389 let dir = temp_dir("refuse");
390 let mgr = TunnelManager::new(&dir);
391 let cfg = WgConfig::parse(
392 "[Interface]\nPrivateKey = k\nAddress = 10.9.0.2/32\nPostUp = touch /tmp/pwned\n\n[Peer]\nPublicKey = pk\n",
393 )
394 .unwrap();
395
396 assert!(mgr.install("office", &cfg).await.is_err());
397 assert!(!mgr.config_path("office").exists(), "nothing was written");
398 let _ = std::fs::remove_dir_all(&dir);
399 }
400
401 #[tokio::test]
402 async fn reinstalling_replaces_rather_than_appends() {
403 let dir = temp_dir("replace");
404 let mgr = TunnelManager::new(&dir);
405 mgr.install("office", &sample_config()).await.unwrap();
406 let first = std::fs::read_to_string(mgr.config_path("office")).unwrap();
407
408 mgr.install("office", &sample_config()).await.unwrap();
409 let second = std::fs::read_to_string(mgr.config_path("office")).unwrap();
410
411 assert_ne!(first, second, "a fresh key was written");
412 assert_eq!(second.matches("[Interface]").count(), 1, "not appended");
413 let _ = std::fs::remove_dir_all(&dir);
414 }
415
416 #[tokio::test]
417 async fn uninstalling_something_absent_is_not_an_error() {
418 let dir = temp_dir("uninstall");
419 let mgr = TunnelManager::new(&dir);
420 assert!(mgr.uninstall("never-installed").await.is_ok());
421 assert!(mgr.installed("never-installed").await.is_none());
422 }
423
424 #[tokio::test]
425 async fn every_backend_probes_without_panicking() {
426 let mgr = TunnelManager::new("/tmp/state");
429 for (label, availability) in mgr.availability().await {
430 assert!(!label.is_empty());
431 assert!(!availability.detail.is_empty(), "{label} gave no reason");
432 }
433 }
434
435 #[tokio::test]
436 async fn availability_covers_every_backend_in_preference_order() {
437 let mgr = TunnelManager::new("/tmp/state");
440 let reported: Vec<&str> = mgr.availability().await.into_iter().map(|(l, _)| l).collect();
441 let expected: Vec<&str> = mgr.backends().iter().map(|b| b.label()).collect();
442 assert_eq!(reported, expected);
443 }
444}