From 0f0123058fea282804da279b477f5e818dd9a1ae Mon Sep 17 00:00:00 2001 From: Victoria Brekenfeld Date: Tue, 10 Nov 2026 15:24:24 +0100 Subject: [PATCH] crate: Introduce cosmic-comp-ipc --- Cargo.lock | 12 +++ Cargo.toml | 3 +- cosmic-comp-ipc/Cargo.toml | 15 +++ cosmic-comp-ipc/src/lib.rs | 108 +++++++++++++++++++ cosmic-comp-ipc/src/nonblocking.rs | 33 ++++++ src/lib.rs | 11 +- src/session.rs | 162 ++++++----------------------- src/state.rs | 4 + 8 files changed, 216 insertions(+), 132 deletions(-) create mode 100644 cosmic-comp-ipc/Cargo.toml create mode 100644 cosmic-comp-ipc/src/lib.rs create mode 100644 cosmic-comp-ipc/src/nonblocking.rs diff --git a/Cargo.lock b/Cargo.lock index 33c9329a5..7804ddf64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -678,6 +678,7 @@ dependencies = [ "calloop", "clap_lex", "cosmic-comp-config", + "cosmic-comp-ipc", "cosmic-config", "cosmic-login1-zbus", "cosmic-protocols", @@ -745,6 +746,17 @@ dependencies = [ "tracing", ] +[[package]] +name = "cosmic-comp-ipc" +version = "0.1.0" +dependencies = [ + "futures-util", + "rustix 1.1.6", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "cosmic-config" version = "1.0.0" diff --git a/Cargo.toml b/Cargo.toml index fda3bbde4..84d7a83ae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ version = "1.0.0" rust-version = "1.95" [workspace] -members = ["cosmic-comp-config"] +members = ["cosmic-comp-config", "cosmic-comp-ipc"] [dependencies] anyhow = { version = "1.0.102", features = ["backtrace"] } @@ -17,6 +17,7 @@ cosmic-comp-config = { path = "cosmic-comp-config", features = [ "libdisplay-info", "output", ] } +cosmic-comp-ipc = { path = "cosmic-comp-ipc" } cosmic-config = { git = "https://github.com/pop-os/libcosmic", features = [ "calloop", "macro", diff --git a/cosmic-comp-ipc/Cargo.toml b/cosmic-comp-ipc/Cargo.toml new file mode 100644 index 000000000..948c4e56b --- /dev/null +++ b/cosmic-comp-ipc/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "cosmic-comp-ipc" +version = "0.1.0" +edition = "2024" + +[dependencies] +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +thiserror = "2.0.21" +futures-util = { version = "0.3.34", features = ["io"], optional = true } +rustix = "1.1.6" + +[features] +default = ["async"] +async = ["dep:futures-util"] diff --git a/cosmic-comp-ipc/src/lib.rs b/cosmic-comp-ipc/src/lib.rs new file mode 100644 index 000000000..e01a56879 --- /dev/null +++ b/cosmic-comp-ipc/src/lib.rs @@ -0,0 +1,108 @@ +use serde::{Deserialize, Serialize}; +use std::{ + collections::HashMap, + io, + os::{ + fd::{BorrowedFd, FromRawFd, IntoRawFd, RawFd}, + unix::net::UnixStream, + }, +}; + +#[cfg(feature = "async")] +mod nonblocking; +#[cfg(feature = "async")] +pub use self::nonblocking::*; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "snake_case", tag = "message")] +pub enum Message { + SetEnv { variables: HashMap }, +} + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("Failed to serialize message")] + Serialize(#[source] serde_json::Error), + #[error("Failed to deserialize message")] + Deserialize(#[source] serde_json::Error), + #[error(transparent)] + IO(#[from] io::Error), +} + +unsafe fn set_cloexec(fd: RawFd, set: bool) -> rustix::io::Result<()> { + if fd == -1 { + return Err(rustix::io::Errno::BADF); + } + let fd = unsafe { BorrowedFd::borrow_raw(fd) }; + let flags = rustix::io::fcntl_getfd(fd)?; + if set { + rustix::io::fcntl_setfd(fd, flags | rustix::io::FdFlags::CLOEXEC) + } else { + rustix::io::fcntl_setfd(fd, flags & rustix::io::FdFlags::CLOEXEC.complement()) + } +} + +/// Searches for a passed cosmic session socket and returns a [`UnixStream`] if found. +/// +/// *Note:* If you need an async variant of the socket, use e.g. +/// - [`async_io::Async::new`](https://docs.rs/async-io/latest/async_io/struct.Async.html#method.new) +/// - [`tokio::net::UnixStream::from_std`](https://docs.rs/tokio/latest/tokio/net/struct.UnixStream.html#method.from_std) +pub fn find_ipc_socket() -> Result, Error> { + if let Ok(fd_num) = std::env::var("COSMIC_SESSION_SOCK") + && let Ok(fd) = fd_num.parse::() + { + let res = unsafe { set_cloexec(fd, true) }; + if res.is_err() { + unsafe { rustix::io::close(fd) }; + } + res.map(|()| Some(unsafe { UnixStream::from_raw_fd(fd) })) + .map_err(|err| Error::IO(err.kind().into())) + } else { + Ok(None) + } +} + +/// Creates a socket pair and returns one end as well as a map of env variables +/// to pass to a spawned cosmic-comp instance. +/// +/// *Note:* If you need an async variant of the socket, use e.g. +/// - [`async_io::Async::new`](https://docs.rs/async-io/latest/async_io/struct.Async.html#method.new) +/// - [`tokio::net::UnixStream::from_std`](https://docs.rs/tokio/latest/tokio/net/struct.UnixStream.html#method.from_std) +pub fn setup_socket() -> Result<(UnixStream, HashMap), Error> { + let (session, comp) = UnixStream::pair()?; + let comp_fd = comp.into_raw_fd(); + unsafe { set_cloexec(comp_fd, false) }.map_err(|err| Error::IO(err.kind().into()))?; + let mut env_map = HashMap::new(); + env_map.insert("COSMIC_SESSION_SOCK".to_string(), comp_fd.to_string()); + Ok((session, env_map)) +} + +/// Encode and write a cosmic-comp ipc message to a given `std::io` compatible writer. +/// +/// **Note:** This method does not deal with buffering partial message, +/// as it is meant to be used with unix sockets with provide message +/// atomicity. +pub fn write_msg_blocking(writer: &mut W, msg: &Message) -> Result<(), Error> { + let message = serde_json::to_string(msg).map_err(Error::Serialize)?; + let bytes = message.into_bytes(); + let len = (bytes.len() as u16).to_ne_bytes(); + writer.write_all(&len)?; + writer.write_all(&bytes)?; + writer.flush()?; + Ok(()) +} + +/// Read and parse a cosmic-comp ipc message from a given `std::io` compatible reader. +/// +/// **Note:** This method does not deal with buffering partial message, +/// as it is meant to be used with unix sockets with provide message +/// atomicity. +pub fn read_msg_blocking(reader: &mut R) -> Result { + let mut buf = [0u8; 2]; + reader.read_exact(&mut buf)?; + let len = u16::from_ne_bytes(buf); + + let mut msg_buf = vec![0u8; len as usize]; + reader.read_exact(&mut msg_buf)?; + serde_json::from_slice(&msg_buf).map_err(Error::Deserialize) +} diff --git a/cosmic-comp-ipc/src/nonblocking.rs b/cosmic-comp-ipc/src/nonblocking.rs new file mode 100644 index 000000000..382587168 --- /dev/null +++ b/cosmic-comp-ipc/src/nonblocking.rs @@ -0,0 +1,33 @@ +use std::pin::Pin; + +use crate::{Error, Message}; + +use futures_util::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; + +pub trait Readable { + fn readable(&self) -> impl Future>; +} + +/// Encode and write a cosmic-comp ipc message to a given `futures_io` compatible writer. +pub async fn write_msg(mut writer: Pin<&mut W>, msg: &Message) -> Result<(), Error> { + let message = serde_json::to_string(msg).map_err(Error::Serialize)?; + let bytes = message.into_bytes(); + let len = (bytes.len() as u16).to_ne_bytes(); + writer.write_all(&len).await?; + writer.write_all(&bytes).await?; + writer.flush().await?; + Ok(()) +} + +/// Read and parse a cosmic-comp ipc message from a given `futures_io` compatible reader. +pub async fn read_msg(mut reader: Pin<&mut R>) -> Result { + reader.readable().await?; + let mut buf = [0u8; 2]; + reader.read_exact(&mut buf).await?; + let len = u16::from_ne_bytes(buf); + + reader.readable().await?; + let mut msg_buf = vec![0u8; len as usize]; + reader.read_exact(&mut msg_buf).await?; + serde_json::from_slice(&msg_buf).map_err(Error::Deserialize) +} diff --git a/src/lib.rs b/src/lib.rs index cf75e8ff8..135846705 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -77,7 +77,7 @@ impl State { // potentially tell the session we are setup now if let Err(err) = - session::run_socket(self.common.event_loop_handle.clone(), &self.common) + session::run_socket(self.common.event_loop_handle.clone(), &mut self.common) { warn!(?err, "Failed to setup cosmic-session communication"); } @@ -156,8 +156,12 @@ pub fn run(hooks: crate::hooks::Hooks) -> Result<(), Box> { utils::rlimit::increase_nofile_limit(); // This needs to be done before any potential program launches // (e.g. Xwayland) as it handles passed file descriptors. - if let Err(err) = session::setup_socket() { - warn!("Session error: {:?}", err); + let session_sock = match cosmic_comp_ipc::find_ipc_socket() { + Ok(sock) => sock, + Err(err) => { + warn!("Session error: {:?}", err); + None + } }; // init hook globals @@ -174,6 +178,7 @@ pub fn run(hooks: crate::hooks::Hooks) -> Result<(), Box> { socket, event_loop.handle(), event_loop.get_signal(), + session_sock, with_xwayland, kiosk_command, ); diff --git a/src/session.rs b/src/session.rs index 0b4025a6c..5621a1a37 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1,60 +1,13 @@ // SPDX-License-Identifier: GPL-3.0-only -use smithay::reexports::{ - calloop::{Interest, LoopHandle, Mode, PostAction, generic::Generic}, - rustix, -}; +use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction, generic::Generic}; use anyhow::{Context, Result, anyhow}; -use serde::{Deserialize, Serialize}; -use std::{ - collections::HashMap, - io::{Read, Write}, - os::unix::{ - io::{AsFd, BorrowedFd, FromRawFd, RawFd}, - net::UnixStream, - }, -}; -use tracing::{error, warn}; +use std::collections::HashMap; +use tracing::{error, info, warn}; use crate::state::{Common, State}; - -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "snake_case", tag = "message")] -pub enum Message { - SetEnv { variables: HashMap }, -} - -struct StreamWrapper { - stream: UnixStream, - buffer: Vec, - size: u16, - read_bytes: usize, -} -impl AsFd for StreamWrapper { - fn as_fd(&self) -> BorrowedFd<'_> { - self.stream.as_fd() - } -} -impl From for StreamWrapper { - fn from(stream: UnixStream) -> StreamWrapper { - StreamWrapper { - stream, - buffer: Vec::new(), - size: 0, - read_bytes: 0, - } - } -} - -unsafe fn set_cloexec(fd: RawFd) -> rustix::io::Result<()> { - if fd == -1 { - return Err(rustix::io::Errno::BADF); - } - let fd = unsafe { BorrowedFd::borrow_raw(fd) }; - let flags = rustix::io::fcntl_getfd(fd)?; - rustix::io::fcntl_setfd(fd, flags | rustix::io::FdFlags::CLOEXEC) -} +use cosmic_comp_ipc::Message; pub fn get_env(common: &Common) -> Result> { let mut env = HashMap::new(); @@ -72,90 +25,43 @@ pub fn get_env(common: &Common) -> Result> { Ok(env) } -pub fn setup_socket() -> Result<()> { - if let Ok(fd_num) = std::env::var("COSMIC_SESSION_SOCK") - && let Ok(fd) = fd_num.parse::() - { - let res = unsafe { set_cloexec(fd) }.with_context(|| "Failed to setup session socket"); - if res.is_err() { - unsafe { rustix::io::close(fd) }; - } - res - } else { - Ok(()) - } -} - -pub fn run_socket(handle: LoopHandle, common: &Common) -> Result<()> { - if let Ok(fd_num) = std::env::var("COSMIC_SESSION_SOCK") { - if let Ok(fd) = fd_num.parse::() { - let mut session_socket = unsafe { UnixStream::from_raw_fd(fd) }; +pub fn run_socket(handle: LoopHandle, common: &mut Common) -> Result<()> { + let Some(mut socket) = common.session_sock.take() else { + return Ok(()); + }; + info!("Found cosmic-comp ipc socket"); - let env = get_env(common)?; - let message = serde_json::to_string(&Message::SetEnv { variables: env }) - .with_context(|| "Failed to encode environment variables into json")?; - let bytes = message.into_bytes(); - let len = (bytes.len() as u16).to_ne_bytes(); - session_socket - .write_all(&len) - .with_context(|| "Failed to write message len")?; - session_socket - .write_all(&bytes) - .with_context(|| "Failed to write message bytes")?; + let env = get_env(common)?; + let message = Message::SetEnv { variables: env }; + cosmic_comp_ipc::write_msg_blocking(&mut socket, &message) + .context("Failed to send session ipc message")?; - handle.insert_source( - Generic::new(StreamWrapper::from(session_socket), Interest::READ, Mode::Level), - move |_, stream, _state| { - // SAFETY: We don't drop the stream! - let stream = unsafe { stream.get_mut() }; + handle + .insert_source( + Generic::new(socket, Interest::READ, Mode::Level), + move |_, stream, _state| { + // SAFETY: We don't drop the stream! + let stream = unsafe { stream.get_mut() }; - if stream.size == 0 { - let mut len = [0u8; 2]; - match stream.stream.read_exact(&mut len) { - Ok(()) => { - stream.size = u16::from_ne_bytes(len); - stream.buffer = vec![0; stream.size as usize]; - }, - Err(err) => { - warn!(?err, "Error reading from session socket"); - return Ok(PostAction::Remove); - } + match cosmic_comp_ipc::read_msg_blocking(stream) { + Ok(msg) => match msg { + Message::SetEnv { .. } => { + warn!("Got SetEnv from session? What is this?"); + Ok(PostAction::Continue) } + }, + Err(cosmic_comp_ipc::Error::IO(err)) => { + error!(?err, "Error reading from session socket"); + Ok(PostAction::Remove) } - - stream.read_bytes += match stream.stream.read(&mut stream.buffer) { - Ok(size) => size, - Err(err) => { - error!(?err, "Error reading from session socket"); - return Ok(PostAction::Remove); - } - }; - - if stream.read_bytes != 0 && stream.read_bytes == stream.size as usize { - stream.size = 0; - stream.read_bytes = 0; - match std::str::from_utf8(&stream.buffer) { - Ok(message) => { - match serde_json::from_str::<'_, Message>(message) { - Ok(Message::SetEnv { .. }) => warn!("Got SetEnv from session? What is this?"), - _ => warn!("Unknown session socket message, are you using incompatible cosmic-session and cosmic-comp versions?"), - }; - Ok(PostAction::Continue) - }, - Err(err) => { - warn!(?err, "Invalid message from session sock"); - Ok(PostAction::Continue) - } - } - } else { + Err(err) => { + warn!(?err, "Invalid message from session sock"); Ok(PostAction::Continue) } - }, - ).with_context(|| "Failed to init the cosmic session socket source")?; - } else { - error!(socket = fd_num, "COSMIC_SESSION_SOCK is no valid RawFd."); - } - }; + } + }, + ) + .with_context(|| "Failed to init the cosmic session socket source")?; Ok(()) } diff --git a/src/state.rs b/src/state.rs index ec0122617..e88f00cca 100644 --- a/src/state.rs +++ b/src/state.rs @@ -128,6 +128,7 @@ use std::{ cmp::min, collections::HashSet, ffi::OsString, + os::unix::net::UnixStream, process::{Child, Command}, sync::{Arc, LazyLock, Once, atomic::AtomicBool}, time::{Duration, Instant}, @@ -238,6 +239,7 @@ pub struct Common { pub display_handle: DisplayHandle, pub event_loop_handle: LoopHandle<'static, State>, pub event_loop_signal: LoopSignal, + pub session_sock: Option, pub popups: PopupManager, pub shell: Arc>, @@ -661,6 +663,7 @@ impl State { socket: OsString, handle: LoopHandle<'static, State>, signal: LoopSignal, + session_sock: Option, with_xwayland: bool, kiosk_command: Option, ) -> State { @@ -779,6 +782,7 @@ impl State { display_handle: dh.clone(), event_loop_handle: handle, event_loop_signal: signal, + session_sock, popups: PopupManager::default(), shell,