diff --git a/fader_master/Cargo.toml b/fader_master/Cargo.toml index 501be8a..1ed14f2 100644 --- a/fader_master/Cargo.toml +++ b/fader_master/Cargo.toml @@ -13,8 +13,12 @@ clap.workspace = true fader-config.workspace = true fader-core.workspace = true midi.workspace = true +rustix.workspace = true serde.workspace = true thiserror.workspace = true toml.workspace = true tui.workspace = true volume_lib.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/fader_master/src/lib.rs b/fader_master/src/lib.rs index f694ec5..9965fba 100644 --- a/fader_master/src/lib.rs +++ b/fader_master/src/lib.rs @@ -5,6 +5,7 @@ pub mod cli; pub mod ipc; pub mod live; +pub mod local; use std::{collections::BTreeMap, error::Error, fmt}; diff --git a/fader_master/src/local.rs b/fader_master/src/local.rs new file mode 100644 index 0000000..2a81cd8 --- /dev/null +++ b/fader_master/src/local.rs @@ -0,0 +1,266 @@ +use std::{ + fs, io, + os::unix::{ + fs::{FileTypeExt, MetadataExt, PermissionsExt}, + net::{UnixListener, UnixStream}, + }, + path::{Path, PathBuf}, + sync::mpsc::RecvTimeoutError, + time::Duration, +}; + +use fader_config::{XdgEnvironment, XdgPaths}; +use fader_core::{BackendEpoch, Gain}; +use thiserror::Error; +use volume_lib::PulseWorker; + +use crate::{ + ipc::{ + ClientRequest, PROTOCOL_VERSION, ResponseResult, ServerResponse, read_frame, write_frame, + }, + live::LiveMixerState, +}; + +const CLIENT_TIMEOUT: Duration = Duration::from_millis(500); +const SERVER_TICK: Duration = Duration::from_millis(10); + +#[derive(Debug, Error)] +pub enum LocalError { + #[error("XDG_RUNTIME_DIR is required for the local server socket")] + MissingRuntimeDirectory, + #[error("another fader_master server is already listening at {0}")] + AlreadyRunning(PathBuf), + #[error("refusing unsafe server socket {path}: {reason}")] + UnsafeSocket { path: PathBuf, reason: String }, + #[error("local socket operation failed for {path}: {source}")] + Socket { + path: PathBuf, + #[source] + source: io::Error, + }, + #[error(transparent)] + Frame(#[from] crate::ipc::FrameError), + #[error("server response request ID {actual} does not match {expected}")] + RequestId { actual: u64, expected: u64 }, + #[error("server protocol version {actual} does not match {expected}")] + Protocol { actual: u16, expected: u16 }, + #[error("audio worker command lane is unavailable or full")] + WorkerCommand, + #[error("audio worker event lane disconnected")] + WorkerDisconnected, + #[error(transparent)] + Mixer(#[from] crate::live::LiveMixerError), + #[error(transparent)] + Config(#[from] fader_config::ConfigError), +} + +pub fn default_socket_path() -> Result { + let environment = XdgEnvironment::from_process()?; + let paths = XdgPaths::resolve(&environment)?; + let directory = paths + .runtime_dir() + .ok_or(LocalError::MissingRuntimeDirectory)?; + Ok(directory.join("control.sock")) +} + +/// One-instance listener that removes only its own socket on orderly drop. +#[derive(Debug)] +pub struct OwnedListener { + listener: UnixListener, + path: PathBuf, +} + +impl OwnedListener { + pub fn bind(path: impl Into) -> Result { + let path = path.into(); + if path.exists() { + match UnixStream::connect(&path) { + Ok(_) => return Err(LocalError::AlreadyRunning(path)), + Err(_) => remove_stale_socket(&path)?, + } + } + let listener = UnixListener::bind(&path).map_err(|source| LocalError::Socket { + path: path.clone(), + source, + })?; + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).map_err(|source| { + LocalError::Socket { + path: path.clone(), + source, + } + })?; + listener + .set_nonblocking(true) + .map_err(|source| LocalError::Socket { + path: path.clone(), + source, + })?; + Ok(Self { listener, path }) + } + + pub fn accept(&self) -> Result, LocalError> { + match self.listener.accept() { + Ok((stream, _)) => Ok(Some(stream)), + Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(None), + Err(source) => Err(LocalError::Socket { + path: self.path.clone(), + source, + }), + } + } + + #[must_use] + pub fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for OwnedListener { + fn drop(&mut self) { + let _ = fs::remove_file(&self.path); + } +} + +/// Sends one bounded request and waits for its corresponding response. +pub fn client_request( + socket: &Path, + request: &ClientRequest, +) -> Result { + validate_socket(socket)?; + let mut stream = UnixStream::connect(socket).map_err(|source| LocalError::Socket { + path: socket.to_owned(), + source, + })?; + stream + .set_read_timeout(Some(CLIENT_TIMEOUT)) + .and_then(|()| stream.set_write_timeout(Some(CLIENT_TIMEOUT))) + .map_err(|source| LocalError::Socket { + path: socket.to_owned(), + source, + })?; + write_frame(&mut stream, request)?; + let response: ServerResponse = read_frame(&mut stream)?; + if response.version != PROTOCOL_VERSION { + return Err(LocalError::Protocol { + actual: response.version, + expected: PROTOCOL_VERSION, + }); + } + if response.request_id != request.request_id { + return Err(LocalError::RequestId { + actual: response.request_id, + expected: request.request_id, + }); + } + Ok(response) +} + +/// Persistent local server joining the Pulse owner thread on drop. +#[derive(Debug)] +pub struct LocalServer { + listener: OwnedListener, + worker: PulseWorker, + mixer: LiveMixerState, +} + +impl LocalServer { + pub fn pulse(socket: impl Into, write_ceiling: Gain) -> Result { + Ok(Self { + listener: OwnedListener::bind(socket)?, + worker: PulseWorker::spawn(BackendEpoch::new(1), 256), + mixer: LiveMixerState::new(write_ceiling, "pulse"), + }) + } + + /// Runs until process termination or a fatal worker/socket error. + pub fn run(&mut self) -> Result<(), LocalError> { + loop { + self.tick()?; + } + } + + pub fn tick(&mut self) -> Result<(), LocalError> { + match self.worker.receive_timeout(SERVER_TICK) { + Ok(event) => { + let commands = self.mixer.worker_event(event)?; + self.submit(commands)?; + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return Err(LocalError::WorkerDisconnected), + } + while let Some(mut client) = self.listener.accept()? { + let _ = client.set_read_timeout(Some(CLIENT_TIMEOUT)); + let _ = client.set_write_timeout(Some(CLIENT_TIMEOUT)); + if let Err(error) = self.serve_client(&mut client) + && matches!(error, LocalError::WorkerCommand) + { + return Err(error); + } + } + Ok(()) + } + + fn serve_client(&mut self, stream: &mut UnixStream) -> Result<(), LocalError> { + let request: ClientRequest = read_frame(stream)?; + let request_id = request.request_id; + let response = match self.mixer.request(request) { + Ok((response, commands)) => { + self.submit(commands)?; + response + } + Err(error) => ServerResponse { + version: PROTOCOL_VERSION, + request_id, + result: ResponseResult::Error { + message: error.to_string(), + resync: true, + }, + }, + }; + write_frame(stream, &response)?; + Ok(()) + } + + fn submit(&self, commands: Vec) -> Result<(), LocalError> { + for command in commands { + self.worker + .try_submit(command) + .map_err(|_| LocalError::WorkerCommand)?; + } + Ok(()) + } +} + +fn validate_socket(path: &Path) -> Result<(), LocalError> { + let metadata = fs::symlink_metadata(path).map_err(|source| LocalError::Socket { + path: path.to_owned(), + source, + })?; + if !metadata.file_type().is_socket() { + return Err(LocalError::UnsafeSocket { + path: path.to_owned(), + reason: "path is not a Unix socket".to_owned(), + }); + } + if metadata.uid() != rustix::process::getuid().as_raw() { + return Err(LocalError::UnsafeSocket { + path: path.to_owned(), + reason: "socket is owned by another user".to_owned(), + }); + } + if metadata.mode() & 0o777 != 0o600 { + return Err(LocalError::UnsafeSocket { + path: path.to_owned(), + reason: "socket permissions must be 0600".to_owned(), + }); + } + Ok(()) +} + +fn remove_stale_socket(path: &Path) -> Result<(), LocalError> { + validate_socket(path)?; + fs::remove_file(path).map_err(|source| LocalError::Socket { + path: path.to_owned(), + source, + }) +} diff --git a/fader_master/tests/local_socket.rs b/fader_master/tests/local_socket.rs new file mode 100644 index 0000000..1c48092 --- /dev/null +++ b/fader_master/tests/local_socket.rs @@ -0,0 +1,80 @@ +use std::{ + fs, + os::unix::fs::{FileTypeExt, PermissionsExt}, + thread, +}; + +use fader_master::{ + ipc::{ClientRequest, PROTOCOL_VERSION, RequestCommand, ResponseResult, ServerResponse}, + local::{LocalError, OwnedListener, client_request}, +}; + +#[test] +fn listener_is_private_and_prevents_a_second_server() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("control.sock"); + let listener = OwnedListener::bind(&path).unwrap(); + let metadata = fs::metadata(&path).unwrap(); + assert!(metadata.file_type().is_socket()); + assert_eq!(metadata.permissions().mode() & 0o777, 0o600); + assert!(matches!( + OwnedListener::bind(&path), + Err(LocalError::AlreadyRunning(_)) + )); + drop(listener); + assert!(!path.exists()); +} + +#[test] +fn client_rejects_a_socket_with_wrong_permissions() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("control.sock"); + let listener = OwnedListener::bind(&path).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o666)).unwrap(); + let request = ClientRequest { + version: PROTOCOL_VERSION, + request_id: 1, + command: RequestCommand::Snapshot, + }; + assert!(matches!( + client_request(&path, &request), + Err(LocalError::UnsafeSocket { .. }) + )); + drop(listener); +} + +#[test] +fn client_validates_correlated_versioned_response() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("control.sock"); + let listener = OwnedListener::bind(&path).unwrap(); + let request = ClientRequest { + version: PROTOCOL_VERSION, + request_id: 77, + command: RequestCommand::Snapshot, + }; + let server = thread::spawn(move || { + loop { + if let Some(mut stream) = listener.accept().unwrap() { + let received: ClientRequest = fader_master::ipc::read_frame(&mut stream).unwrap(); + fader_master::ipc::write_frame( + &mut stream, + &ServerResponse { + version: PROTOCOL_VERSION, + request_id: received.request_id, + result: ResponseResult::Error { + message: "fixture".into(), + resync: false, + }, + }, + ) + .unwrap(); + break; + } + thread::yield_now(); + } + }); + let response = client_request(&path, &request).unwrap(); + assert_eq!(response.request_id, 77); + server.join().unwrap(); +}