From eb8c2d091b579fca627c7fda1f6b0db3cabec6cf Mon Sep 17 00:00:00 2001 From: Ferdinand Schober Date: Thu, 26 Mar 2026 13:27:05 +0100 Subject: [PATCH] automatically update config when changed --- Cargo.lock | 106 ++++++++++++++++++++++++++++++++++++++++++++++++ Cargo.toml | 1 + src/capture.rs | 14 ++++++- src/client.rs | 30 ++++++++++++++ src/config.rs | 107 ++++++++++++++++++++++++++++++++++++++++--------- src/service.rs | 47 +++++++++++++--------- 6 files changed, 267 insertions(+), 38 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b5fcf02..b06abaa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -971,6 +971,15 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fsevent-sys" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" +dependencies = [ + "libc", +] + [[package]] name = "futures" version = "0.3.31" @@ -1652,6 +1661,26 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "inotify" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd5b3eaf1a28b758ac0faa5a4254e8ab2705605496f1b1f3fbbc3988ad73d199" +dependencies = [ + "bitflags 2.9.1", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb" +dependencies = [ + "libc", +] + [[package]] name = "inout" version = "0.1.4" @@ -1843,6 +1872,26 @@ dependencies = [ "quote", ] +[[package]] +name = "kqueue" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b" +dependencies = [ + "bitflags 1.3.2", + "libc", +] + [[package]] name = "lan-mouse" version = "0.10.0" @@ -1861,6 +1910,7 @@ dependencies = [ "libc", "local-channel", "log", + "notify", "rcgen", "rustls", "serde", @@ -2121,6 +2171,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" dependencies = [ "libc", + "log", "wasi 0.11.1+wasi-snapshot-preview1", "windows-sys 0.59.0", ] @@ -2180,6 +2231,33 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "notify" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" +dependencies = [ + "bitflags 2.9.1", + "fsevent-sys", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "walkdir", + "windows-sys 0.60.2", +] + +[[package]] +name = "notify-types" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a" +dependencies = [ + "bitflags 2.9.1", +] + [[package]] name = "nu-ansi-term" version = "0.46.0" @@ -2820,6 +2898,15 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -3526,6 +3613,16 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -3763,6 +3860,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.60.2", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index 29c0097..b482e5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,7 @@ rustls = { version = "0.23.12", default-features = false, features = [ ] } rcgen = "0.13.1" sha2 = "0.10.8" +notify = "8.2.0" [target.'cfg(unix)'.dependencies] libc = "0.2.148" diff --git a/src/capture.rs b/src/capture.rs index e4d9c8a..4300dea 100644 --- a/src/capture.rs +++ b/src/capture.rs @@ -49,7 +49,7 @@ pub(crate) enum CaptureType { EnterOnly, } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Debug)] enum CaptureRequest { /// capture must release the mouse Release, @@ -59,6 +59,8 @@ enum CaptureRequest { Destroy(CaptureHandle), /// reenable input capture Reenable, + /// set release bind + SetReleaseBind(Vec), } impl Capture { @@ -131,6 +133,10 @@ impl Capture { pub(crate) async fn event(&mut self) -> ICaptureEvent { self.event_rx.recv().await.expect("channel closed") } + + pub(crate) fn set_release_bind(&mut self, bind: Vec) { + let _ = self.request_tx.send(CaptureRequest::SetReleaseBind(bind)); + } } /// debounce a statement `$st`, i.e. the statement is executed only if the @@ -205,6 +211,9 @@ impl CaptureTask { CaptureRequest::Create(h, p, t) => self.add_capture(h, p, t), CaptureRequest::Destroy(h) => self.remove_capture(h), CaptureRequest::Release => { /* nothing to do */ } + CaptureRequest::SetReleaseBind(bind) => { + self.release_bind.borrow_mut().clone_from(&bind); + } }, _ = self.cancellation_token.cancelled() => return, } @@ -295,6 +304,9 @@ impl CaptureTask { self.remove_capture(h); capture.destroy(h).await?; } + CaptureRequest::SetReleaseBind(bind) => { + self.release_bind.borrow_mut().clone_from(&bind); + } }, _ = self.cancellation_token.cancelled() => break, } diff --git a/src/client.rs b/src/client.rs index b67f787..3229c8c 100644 --- a/src/client.rs +++ b/src/client.rs @@ -9,6 +9,8 @@ use slab::Slab; use lan_mouse_ipc::{ClientConfig, ClientHandle, ClientState, Position}; +use crate::config::ConfigClient; + #[derive(Clone, Default)] pub struct ClientManager { clients: Rc>>, @@ -24,6 +26,25 @@ impl ClientManager { .collect::>() } + pub fn add_with_config(&self, config_client: ConfigClient) -> ClientHandle { + let config = ClientConfig { + hostname: config_client.hostname, + fix_ips: config_client.ips.into_iter().collect(), + port: config_client.port, + pos: config_client.pos, + cmd: config_client.enter_hook, + }; + let state = ClientState { + active: config_client.active, + ips: HashSet::from_iter(config.fix_ips.iter().cloned()), + ..Default::default() + }; + let handle = self.add_client(); + self.set_config(handle, config); + self.set_state(handle, state); + handle + } + /// add a new client to this manager pub fn add_client(&self) -> ClientHandle { self.clients.borrow_mut().insert(Default::default()) as ClientHandle @@ -230,6 +251,15 @@ impl ClientManager { .and_then(|(c, _)| c.cmd.clone()) } + /// returns all clients that are currently registered + pub(crate) fn registered_clients(&self) -> Vec { + self.clients + .borrow() + .iter() + .map(|(h, _)| h as ClientHandle) + .collect() + } + /// returns all clients that are currently active pub(crate) fn active_clients(&self) -> Vec { self.clients diff --git a/src/config.rs b/src/config.rs index 78750f3..d9d4fa6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,6 +1,7 @@ use crate::capture_test::TestCaptureArgs; use crate::emulation_test::TestEmulationArgs; use clap::{Parser, Subcommand, ValueEnum}; +use notify::{EventKind, RecommendedWatcher, Watcher}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::env::{self, VarError}; @@ -46,7 +47,7 @@ fn default_path() -> Result { Ok(PathBuf::from(default_path)) } -#[derive(Serialize, Deserialize, Clone, Debug, Default)] +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)] struct ConfigToml { capture_backend: Option, emulation_backend: Option, @@ -244,8 +245,14 @@ pub struct Config { cert_path: PathBuf, /// path to the config file used config_path: PathBuf, + /// path to config directory (parent of above) + config_dir: PathBuf, /// the (optional) toml config and it's path config_toml: Option, + // filesystem watcher + watcher: notify::RecommendedWatcher, + // channel for filesystem events + watch_rx: tokio::sync::mpsc::Receiver>, } pub struct ConfigClient { @@ -311,6 +318,8 @@ pub enum ConfigError { Io(#[from] io::Error), #[error(transparent)] Var(#[from] VarError), + #[error(transparent)] + Watcher(#[from] notify::Error), } const DEFAULT_RELEASE_KEYS: [scancode::Linux; 4] = @@ -342,12 +351,55 @@ impl Config { .or(config_toml.as_ref().and_then(|c| c.cert_path.clone())) .unwrap_or(default_path()?.join(CERT_FILE_NAME)); - Ok(Config { + let (tx, watch_rx) = tokio::sync::mpsc::channel(16); + let watcher = RecommendedWatcher::new( + move |res| { + let _ = tx.blocking_send(res); + }, + notify::Config::default(), + )?; + let config_dir = config_path + .parent() + .expect("config directory") + .to_path_buf(); + let mut config = Config { args, cert_path, config_path, + config_dir, config_toml, - }) + watcher, + watch_rx, + }; + config.watch()?; + Ok(config) + } + + fn watch(&mut self) -> Result<(), notify::Error> { + self.watcher + .watch(&self.config_dir, notify::RecursiveMode::NonRecursive)?; + Ok(()) + } + + fn unwatch(&mut self) -> Result<(), notify::Error> { + self.watcher.unwatch(&self.config_dir)?; + Ok(()) + } + + pub async fn changed(&mut self) -> Result<(), notify::Error> { + loop { + let event = self.watch_rx.recv().await.expect("channel closed"); + let event = event.expect("filesystem event"); + if event.paths.contains(&self.config_path) + && matches!( + event.kind, + EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_) + ) + && self.read_from_disk()? + { + return Ok(()); + } + } } /// the command to run @@ -428,9 +480,6 @@ impl Config { /// set authorized keys pub fn set_authorized_keys(&mut self, fingerprints: HashMap) { - if fingerprints.is_empty() { - return; - } if self.config_toml.is_none() { self.config_toml = Default::default(); } @@ -440,38 +489,58 @@ impl Config { .authorized_fingerprints = Some(fingerprints); } - pub fn write_back(&self) -> Result<(), io::Error> { - log::info!("writing config to {:?}", &self.config_path); - /* load the current configuration file */ - let current_config = match fs::read_to_string(&self.config_path) { - Ok(c) => c.parse::().unwrap_or_default(), + pub fn read_from_disk(&mut self) -> Result { + log::info!("reading config from {:?}", &self.config_path); + + let current_config = fs::read_to_string(&self.config_path)?; + let current_config = match current_config.parse::() { + Ok(c) => c, Err(e) => { - log::info!("{:?} {e} => creating new config", self.config_path()); - Default::default() + log::warn!("{:?} {e}", self.config_path()); + return Ok(false); } }; - let _current_config = - toml_edit::de::from_document::(current_config).unwrap_or_default(); + let mut changed = false; + match toml_edit::de::from_document::(current_config) { + Ok(current_config) => { + changed = self + .config_toml + .as_ref() + .is_none_or(|c| c != ¤t_config); + self.config_toml.replace(current_config); + } + Err(e) => log::warn!("{:?} {e}", self.config_path()), + }; + Ok(changed) + } + pub fn write_back(&mut self) -> Result<(), io::Error> { + log::info!("writing config to {:?}", &self.config_path); /* the new config */ let new_config = self.config_toml.clone().unwrap_or_default(); - // let new_config = toml_edit::ser::to_document::(&new_config).expect("fixme"); let new_config = toml_edit::ser::to_string_pretty(&new_config).expect("config"); /* - * TODO merge documents => eventually we might want to split this up into clients configured + * TODO merge with current config file to preserve comments + * => eventually we might want to split this up into clients configured * via the config file and clients managed through the GUI / frontend. * The latter should be saved to $XDG_DATA_HOME instead of $XDG_CONFIG_HOME, * and clients configured through .config could be made permanent. * For now we just override the config file. */ + let _ = self.unwatch(); /* write new config to file */ if let Some(p) = self.config_path().parent() { fs::create_dir_all(p)?; } - let mut f = File::create(self.config_path())?; - f.write_all(new_config.as_bytes())?; + { + let mut f = File::create(self.config_path())?; + f.write_all(new_config.as_bytes())?; + f.sync_all()?; + } + + let _ = self.watch(); Ok(()) } diff --git a/src/service.rs b/src/service.rs index ff7c22f..d0772f6 100644 --- a/src/service.rs +++ b/src/service.rs @@ -11,8 +11,8 @@ use crate::{ use futures::StreamExt; use hickory_resolver::ResolveError; use lan_mouse_ipc::{ - AsyncFrontendListener, ClientConfig, ClientHandle, ClientState, FrontendEvent, FrontendRequest, - IpcError, IpcListenerCreationError, Position, Status, + AsyncFrontendListener, ClientHandle, FrontendEvent, FrontendRequest, IpcError, + IpcListenerCreationError, Position, Status, }; use log; use std::{ @@ -83,21 +83,7 @@ impl Service { pub async fn new(config: Config) -> Result { let client_manager = ClientManager::default(); for client in config.clients() { - let config = ClientConfig { - hostname: client.hostname, - fix_ips: client.ips.into_iter().collect(), - port: client.port, - pos: client.pos, - cmd: client.enter_hook, - }; - let state = ClientState { - active: client.active, - ips: HashSet::from_iter(config.fix_ips.iter().cloned()), - ..Default::default() - }; - let handle = client_manager.add_client(); - client_manager.set_config(handle, config); - client_manager.set_state(handle, state); + client_manager.add_with_config(client); } // load certificate @@ -164,6 +150,7 @@ impl Service { event = self.emulation.event() => self.handle_emulation_event(event), event = self.capture.event() => self.handle_capture_event(event), event = self.resolver.event() => self.handle_resolver_event(event), + _ = self.config.changed() => self.handle_config_change(), r = signal::ctrl_c() => break r.expect("failed to wait for CTRL+C"), } } @@ -255,6 +242,30 @@ impl Service { } } + fn handle_config_change(&mut self) { + for h in self.client_manager.registered_clients() { + self.remove_client(h); + } + for c in self.config.clients() { + let handle = self.client_manager.add_with_config(c); + log::info!("added client {handle}"); + let (c, s) = self.client_manager.get_state(handle).unwrap(); + if s.active { + self.client_manager.deactivate_client(handle); + self.activate_client(handle); + } + self.notify_frontend(FrontendEvent::Created(handle, c, s)); + } + let release_bind = self.config.release_bind(); + self.capture.set_release_bind(release_bind); + let authorized_keys = self.config.authorized_fingerprints(); + self.authorized_keys + .write() + .unwrap() + .clone_from(&authorized_keys); + self.sync_frontend(); + } + async fn handle_frontend_pending(&mut self) { while let Some(event) = self.pending_frontend_events.pop_front() { self.frontend_listener.broadcast(event).await; @@ -477,7 +488,7 @@ impl Service { } fn activate_client(&mut self, handle: ClientHandle) { - log::debug!("activating client"); + log::debug!("activating client {handle}"); /* resolve dns on activate */ self.resolve(handle);