diff --git a/Cargo.lock b/Cargo.lock index 33a721e..876cf16 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -920,6 +920,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.32" @@ -1606,6 +1615,26 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inotify" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd5b3eaf1a28b758ac0faa5a4254e8ab2705605496f1b1f3fbbc3988ad73d199" +dependencies = [ + "bitflags 2.11.0", + "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" @@ -1787,6 +1816,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" @@ -1805,6 +1854,7 @@ dependencies = [ "libc", "local-channel", "log", + "notify", "rcgen", "rustls", "serde", @@ -2039,6 +2089,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", + "log", "wasi", "windows-sys 0.61.2", ] @@ -2083,6 +2134,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.11.0", + "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.11.0", +] + [[package]] name = "num-bigint" version = "0.4.6" @@ -2678,6 +2756,15 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +[[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 = "scopeguard" version = "1.2.0" @@ -3352,6 +3439,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" @@ -3619,6 +3716,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.61.2", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" @@ -3781,7 +3887,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -3790,7 +3896,16 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", ] [[package]] @@ -3808,14 +3923,31 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link 0.2.1", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", ] [[package]] @@ -3833,48 +3965,96 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.7.15" 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 a8f74a7..6300aa5 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 = Some(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);