Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand All @@ -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",
Expand Down
15 changes: 15 additions & 0 deletions cosmic-comp-ipc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"]
108 changes: 108 additions & 0 deletions cosmic-comp-ipc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<String, String> },
}

#[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<Option<UnixStream>, Error> {
if let Ok(fd_num) = std::env::var("COSMIC_SESSION_SOCK")
&& let Ok(fd) = fd_num.parse::<RawFd>()
{
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<String, String>), 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<W: io::Write>(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<R: io::Read>(reader: &mut R) -> Result<Message, Error> {
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)
}
33 changes: 33 additions & 0 deletions cosmic-comp-ipc/src/nonblocking.rs
Original file line number Diff line number Diff line change
@@ -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<Output = std::io::Result<()>>;
}

/// Encode and write a cosmic-comp ipc message to a given `futures_io` compatible writer.
pub async fn write_msg<W: AsyncWrite>(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<R: AsyncRead + Readable>(mut reader: Pin<&mut R>) -> Result<Message, Error> {
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)
}
11 changes: 8 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Expand Down Expand Up @@ -156,8 +156,12 @@ pub fn run(hooks: crate::hooks::Hooks) -> Result<(), Box<dyn Error>> {
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
Expand All @@ -174,6 +178,7 @@ pub fn run(hooks: crate::hooks::Hooks) -> Result<(), Box<dyn Error>> {
socket,
event_loop.handle(),
event_loop.get_signal(),
session_sock,
with_xwayland,
kiosk_command,
);
Expand Down
Loading
Loading