forge
Explore
Log in

Don't you dare go Hollow

`niri_ipc::Socket`; `niri msg version`; version checking on IPC (#278)

Browse files at this commit

b5f7e4bd83dbfc77e0c8b973bc217c9a4cb3f364Unverifiedsodiboo and Ivan MolodetskikhParent: b98b958
* Implement version checking in IPC

implement version checking; streamed IPC

streamed IPC will allow multiple requests per connection

add nonsense request

change inline struct to json macro

only check version if request actually fails

fix usage of inspect_err (MSRV 1.72.0; stabilized 1.76.0)

"nonsense request" -> "return error"

oneshot connections

* Change some things around

* Unqualify niri_ipc::Transform

---------
Cargo.lockmodified+1 -0
@@ -2202,6 +2202,7 @@ version = "0.1.4"
22022202 dependencies = [
22032203 "clap",
22042204 "serde",
2205+ "serde_json",
22052206 ]
22062207
22072208 [[package]]
Cargo.tomlmodified+2 -1
@@ -14,6 +14,7 @@ anyhow = "1.0.81"
1414 bitflags = "2.5.0"
1515 clap = { version = "~4.4.18", features = ["derive"] }
1616 serde = { version = "1.0.197", features = ["derive"] }
17+serde_json = "1.0.115"
1718 tracing = { version = "0.1.40", features = ["max_level_trace", "release_max_level_debug"] }
1819 tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
1920 tracy-client = { version = "0.17.0", default-features = false }
@@ -67,7 +68,7 @@ portable-atomic = { version = "1.6.0", default-features = false, features = ["fl
6768 profiling = "1.0.15"
6869 sd-notify = "0.4.1"
6970 serde.workspace = true
70-serde_json = "1.0.115"
71+serde_json.workspace = true
7172 smithay-drm-extras.workspace = true
7273 tracing-subscriber.workspace = true
7374 tracing.workspace = true
niri-ipc/Cargo.tomlmodified+1 -0
@@ -10,6 +10,7 @@ repository.workspace = true
1010 [dependencies]
1111 clap = { workspace = true, optional = true }
1212 serde.workspace = true
13+serde_json.workspace = true
1314
1415 [features]
1516 clap = ["dep:clap"]
niri-ipc/src/lib.rsmodified+8 -2
@@ -6,18 +6,22 @@ use std::str::FromStr;
66
77 use serde::{Deserialize, Serialize};
88
9-/// Name of the environment variable containing the niri IPC socket path.
10-pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET";
9+mod socket;
10+pub use socket::{Socket, SOCKET_PATH_ENV};
1111
1212 /// Request from client to niri.
1313 #[derive(Debug, Serialize, Deserialize, Clone)]
1414 pub enum Request {
15+ /// Request the version string for the running niri instance.
16+ Version,
1517 /// Request information about connected outputs.
1618 Outputs,
1719 /// Request information about the focused window.
1820 FocusedWindow,
1921 /// Perform an action.
2022 Action(Action),
23+ /// Respond with an error (for testing error handling).
24+ ReturnError,
2125 }
2226
2327 /// Reply from niri to client.
@@ -35,6 +39,8 @@ pub type Reply = Result<Response, String>;
3539 pub enum Response {
3640 /// A request that does not need a response was handled successfully.
3741 Handled,
42+ /// The version string for the running niri instance.
43+ Version(String),
3844 /// Information about connected outputs.
3945 ///
4046 /// Map from connector name to output info.
niri-ipc/src/socket.rsadded+63 -0
@@ -0,0 +1,63 @@
1+//! Helper for blocking communication over the niri socket.
2+
3+use std::env;
4+use std::io::{self, Read, Write};
5+use std::net::Shutdown;
6+use std::os::unix::net::UnixStream;
7+use std::path::Path;
8+
9+use crate::{Reply, Request};
10+
11+/// Name of the environment variable containing the niri IPC socket path.
12+pub const SOCKET_PATH_ENV: &str = "NIRI_SOCKET";
13+
14+/// Helper for blocking communication over the niri socket.
15+///
16+/// This struct is used to communicate with the niri IPC server. It handles the socket connection
17+/// and serialization/deserialization of messages.
18+pub struct Socket {
19+ stream: UnixStream,
20+}
21+
22+impl Socket {
23+ /// Connects to the default niri IPC socket.
24+ ///
25+ /// This is equivalent to calling [`Self::connect_to`] with the path taken from the
26+ /// [`SOCKET_PATH_ENV`] environment variable.
27+ pub fn connect() -> io::Result<Self> {
28+ let socket_path = env::var_os(SOCKET_PATH_ENV).ok_or_else(|| {
29+ io::Error::new(
30+ io::ErrorKind::NotFound,
31+ format!("{SOCKET_PATH_ENV} is not set, are you running this within niri?"),
32+ )
33+ })?;
34+ Self::connect_to(socket_path)
35+ }
36+
37+ /// Connects to the niri IPC socket at the given path.
38+ pub fn connect_to(path: impl AsRef<Path>) -> io::Result<Self> {
39+ let stream = UnixStream::connect(path.as_ref())?;
40+ Ok(Self { stream })
41+ }
42+
43+ /// Sends a request to niri and returns the response.
44+ ///
45+ /// Return values:
46+ ///
47+ /// * `Ok(Ok(response))`: successful [`Response`](crate::Response) from niri
48+ /// * `Ok(Err(message))`: error message from niri
49+ /// * `Err(error)`: error communicating with niri
50+ pub fn send(self, request: Request) -> io::Result<Reply> {
51+ let Self { mut stream } = self;
52+
53+ let mut buf = serde_json::to_vec(&request).unwrap();
54+ stream.write_all(&buf)?;
55+ stream.shutdown(Shutdown::Write)?;
56+
57+ buf.clear();
58+ stream.read_to_end(&mut buf)?;
59+
60+ let reply = serde_json::from_slice(&buf)?;
61+ Ok(reply)
62+ }
63+}
src/cli.rsmodified+4 -0
@@ -52,6 +52,8 @@ pub enum Sub {
5252
5353 #[derive(Subcommand)]
5454 pub enum Msg {
55+ /// Print the version of the running niri instance.
56+ Version,
5557 /// List connected outputs.
5658 Outputs,
5759 /// Print information about the focused window.
@@ -61,4 +63,6 @@ pub enum Msg {
6163 #[command(subcommand)]
6264 action: Action,
6365 },
66+ /// Request an error from the running niri instance.
67+ RequestError,
6468 }
src/ipc/client.rsmodified+84 -43
@@ -1,54 +1,99 @@
1-use std::env;
2-use std::io::{Read, Write};
3-use std::net::Shutdown;
4-use std::os::unix::net::UnixStream;
5-
61 use anyhow::{anyhow, bail, Context};
7-use niri_ipc::{LogicalOutput, Mode, Output, Reply, Request, Response};
2+use niri_ipc::{LogicalOutput, Mode, Output, Request, Response, Socket, Transform};
3+use serde_json::json;
84
95 use crate::cli::Msg;
6+use crate::utils::version;
107
118 pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
12- let socket_path = env::var_os(niri_ipc::SOCKET_PATH_ENV).with_context(|| {
13- format!(
14- "{} is not set, are you running this within niri?",
15- niri_ipc::SOCKET_PATH_ENV
16- )
17- })?;
18-
19- let mut stream =
20- UnixStream::connect(socket_path).context("error connecting to {socket_path}")?;
21-
229 let request = match &msg {
10+ Msg::Version => Request::Version,
2311 Msg::Outputs => Request::Outputs,
2412 Msg::FocusedWindow => Request::FocusedWindow,
2513 Msg::Action { action } => Request::Action(action.clone()),
14+ Msg::RequestError => Request::ReturnError,
2615 };
27- let mut buf = serde_json::to_vec(&request).unwrap();
28- stream
29- .write_all(&buf)
30- .context("error writing IPC request")?;
31- stream
32- .shutdown(Shutdown::Write)
33- .context("error closing IPC stream for writing")?;
3416
35- buf.clear();
36- stream
37- .read_to_end(&mut buf)
38- .context("error reading IPC response")?;
17+ let socket = Socket::connect().context("error connecting to the niri socket")?;
3918
40- let reply: Reply = serde_json::from_slice(&buf).context("error parsing IPC reply")?;
19+ let reply = socket
20+ .send(request)
21+ .context("error communicating with niri")?;
4122
42- let response = reply
43- .map_err(|msg| anyhow!(msg))
44- .context("niri could not handle the request")?;
23+ let compositor_version = match reply {
24+ Err(_) if !matches!(msg, Msg::Version) => {
25+ // If we got an error, it might be that the CLI is a different version from the running
26+ // niri instance. Request the running instance version to compare and print a message.
27+ Socket::connect()
28+ .and_then(|socket| socket.send(Request::Version))
29+ .ok()
30+ }
31+ _ => None,
32+ };
4533
4634 // Default SIGPIPE so that our prints don't panic on stdout closing.
4735 unsafe {
4836 libc::signal(libc::SIGPIPE, libc::SIG_DFL);
4937 }
5038
39+ let response = reply.map_err(|err_msg| {
40+ // Check for CLI-server version mismatch to add helpful context.
41+ match compositor_version {
42+ Some(Ok(Response::Version(compositor_version))) => {
43+ let cli_version = version();
44+ if cli_version != compositor_version {
45+ eprintln!("Running niri compositor has a different version from the niri CLI:");
46+ eprintln!("Compositor version: {compositor_version}");
47+ eprintln!("CLI version: {cli_version}");
48+ eprintln!("Did you forget to restart niri after an update?");
49+ eprintln!();
50+ }
51+ }
52+ Some(_) => {
53+ eprintln!("Unable to get the running niri compositor version.");
54+ eprintln!("Did you forget to restart niri after an update?");
55+ eprintln!();
56+ }
57+ None => {
58+ // Communication error, or the original request was already a version request.
59+ // Don't add irrelevant context.
60+ }
61+ }
62+
63+ anyhow!(err_msg).context("niri returned an error")
64+ })?;
65+
5166 match msg {
67+ Msg::RequestError => {
68+ bail!("unexpected response: expected an error, got {response:?}");
69+ }
70+ Msg::Version => {
71+ let Response::Version(compositor_version) = response else {
72+ bail!("unexpected response: expected Version, got {response:?}");
73+ };
74+
75+ let cli_version = version();
76+
77+ if json {
78+ println!(
79+ "{}",
80+ json!({
81+ "compositor": compositor_version,
82+ "cli": cli_version,
83+ })
84+ );
85+ return Ok(());
86+ }
87+
88+ if cli_version != compositor_version {
89+ eprintln!("Running niri compositor has a different version from the niri CLI.");
90+ eprintln!("Did you forget to restart niri after an update?");
91+ eprintln!();
92+ }
93+
94+ println!("Compositor version: {compositor_version}");
95+ println!("CLI version: {cli_version}");
96+ }
5297 Msg::Outputs => {
5398 let Response::Outputs(outputs) = response else {
5499 bail!("unexpected response: expected Outputs, got {response:?}");
@@ -123,18 +168,14 @@ pub fn handle_msg(msg: Msg, json: bool) -> anyhow::Result<()> {
123168 println!(" Scale: {scale}");
124169
125170 let transform = match transform {
126- niri_ipc::Transform::Normal => "normal",
127- niri_ipc::Transform::_90 => "90° counter-clockwise",
128- niri_ipc::Transform::_180 => "180°",
129- niri_ipc::Transform::_270 => "270° counter-clockwise",
130- niri_ipc::Transform::Flipped => "flipped horizontally",
131- niri_ipc::Transform::Flipped90 => {
132- "90° counter-clockwise, flipped horizontally"
133- }
134- niri_ipc::Transform::Flipped180 => "flipped vertically",
135- niri_ipc::Transform::Flipped270 => {
136- "270° counter-clockwise, flipped horizontally"
137- }
171+ Transform::Normal => "normal",
172+ Transform::_90 => "90° counter-clockwise",
173+ Transform::_180 => "180°",
174+ Transform::_270 => "270° counter-clockwise",
175+ Transform::Flipped => "flipped horizontally",
176+ Transform::Flipped90 => "90° counter-clockwise, flipped horizontally",
177+ Transform::Flipped180 => "flipped vertically",
178+ Transform::Flipped270 => "270° counter-clockwise, flipped horizontally",
138179 };
139180 println!(" Transform: {transform}");
140181 }
src/ipc/server.rsmodified+17 -8
@@ -8,7 +8,7 @@ use calloop::io::Async;
88 use directories::BaseDirs;
99 use futures_util::io::{AsyncReadExt, BufReader};
1010 use futures_util::{AsyncBufReadExt, AsyncWriteExt};
11-use niri_ipc::{Request, Response};
11+use niri_ipc::{Reply, Request, Response};
1212 use smithay::desktop::Window;
1313 use smithay::reexports::calloop::generic::Generic;
1414 use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
@@ -18,6 +18,7 @@ use smithay::wayland::shell::xdg::XdgToplevelSurfaceData;
1818
1919 use crate::backend::IpcOutputMap;
2020 use crate::niri::State;
21+use crate::utils::version;
2122
2223 pub struct IpcServer {
2324 pub socket_path: PathBuf,
@@ -114,10 +115,18 @@ async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow:
114115 .await
115116 .context("error reading request")?;
116117
117- let reply = process(&ctx, &buf).map_err(|err| {
118- warn!("error processing IPC request: {err:?}");
119- err.to_string()
120- });
118+ let request = serde_json::from_str(&buf)
119+ .context("error parsing request")
120+ .map_err(|err| err.to_string());
121+ let requested_error = matches!(request, Ok(Request::ReturnError));
122+
123+ let reply = request.and_then(|request| process(&ctx, request));
124+
125+ if let Err(err) = &reply {
126+ if !requested_error {
127+ warn!("error processing IPC request: {err:?}");
128+ }
129+ }
121130
122131 let buf = serde_json::to_vec(&reply).context("error formatting reply")?;
123132 write.write_all(&buf).await.context("error writing reply")?;
@@ -125,10 +134,10 @@ async fn handle_client(ctx: ClientCtx, stream: Async<'_, UnixStream>) -> anyhow:
125134 Ok(())
126135 }
127136
128-fn process(ctx: &ClientCtx, buf: &str) -> anyhow::Result<Response> {
129- let request: Request = serde_json::from_str(buf).context("error parsing request")?;
130-
137+fn process(ctx: &ClientCtx, request: Request) -> Reply {
131138 let response = match request {
139+ Request::ReturnError => return Err(String::from("example compositor error")),
140+ Request::Version => Response::Version(version()),
132141 Request::Outputs => {
133142 let ipc_outputs = ctx.ipc_outputs.lock().unwrap().clone();
134143 Response::Outputs(ipc_outputs)